@adport/provider-google 0.12.1 → 0.13.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 +159 -3
- package/dist/index.js +1363 -552
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -6,12 +6,12 @@ var isDataManagerFieldPath = (value) => typeof value === "string" && value.lengt
|
|
|
6
6
|
var TOKEN_URL = "https://oauth2.googleapis.com/token";
|
|
7
7
|
var API_BASE = "https://googleads.googleapis.com";
|
|
8
8
|
var DEFAULT_API_VERSION = "v25";
|
|
9
|
-
function normalizeCustomerId(
|
|
10
|
-
const
|
|
11
|
-
if (!/^\d{10}$/.test(
|
|
12
|
-
throw new AdportError("INVALID_INPUT", `"${
|
|
9
|
+
function normalizeCustomerId(id11) {
|
|
10
|
+
const normalized2 = id11.replace(/^customers\//, "").replace(/-/g, "").trim();
|
|
11
|
+
if (!/^\d{10}$/.test(normalized2)) {
|
|
12
|
+
throw new AdportError("INVALID_INPUT", `"${id11}" is not a valid Google Ads customer id (expected 10 digits).`);
|
|
13
13
|
}
|
|
14
|
-
return
|
|
14
|
+
return normalized2;
|
|
15
15
|
}
|
|
16
16
|
var GoogleAdsRestClient = class {
|
|
17
17
|
constructor(credentials, version = process.env.GOOGLE_ADS_API_VERSION ?? DEFAULT_API_VERSION, fetchImpl = fetch) {
|
|
@@ -98,10 +98,10 @@ var GoogleAdsRestClient = class {
|
|
|
98
98
|
throw new AdportError("PROVIDER_ERROR", "google: invalid Data Manager response; do not assume ingestion or retry automatically");
|
|
99
99
|
}
|
|
100
100
|
if (!response.ok) {
|
|
101
|
-
const
|
|
102
|
-
const error =
|
|
101
|
+
const object7 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
102
|
+
const error = object7(object7(body).error), details = Array.isArray(error.details) ? error.details.map(object7) : [];
|
|
103
103
|
const reasons = details.flatMap((value) => typeof value.reason === "string" && /^[A-Z][A-Z0-9_]{0,127}$/.test(value.reason) ? [value.reason] : []).slice(0, 30);
|
|
104
|
-
const fields5 = details.flatMap((value) => Array.isArray(value.fieldViolations) ? value.fieldViolations.map(
|
|
104
|
+
const fields5 = details.flatMap((value) => Array.isArray(value.fieldViolations) ? value.fieldViolations.map(object7).flatMap((item) => isDataManagerFieldPath(item.field) ? [item.field] : []) : []).slice(0, 100);
|
|
105
105
|
const status = typeof error.status === "string" && /^[A-Z_]{1,64}$/.test(error.status) ? error.status : "UNKNOWN";
|
|
106
106
|
throw new AdportError("PROVIDER_ERROR", `google: Data Manager rejected the request (HTTP ${response.status}; ${status}${reasons.length ? `; ${reasons.join(", ")}` : ""}). No automatic retry.`, { http_status: response.status, status, reasons, fields: fields5 });
|
|
107
107
|
}
|
|
@@ -185,7 +185,16 @@ var GoogleAdsRestClient = class {
|
|
|
185
185
|
*/
|
|
186
186
|
async mutate(customerId, service, operations, { validateOnly, responseContentType }) {
|
|
187
187
|
const body = { operations, validateOnly, ...responseContentType ? { responseContentType } : {} };
|
|
188
|
-
|
|
188
|
+
const atomicOnly = [
|
|
189
|
+
"customerManagerLinks",
|
|
190
|
+
"assetGroups",
|
|
191
|
+
"assetGroupListingGroupFilters",
|
|
192
|
+
"customConversionGoals",
|
|
193
|
+
"campaignConversionGoals",
|
|
194
|
+
"customerConversionGoals",
|
|
195
|
+
"conversionGoalCampaignConfigs"
|
|
196
|
+
];
|
|
197
|
+
if (!atomicOnly.includes(service)) body.partialFailure = false;
|
|
189
198
|
return this.request(`customers/${normalizeCustomerId(customerId)}/${service}:mutate`, {
|
|
190
199
|
method: "POST",
|
|
191
200
|
body
|
|
@@ -220,6 +229,11 @@ function safeJson(raw) {
|
|
|
220
229
|
return raw;
|
|
221
230
|
}
|
|
222
231
|
}
|
|
232
|
+
function isGoogleAdsRejection(error) {
|
|
233
|
+
if (!(error instanceof AdportError)) return false;
|
|
234
|
+
const failure = error.details?.error;
|
|
235
|
+
return typeof failure?.code === "number" && failure.code >= 400 && failure.code < 500 && Array.isArray(failure.details) && failure.details.some((item) => Array.isArray(item?.errors) && item.errors.length > 0);
|
|
236
|
+
}
|
|
223
237
|
function formatGoogleAdsError(status, raw) {
|
|
224
238
|
const parsed = safeJson(raw);
|
|
225
239
|
const error = parsed?.error;
|
|
@@ -243,7 +257,7 @@ function formatGoogleAdsError(status, raw) {
|
|
|
243
257
|
import {
|
|
244
258
|
creativeStatusAction as creativeStatusAction2,
|
|
245
259
|
creativesOutput as creativesOutput3,
|
|
246
|
-
AdportError as
|
|
260
|
+
AdportError as AdportError13,
|
|
247
261
|
resolveDateRange
|
|
248
262
|
} from "@adport/core";
|
|
249
263
|
|
|
@@ -917,61 +931,356 @@ function googleConversionTools(provider) {
|
|
|
917
931
|
];
|
|
918
932
|
}
|
|
919
933
|
|
|
920
|
-
// src/
|
|
934
|
+
// src/conversion-goals.ts
|
|
921
935
|
import { createHash as createHash3 } from "crypto";
|
|
922
936
|
import { AdportError as AdportError6, defineTool as defineTool5, guardedWriteTool as guardedWriteTool5 } from "@adport/core";
|
|
923
937
|
import { z as z5 } from "zod";
|
|
924
|
-
var object2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
925
938
|
var id5 = z5.string().regex(/^[1-9]\d*$/);
|
|
926
939
|
var hash3 = z5.string().regex(/^[a-f0-9]{64}$/);
|
|
927
|
-
var
|
|
928
|
-
var
|
|
929
|
-
var
|
|
930
|
-
var
|
|
931
|
-
var
|
|
932
|
-
var
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
z5.object({
|
|
940
|
+
var ORIGINS = ["WEBSITE", "GOOGLE_HOSTED", "APP", "CALL_FROM_ADS", "STORE", "YOUTUBE_HOSTED", "LOCAL_SERVICES_ADS"];
|
|
941
|
+
var unique = (values) => new Set(values).size === values.length;
|
|
942
|
+
var campaignIds = z5.array(id5).min(1).max(50).refine(unique, "Campaign IDs must be unique");
|
|
943
|
+
var actionIds = z5.array(id5).min(1).max(100).refine(unique, "Conversion action IDs must be unique");
|
|
944
|
+
var goalName = z5.string().trim().min(1).max(255);
|
|
945
|
+
var createGoal = z5.object({ name: goalName, conversion_action_ids: actionIds });
|
|
946
|
+
var toggle = z5.object({ category: z5.string().regex(/^[A-Z][A-Z0-9_]{1,63}$/), origin: z5.enum(ORIGINS), biddable: z5.boolean() }).strict();
|
|
947
|
+
var target3 = z5.discriminatedUnion("type", [
|
|
948
|
+
z5.object({ type: z5.literal("CUSTOM_GOAL"), custom_conversion_goal_id: id5, expected_goal_hash: hash3 }).strict(),
|
|
949
|
+
z5.object({ type: z5.literal("ACCOUNT_DEFAULT") }).strict()
|
|
950
|
+
]);
|
|
951
|
+
var setGoal = z5.object({ campaign_ids: campaignIds, expected_snapshot_hash: hash3, goal: target3.optional(), standard_goals: z5.union([z5.literal("DISABLE_ALL"), z5.array(toggle).min(1).max(100)]).optional() }).superRefine((value, ctx) => {
|
|
952
|
+
if (!value.goal && !value.standard_goals) ctx.addIssue({ code: "custom", message: "Supply goal, standard_goals or both" });
|
|
953
|
+
if (value.goal?.type === "ACCOUNT_DEFAULT" && value.standard_goals) ctx.addIssue({ code: "custom", message: "ACCOUNT_DEFAULT restores account goals; standard_goals would switch the campaigns back to campaign-level goals" });
|
|
954
|
+
if (Array.isArray(value.standard_goals) && !unique(value.standard_goals.map((item) => `${item.category}~${item.origin}`))) ctx.addIssue({ code: "custom", message: "Each category/origin pair can appear once" });
|
|
955
|
+
});
|
|
956
|
+
var goalFields = "custom_conversion_goal.resource_name, custom_conversion_goal.id, custom_conversion_goal.name, custom_conversion_goal.status, custom_conversion_goal.conversion_actions";
|
|
957
|
+
var object2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
958
|
+
var canonical2 = (value) => Array.isArray(value) ? value.map(canonical2) : value && typeof value === "object" ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key2, item]) => [key2, canonical2(item)])) : value;
|
|
959
|
+
var digest2 = (value) => createHash3("sha256").update(JSON.stringify(canonical2(value))).digest("hex");
|
|
960
|
+
var words = (value) => {
|
|
961
|
+
const text2 = value.toLowerCase().replace(/_/g, " ");
|
|
962
|
+
return text2.charAt(0).toUpperCase() + text2.slice(1);
|
|
963
|
+
};
|
|
964
|
+
var standardLabel = (row2) => `${words(row2.category)} \xB7 ${words(row2.origin)}`;
|
|
965
|
+
var chunks = (values, size) => Array.from({ length: Math.ceil(values.length / size) }, (_, index) => values.slice(index * size, index * size + size));
|
|
966
|
+
var GOOGLE_CONVERSION_GOAL_WRITES = /* @__PURE__ */ new Set(["google_create_custom_conversion_goal", "google_set_campaign_conversion_goal"]);
|
|
967
|
+
var GoogleConversionGoalService = class {
|
|
968
|
+
constructor(client, conversions) {
|
|
969
|
+
this.client = client;
|
|
970
|
+
this.conversions = conversions;
|
|
971
|
+
}
|
|
972
|
+
client;
|
|
973
|
+
conversions;
|
|
974
|
+
/** Goals are owned by the selected customer or, with cross-account tracking, its conversion customer. */
|
|
975
|
+
owners(account2, conversionCustomer) {
|
|
976
|
+
return /* @__PURE__ */ new Set([account2, ...conversionCustomer ? [conversionCustomer.slice("customers/".length)] : []]);
|
|
977
|
+
}
|
|
978
|
+
goal(value, owners) {
|
|
979
|
+
const row2 = object2(value), match = typeof row2.resourceName === "string" ? row2.resourceName.match(/^customers\/(\d{10})\/customConversionGoals\/([1-9]\d*)$/) : null;
|
|
980
|
+
const actions = row2.conversionActions === void 0 ? [] : row2.conversionActions;
|
|
981
|
+
if (!match || !owners.has(match[1]) || row2.id !== match[2] || typeof row2.name !== "string" || !["ENABLED", "REMOVED"].includes(String(row2.status)) || !Array.isArray(actions) || actions.some((item) => typeof item !== "string" || !/^customers\/\d{10}\/conversionActions\/[1-9]\d*$/.test(item))) throw new AdportError6("PROVIDER_ERROR", "google: custom conversion goal response has an invalid identity, status or action list");
|
|
982
|
+
return { resourceName: row2.resourceName, id: row2.id, name: row2.name, status: String(row2.status), conversionActions: [...actions].sort() };
|
|
983
|
+
}
|
|
984
|
+
goalView(goal, actions) {
|
|
985
|
+
return { custom_conversion_goal_id: goal.id, resource_name: goal.resourceName, name: goal.name, status: goal.status, conversion_actions: goal.conversionActions.map((resource) => {
|
|
986
|
+
const action2 = actions.get(resource);
|
|
987
|
+
return { conversion_action_id: resource.split("/").at(-1), resource_name: resource, name: typeof action2?.name === "string" ? action2.name : null, ...action2 ? { status: action2.status, category: action2.category } : {} };
|
|
988
|
+
}), snapshot_hash: digest2(goal) };
|
|
989
|
+
}
|
|
990
|
+
/** Resolves action resource names to native actions; unreturned resources stay unresolved. */
|
|
991
|
+
async actions(account2, resources) {
|
|
992
|
+
const found = /* @__PURE__ */ new Map(), ids2 = [...new Set(resources.map((resource) => resource.split("/").at(-1)))];
|
|
993
|
+
for (const batch of chunks(ids2, 100)) {
|
|
994
|
+
const rows = await this.client.search(account2, `SELECT conversion_action.resource_name, conversion_action.id, conversion_action.name, conversion_action.status, conversion_action.category, conversion_action.type FROM conversion_action WHERE conversion_action.id IN (${batch.join(",")}) LIMIT ${batch.length * 2 + 1}`, { maxRows: batch.length * 2 + 1 });
|
|
995
|
+
for (const raw of rows) {
|
|
996
|
+
const action2 = object2(raw.conversionAction);
|
|
997
|
+
if (typeof action2.resourceName !== "string" || !batch.includes(String(action2.id)) || action2.resourceName.split("/").at(-1) !== action2.id || found.has(action2.resourceName)) throw new AdportError6("PROVIDER_ERROR", "google: conversion action lookup returned an unexpected identity");
|
|
998
|
+
found.set(action2.resourceName, action2);
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
return found;
|
|
1002
|
+
}
|
|
1003
|
+
/** Lists custom goals; with campaign_ids, also the goal state of those campaigns and the snapshot that binds google_set_campaign_conversion_goal. */
|
|
1004
|
+
async list(input2) {
|
|
1005
|
+
const account2 = normalizeCustomerId(input2.account_id), context = await this.conversions.context(account2), owners = this.owners(account2, context.conversion_customer);
|
|
1006
|
+
if (input2.after_goal_id) id5.parse(input2.after_goal_id);
|
|
1007
|
+
const predicates = [...!input2.include_removed ? ["custom_conversion_goal.status != 'REMOVED'"] : [], ...input2.after_goal_id ? [`custom_conversion_goal.id > ${input2.after_goal_id}`] : []];
|
|
1008
|
+
const rows = await this.client.search(account2, `SELECT ${goalFields} FROM custom_conversion_goal${predicates.length ? ` WHERE ${predicates.join(" AND ")}` : ""} ORDER BY custom_conversion_goal.id ASC LIMIT ${input2.limit + 1}`, { maxRows: input2.limit + 1 });
|
|
1009
|
+
const goals = rows.map((row2) => this.goal(row2.customConversionGoal, owners));
|
|
1010
|
+
if (goals.some((goal, index) => BigInt(goal.id) <= BigInt(index ? goals[index - 1].id : input2.after_goal_id ?? "0"))) throw new AdportError6("PROVIDER_ERROR", "google: custom conversion goal continuation did not advance");
|
|
1011
|
+
const page = goals.slice(0, input2.limit), truncated = goals.length > input2.limit;
|
|
1012
|
+
const selected2 = input2.campaign_ids ? campaignIds.parse(input2.campaign_ids) : null, current = selected2 ? await this.campaignContext(account2, selected2, owners) : null;
|
|
1013
|
+
const referenced = current ? await this.referencedGoals(account2, owners, [...current.campaigns.values()]) : /* @__PURE__ */ new Map();
|
|
1014
|
+
const actions = await this.actions(account2, [...page, ...referenced.values()].flatMap((goal) => goal.conversionActions));
|
|
1015
|
+
return { conversion_customer: context.conversion_customer, goals: page.map((goal) => this.goalView(goal, actions)), truncated, ...truncated ? { next_cursor: page.at(-1).id } : {}, ...selected2 && current ? { campaigns: selected2.map((campaignId) => this.campaignView(current.campaigns.get(campaignId), referenced, actions)), snapshot_hash: current.snapshot_hash } : {} };
|
|
1016
|
+
}
|
|
1017
|
+
async goalById(account2, owners, goalId) {
|
|
1018
|
+
id5.parse(goalId);
|
|
1019
|
+
const rows = await this.client.search(account2, `SELECT ${goalFields} FROM custom_conversion_goal WHERE custom_conversion_goal.id = ${goalId} LIMIT 2`, { maxRows: 2 });
|
|
1020
|
+
if (rows.length !== 1) throw new AdportError6("INVALID_INPUT", "google: custom conversion goal was not returned by the selected account. Google lists the conversion customer's goals from client accounts, but a goal it does not return cannot be verified here; check the goal in Google Ads or select the account that owns it");
|
|
1021
|
+
const goal = this.goal(rows[0].customConversionGoal, owners);
|
|
1022
|
+
if (goal.id !== goalId) throw new AdportError6("PROVIDER_ERROR", "google: custom conversion goal ID mismatch");
|
|
1023
|
+
return goal;
|
|
1024
|
+
}
|
|
1025
|
+
async checkedGoal(account2, owners, input2) {
|
|
1026
|
+
const goal = await this.goalById(account2, owners, input2.custom_conversion_goal_id);
|
|
1027
|
+
if (digest2(goal) !== input2.expected_goal_hash) throw new AdportError6("PENDING_MISMATCH", "google: custom conversion goal changed; read google_custom_conversion_goals again and request a fresh preview");
|
|
1028
|
+
return goal;
|
|
1029
|
+
}
|
|
1030
|
+
/** Reads exactly the requested campaigns, their goal configuration and standard (category/origin) goals. */
|
|
1031
|
+
async campaignContext(account2, ids2, owners) {
|
|
1032
|
+
const list2 = ids2.join(","), bound = ids2.length * 200;
|
|
1033
|
+
const campaigns = await this.client.search(account2, `SELECT campaign.resource_name, campaign.id, campaign.name, campaign.status, campaign.advertising_channel_type FROM campaign WHERE campaign.id IN (${list2}) LIMIT ${ids2.length + 1}`, { maxRows: ids2.length + 1 });
|
|
1034
|
+
const byId = /* @__PURE__ */ new Map();
|
|
1035
|
+
for (const raw of campaigns) {
|
|
1036
|
+
const campaign = object2(raw.campaign), campaignId = String(campaign.id);
|
|
1037
|
+
if (!ids2.includes(campaignId) || campaign.resourceName !== `customers/${account2}/campaigns/${campaignId}` || byId.has(campaignId) || !["ENABLED", "PAUSED"].includes(String(campaign.status))) throw new AdportError6("INVALID_INPUT", "google: every campaign must be an enabled or paused campaign in the selected account");
|
|
1038
|
+
byId.set(campaignId, { campaign, config: { resourceName: "", level: "CUSTOMER", goal: null }, standard: [] });
|
|
1039
|
+
}
|
|
1040
|
+
if (byId.size !== ids2.length) throw new AdportError6("INVALID_INPUT", `google: campaigns not found in the selected account: ${ids2.filter((value) => !byId.has(value)).join(", ")}`);
|
|
1041
|
+
const configs2 = await this.client.search(account2, `SELECT conversion_goal_campaign_config.resource_name, conversion_goal_campaign_config.campaign, conversion_goal_campaign_config.goal_config_level, conversion_goal_campaign_config.custom_conversion_goal, campaign.id FROM conversion_goal_campaign_config WHERE campaign.id IN (${list2}) LIMIT ${ids2.length + 1}`, { maxRows: ids2.length + 1 });
|
|
1042
|
+
const configured = /* @__PURE__ */ new Set();
|
|
1043
|
+
for (const raw of configs2) {
|
|
1044
|
+
const config2 = object2(raw.conversionGoalCampaignConfig), campaignId = String(object2(raw.campaign).id), entry = byId.get(campaignId), goal = config2.customConversionGoal;
|
|
1045
|
+
const goalOwner = typeof goal === "string" ? goal.match(/^customers\/(\d{10})\/customConversionGoals\/[1-9]\d*$/)?.[1] : void 0;
|
|
1046
|
+
if (!entry || configured.has(campaignId) || config2.resourceName !== `customers/${account2}/conversionGoalCampaignConfigs/${campaignId}` || config2.campaign !== entry.campaign.resourceName || !["CUSTOMER", "CAMPAIGN"].includes(String(config2.goalConfigLevel)) || goal !== void 0 && goal !== "" && (!goalOwner || !owners.has(goalOwner))) throw new AdportError6("PROVIDER_ERROR", "google: campaign goal configuration has an invalid identity, level or custom goal");
|
|
1047
|
+
configured.add(campaignId);
|
|
1048
|
+
entry.config = { resourceName: config2.resourceName, level: config2.goalConfigLevel, goal: typeof goal === "string" && goal ? goal : null };
|
|
1049
|
+
}
|
|
1050
|
+
if (configured.size !== ids2.length) throw new AdportError6("PROVIDER_ERROR", "google: a campaign goal configuration was not returned");
|
|
1051
|
+
const standards = await this.client.search(account2, `SELECT campaign_conversion_goal.resource_name, campaign_conversion_goal.campaign, campaign_conversion_goal.category, campaign_conversion_goal.origin, campaign_conversion_goal.biddable, campaign.id FROM campaign_conversion_goal WHERE campaign.id IN (${list2}) LIMIT ${bound + 1}`, { maxRows: bound + 1 });
|
|
1052
|
+
if (standards.length > bound) throw new AdportError6("PROVIDER_ERROR", "google: campaign goals exceed the 200-per-campaign safety bound");
|
|
1053
|
+
for (const raw of standards) {
|
|
1054
|
+
const row2 = object2(raw.campaignConversionGoal), campaignId = String(object2(raw.campaign).id), entry = byId.get(campaignId);
|
|
1055
|
+
if (!entry || row2.campaign !== entry.campaign.resourceName || typeof row2.category !== "string" || !ORIGINS.includes(row2.origin) || row2.resourceName !== `customers/${account2}/campaignConversionGoals/${campaignId}~${row2.category}~${row2.origin}` || entry.standard.some((item) => item.resourceName === row2.resourceName)) throw new AdportError6("PROVIDER_ERROR", "google: campaign conversion goal has an invalid identity, category or origin");
|
|
1056
|
+
entry.standard.push({ resourceName: row2.resourceName, category: row2.category, origin: String(row2.origin), biddable: row2.biddable === true });
|
|
1057
|
+
}
|
|
1058
|
+
for (const entry of byId.values()) entry.standard.sort((a, b) => a.resourceName.localeCompare(b.resourceName));
|
|
1059
|
+
const ordered = [...ids2].sort((a, b) => BigInt(a) < BigInt(b) ? -1 : 1).map((value) => byId.get(value));
|
|
1060
|
+
return { campaigns: byId, snapshot_hash: digest2({ account: account2, campaigns: ordered.map((entry) => ({ id: entry.campaign.id, config: entry.config, standard: entry.standard })) }) };
|
|
1061
|
+
}
|
|
1062
|
+
describe(state, actions) {
|
|
1063
|
+
const bidding = state.standard.filter((row2) => row2.biddable).map(standardLabel);
|
|
1064
|
+
if (state.level === "CUSTOMER") return `Account default goals${bidding.length ? ` (${bidding.join(", ")})` : ""}`;
|
|
1065
|
+
const parts = [];
|
|
1066
|
+
if (state.goal) parts.push(`custom goal "${state.goal.name}" optimizing for ${state.goal.conversionActions.map((resource) => {
|
|
1067
|
+
const name5 = actions.get(resource)?.name;
|
|
1068
|
+
return typeof name5 === "string" ? `"${name5}"` : `action ${resource.split("/").at(-1)}`;
|
|
1069
|
+
}).join(", ") || "no actions"}`);
|
|
1070
|
+
else if (state.goalResource) parts.push(`custom goal ${state.goalResource.split("/").at(-1)}`);
|
|
1071
|
+
parts.push(bidding.length ? `standard goals used for bidding: ${bidding.join(", ")}` : "no standard goals used for bidding");
|
|
1072
|
+
return `Campaign-specific goals: ${parts.join("; ")}`;
|
|
1073
|
+
}
|
|
1074
|
+
campaignView(entry, goals, actions) {
|
|
1075
|
+
const goal = entry.config.goal ? goals.get(entry.config.goal) ?? null : null;
|
|
1076
|
+
return { campaign_id: String(entry.campaign.id), name: entry.campaign.name, status: entry.campaign.status, channel_type: entry.campaign.advertisingChannelType, goal_config_level: entry.config.level, custom_conversion_goal: entry.config.level === "CAMPAIGN" && entry.config.goal ? goal ? this.goalView(goal, actions) : { resource_name: entry.config.goal } : null, standard_goals: entry.standard.map((row2) => ({ category: row2.category, origin: row2.origin, biddable: row2.biddable })), summary: this.describe({ level: entry.config.level, goal, goalResource: entry.config.goal, standard: entry.standard }, actions) };
|
|
1077
|
+
}
|
|
1078
|
+
async referencedGoals(account2, owners, entries) {
|
|
1079
|
+
const resources = [...new Set(entries.filter((entry) => entry.config.level === "CAMPAIGN" && entry.config.goal).map((entry) => entry.config.goal))], found = /* @__PURE__ */ new Map();
|
|
1080
|
+
for (const batch of chunks(resources.map((resource) => resource.split("/").at(-1)), 100)) {
|
|
1081
|
+
const rows = await this.client.search(account2, `SELECT ${goalFields} FROM custom_conversion_goal WHERE custom_conversion_goal.id IN (${batch.join(",")}) LIMIT ${batch.length * 2 + 1}`, { maxRows: batch.length * 2 + 1 });
|
|
1082
|
+
for (const row2 of rows) {
|
|
1083
|
+
const goal = this.goal(row2.customConversionGoal, owners);
|
|
1084
|
+
if (resources.includes(goal.resourceName)) found.set(goal.resourceName, goal);
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
return found;
|
|
1088
|
+
}
|
|
1089
|
+
/** Every referenced action must be an enabled action visible from the selected customer. */
|
|
1090
|
+
async enabledActions(account2, owners, ids2) {
|
|
1091
|
+
const found = /* @__PURE__ */ new Map();
|
|
1092
|
+
for (const batch of chunks(ids2, 100)) {
|
|
1093
|
+
const rows = await this.client.search(account2, `SELECT conversion_action.resource_name, conversion_action.id, conversion_action.name, conversion_action.status, conversion_action.category FROM conversion_action WHERE conversion_action.id IN (${batch.join(",")}) LIMIT ${batch.length + 1}`, { maxRows: batch.length + 1 });
|
|
1094
|
+
for (const raw of rows) {
|
|
1095
|
+
const action2 = object2(raw.conversionAction), match = typeof action2.resourceName === "string" ? action2.resourceName.match(/^customers\/(\d{10})\/conversionActions\/([1-9]\d*)$/) : null;
|
|
1096
|
+
if (!match || !owners.has(match[1]) || match[2] !== action2.id || !batch.includes(match[2]) || found.has(match[2])) throw new AdportError6("PROVIDER_ERROR", "google: conversion action lookup returned an unexpected identity");
|
|
1097
|
+
if (action2.status !== "ENABLED") throw new AdportError6("INVALID_INPUT", `google: conversion action ${match[2]} is ${String(action2.status)}; custom goals need enabled actions`);
|
|
1098
|
+
found.set(match[2], action2);
|
|
1099
|
+
}
|
|
1100
|
+
}
|
|
1101
|
+
const missing = ids2.filter((value) => !found.has(value));
|
|
1102
|
+
if (missing.length) throw new AdportError6("INVALID_INPUT", `google: conversion actions not found in the selected account or its conversion customer: ${missing.join(", ")}`);
|
|
1103
|
+
return ids2.map((value) => found.get(value));
|
|
1104
|
+
}
|
|
1105
|
+
async plan(op) {
|
|
1106
|
+
const kind = op.tool === "google_create_custom_conversion_goal" ? "create" : "update";
|
|
1107
|
+
if (op.provider !== "google" || !GOOGLE_CONVERSION_GOAL_WRITES.has(op.tool) || op.kind !== kind) throw new AdportError6("INVALID_INPUT", "google: conversion goal operation kind mismatch");
|
|
1108
|
+
const account2 = normalizeCustomerId(op.accountId), context = await this.conversions.context(account2), owners = this.owners(account2, context.conversion_customer);
|
|
1109
|
+
if (op.tool === "google_set_campaign_conversion_goal") return this.planCampaigns(account2, owners, setGoal.parse(op.payload));
|
|
1110
|
+
if (context.conversion_customer && context.conversion_customer !== `customers/${account2}`) throw new AdportError6("INVALID_INPUT", `google: custom conversion goals are managed in the conversion customer ${context.conversion_customer}; select that explicitly authorized account to change them`);
|
|
1111
|
+
const input2 = createGoal.parse(op.payload), actions = await this.enabledActions(account2, owners, input2.conversion_action_ids);
|
|
1112
|
+
const operations = [{ customConversionGoalOperation: { create: { name: input2.name, conversionActions: actions.map((action2) => action2.resourceName) } } }];
|
|
1113
|
+
const fields5 = [{ label: "Goal name", before: "(new)", after: input2.name }, { label: "Optimizes for", before: "(new)", after: actions.map((action2) => `${String(action2.name)} [${String(action2.id)}]`) }];
|
|
1114
|
+
const notes2 = ["A custom goal makes its actions biddable for every campaign that uses it, whether or not each action is primary_for_goal.", "Creating a goal does not attach it to any campaign; use google_set_campaign_conversion_goal."];
|
|
1115
|
+
return { summary: `Create Google custom conversion goal "${input2.name}"`, changes: fields5.map((field3) => `${field3.label}: ${JSON.stringify(field3.before)} \u2192 ${JSON.stringify(field3.after)}`), fieldChanges: fields5.map((field3) => ({ field: field3.label, before: JSON.stringify(field3.before), after: JSON.stringify(field3.after) })), coercions: [], budgetDeltas: [], notes: notes2, review: { provider: "google", accountId: account2, kind: op.kind, title: "Create custom conversion goal", fields: fields5, notices: notes2 }, execute: async (validateOnly) => {
|
|
1116
|
+
let result2;
|
|
1117
|
+
try {
|
|
1118
|
+
result2 = await this.client.googleAdsMutate(account2, operations, { validateOnly });
|
|
1119
|
+
} catch (error) {
|
|
1120
|
+
if (validateOnly || isGoogleAdsRejection(error)) throw error;
|
|
1121
|
+
throw new AdportError6("PROVIDER_ERROR", "google: custom conversion goal creation could not be confirmed. Read google_custom_conversion_goals and check the goal name before retrying.");
|
|
1122
|
+
}
|
|
1123
|
+
if (validateOnly) return [];
|
|
1124
|
+
const responses = result2?.mutateOperationResponses, resource = Array.isArray(responses) && responses.length === 1 ? responses[0]?.customConversionGoalResult?.resourceName : void 0;
|
|
1125
|
+
if (typeof resource !== "string" || !new RegExp(`^customers/${account2}/customConversionGoals/[1-9]\\d*$`).test(resource)) throw new AdportError6("PROVIDER_ERROR", "google: custom conversion goal mutation receipt mismatch; reconcile before retrying", { resource_ids: typeof resource === "string" ? [resource] : [] });
|
|
1126
|
+
return [resource];
|
|
1127
|
+
} };
|
|
1128
|
+
}
|
|
1129
|
+
async planCampaigns(account2, owners, input2) {
|
|
1130
|
+
const before = await this.campaignContext(account2, input2.campaign_ids, owners);
|
|
1131
|
+
if (before.snapshot_hash !== input2.expected_snapshot_hash) throw new AdportError6("PENDING_MISMATCH", "google: campaign goal configuration changed; read google_custom_conversion_goals with the same campaign_ids and preview again");
|
|
1132
|
+
const entries = input2.campaign_ids.map((campaignId) => before.campaigns.get(campaignId));
|
|
1133
|
+
const target5 = input2.goal?.type === "CUSTOM_GOAL" ? await this.checkedGoal(account2, owners, input2.goal) : null;
|
|
1134
|
+
if (target5 && target5.status !== "ENABLED") throw new AdportError6("INVALID_INPUT", "google: the selected custom conversion goal has been removed");
|
|
1135
|
+
const goals = await this.referencedGoals(account2, owners, entries);
|
|
1136
|
+
if (target5) goals.set(target5.resourceName, target5);
|
|
1137
|
+
const actions = await this.actions(account2, [...goals.values()].flatMap((goal) => goal.conversionActions));
|
|
1138
|
+
const toggles = Array.isArray(input2.standard_goals) ? input2.standard_goals : [];
|
|
1139
|
+
const configOps = [], standardOps = [], fields5 = [], expectations = [], warnings2 = [];
|
|
1140
|
+
for (const entry of entries) {
|
|
1141
|
+
const campaignId = String(entry.campaign.id), name5 = String(entry.campaign.name), currentGoal = entry.config.level === "CAMPAIGN" ? entry.config.goal : null;
|
|
1142
|
+
const operationsBefore = configOps.length + standardOps.length;
|
|
1143
|
+
let level2 = entry.config.level, goalResource = currentGoal;
|
|
1144
|
+
if (input2.goal?.type === "ACCOUNT_DEFAULT") {
|
|
1145
|
+
if (entry.config.level !== "CUSTOMER") configOps.push({ conversionGoalCampaignConfigOperation: { update: { resourceName: entry.config.resourceName, goalConfigLevel: "CUSTOMER" }, updateMask: "goal_config_level" } });
|
|
1146
|
+
level2 = "CUSTOMER";
|
|
1147
|
+
goalResource = null;
|
|
1148
|
+
} else if (target5) {
|
|
1149
|
+
if (entry.config.level !== "CAMPAIGN") configOps.push({ conversionGoalCampaignConfigOperation: { update: { resourceName: entry.config.resourceName, goalConfigLevel: "CAMPAIGN", customConversionGoal: target5.resourceName }, updateMask: "goal_config_level,custom_conversion_goal" } });
|
|
1150
|
+
else if (currentGoal !== target5.resourceName) configOps.push({ conversionGoalCampaignConfigOperation: { update: { resourceName: entry.config.resourceName, customConversionGoal: target5.resourceName }, updateMask: "custom_conversion_goal" } });
|
|
1151
|
+
level2 = "CAMPAIGN";
|
|
1152
|
+
goalResource = target5.resourceName;
|
|
1153
|
+
} else if (input2.standard_goals && entry.config.level !== "CAMPAIGN") {
|
|
1154
|
+
configOps.push({ conversionGoalCampaignConfigOperation: { update: { resourceName: entry.config.resourceName, goalConfigLevel: "CAMPAIGN" }, updateMask: entry.config.goal ? "goal_config_level,custom_conversion_goal" : "goal_config_level" } });
|
|
1155
|
+
}
|
|
1156
|
+
const biddable = /* @__PURE__ */ new Map(), standardAfter = entry.standard.map((row2) => ({ ...row2 }));
|
|
1157
|
+
if (input2.standard_goals) {
|
|
1158
|
+
level2 = "CAMPAIGN";
|
|
1159
|
+
const wanted = input2.standard_goals === "DISABLE_ALL" ? entry.standard.map((row2) => ({ category: row2.category, origin: row2.origin, biddable: false })) : toggles;
|
|
1160
|
+
for (const item of wanted) {
|
|
1161
|
+
const row2 = standardAfter.find((value) => value.category === item.category && value.origin === item.origin);
|
|
1162
|
+
if (!row2) throw new AdportError6("INVALID_INPUT", `google: campaign "${name5}" [${campaignId}] has no ${item.category}/${item.origin} goal; read google_custom_conversion_goals with campaign_ids for the available pairs`);
|
|
1163
|
+
biddable.set(row2.resourceName, item.biddable);
|
|
1164
|
+
if (row2.biddable !== item.biddable) {
|
|
1165
|
+
standardOps.push({ campaignConversionGoalOperation: { update: { resourceName: row2.resourceName, biddable: item.biddable }, updateMask: "biddable" } });
|
|
1166
|
+
row2.biddable = item.biddable;
|
|
1167
|
+
}
|
|
1168
|
+
}
|
|
1169
|
+
}
|
|
1170
|
+
if (level2 === "CAMPAIGN" && !goalResource && !standardAfter.some((row2) => row2.biddable)) {
|
|
1171
|
+
throw new AdportError6("INVALID_INPUT", "google: campaign " + campaignId + " needs at least one biddable standard goal or a custom conversion goal; keep a standard goal enabled or select a custom goal in this request");
|
|
1172
|
+
}
|
|
1173
|
+
const beforeText = this.describe({ level: entry.config.level, goal: currentGoal ? goals.get(currentGoal) ?? null : null, goalResource: currentGoal, standard: entry.standard }, actions);
|
|
1174
|
+
const afterText = level2 === "CUSTOMER" ? "Account default goals (campaign-specific and custom goals no longer apply)" : this.describe({ level: level2, goal: goalResource ? goals.get(goalResource) ?? null : null, goalResource, standard: standardAfter }, actions);
|
|
1175
|
+
fields5.push({ label: `${name5} [${campaignId}]`, before: beforeText, after: configOps.length + standardOps.length === operationsBefore ? "No change" : afterText });
|
|
1176
|
+
if (target5 && level2 === "CAMPAIGN" && standardAfter.some((row2) => row2.biddable)) warnings2.push(`${name5} [${campaignId}] also keeps bidding on ${standardAfter.filter((row2) => row2.biddable).map(standardLabel).join(", ")}. Pass standard_goals="DISABLE_ALL" to optimize only for the custom goal.`);
|
|
1177
|
+
expectations.push({ campaignId, level: level2, ...goalResource ? { goal: goalResource } : {}, biddable });
|
|
1178
|
+
}
|
|
1179
|
+
const operations = [...configOps, ...standardOps];
|
|
1180
|
+
if (!operations.length) throw new AdportError6("INVALID_INPUT", "google: every selected campaign already has this conversion goal configuration");
|
|
1181
|
+
if (operations.length > 5e3) throw new AdportError6("INVALID_INPUT", "google: conversion goal edits exceed the 5,000-operation tool bound; select fewer campaigns");
|
|
1182
|
+
const changed = fields5.filter((field3) => field3.after !== "No change").length;
|
|
1183
|
+
const notes2 = [...warnings2, "All campaigns change in one atomic request: either every listed change applies or none does.", "Campaign-specific goals stop following future account-level goal changes until the campaign is set back to ACCOUNT_DEFAULT.", "Conversion goals change what automated bidding optimizes for and what the Conversions column reports. Campaign statuses and budgets are not changed."];
|
|
1184
|
+
const summary = target5 ? `Use custom conversion goal "${target5.name}" on ${changed} Google campaign${changed === 1 ? "" : "s"}` : input2.goal?.type === "ACCOUNT_DEFAULT" ? `Restore account default conversion goals on ${changed} Google campaign${changed === 1 ? "" : "s"}` : `Update standard conversion goals on ${changed} Google campaign${changed === 1 ? "" : "s"}`;
|
|
1185
|
+
let details;
|
|
1186
|
+
return { summary, changes: fields5.map((field3) => `${field3.label}: ${String(field3.before)} \u2192 ${String(field3.after)}`), fieldChanges: fields5.map((field3) => ({ field: field3.label, before: String(field3.before), after: String(field3.after) })), coercions: [], budgetDeltas: [], notes: notes2, review: { provider: "google", accountId: account2, kind: "update", title: "Set campaign conversion goals", ...target5 ? { subject: target5.name } : {}, fields: fields5, notices: notes2 }, resultDetails: () => details, execute: async (validateOnly) => {
|
|
1187
|
+
const known = /* @__PURE__ */ new Set();
|
|
1188
|
+
const unconfirmed = () => new AdportError6("PROVIDER_ERROR", "google: campaign conversion goal outcome was not confirmed. Read google_custom_conversion_goals with campaign_ids before another change; no write was retried.", { resourceIds: [...known] });
|
|
1189
|
+
let result2;
|
|
1190
|
+
try {
|
|
1191
|
+
result2 = await this.client.googleAdsMutate(account2, operations, { validateOnly });
|
|
1192
|
+
} catch (error) {
|
|
1193
|
+
if (validateOnly || isGoogleAdsRejection(error)) throw error;
|
|
1194
|
+
throw unconfirmed();
|
|
1195
|
+
}
|
|
1196
|
+
try {
|
|
1197
|
+
if (!result2 || typeof result2 !== "object" || Array.isArray(result2) || "partialFailureError" in result2) throw new AdportError6("PROVIDER_ERROR", "google: conversion goal mutate response envelope could not be verified");
|
|
1198
|
+
if (validateOnly) return [];
|
|
1199
|
+
const responses = result2.mutateOperationResponses;
|
|
1200
|
+
if (!Array.isArray(responses) || responses.length !== operations.length) throw new Error("receipt count mismatch");
|
|
1201
|
+
responses.forEach((response, index) => {
|
|
1202
|
+
const operation = operations[index], key2 = operation.conversionGoalCampaignConfigOperation ? "conversionGoalCampaignConfig" : "campaignConversionGoal", expected = object2(object2(operation[`${key2}Operation`]).update).resourceName;
|
|
1203
|
+
if (Object.keys(object2(response)).length !== 1 || response[`${key2}Result`]?.resourceName !== expected) throw new Error("receipt mismatch");
|
|
1204
|
+
known.add(String(expected));
|
|
1205
|
+
});
|
|
1206
|
+
const after = await this.campaignContext(account2, input2.campaign_ids, owners);
|
|
1207
|
+
for (const expectation of expectations) {
|
|
1208
|
+
const observed = after.campaigns.get(expectation.campaignId);
|
|
1209
|
+
if (observed.config.level !== expectation.level || expectation.level === "CAMPAIGN" && observed.config.goal !== (expectation.goal ?? null) || [...expectation.biddable].some(([resource, value]) => observed.standard.find((row2) => row2.resourceName === resource)?.biddable !== value)) throw new Error("readback mismatch");
|
|
1210
|
+
}
|
|
1211
|
+
details = { snapshot_hash: after.snapshot_hash, campaigns_changed: changed, operations: operations.length, readback_verified: true };
|
|
1212
|
+
return [...known];
|
|
1213
|
+
} catch (error) {
|
|
1214
|
+
if (validateOnly) throw error;
|
|
1215
|
+
throw unconfirmed();
|
|
1216
|
+
}
|
|
1217
|
+
} };
|
|
1218
|
+
}
|
|
1219
|
+
};
|
|
1220
|
+
function googleConversionGoalTools(provider) {
|
|
1221
|
+
const write = (name5, description, payload, kind) => guardedWriteTool5({ name: name5, namespace: "google", provider: "google", description, payload, kind });
|
|
1222
|
+
return [
|
|
1223
|
+
defineTool5({ name: "google_custom_conversion_goals", namespace: "google", description: "List custom conversion goals and their actions, as returned by the selected account (with cross-account tracking Google includes the conversion customer's goals; a goal it does not return shows only as resource_name and cannot be assigned here); each snapshot_hash is the expected_goal_hash. With campaign_ids (up to 50), also returns those campaigns' goal state and the snapshot_hash for google_set_campaign_conversion_goal. Continue next_cursor as after_goal_id.", input: z5.object({ account_id: z5.string(), campaign_ids: campaignIds.optional(), after_goal_id: id5.optional(), include_removed: z5.boolean().default(false), limit: z5.number().int().positive().max(200).default(50) }), output: z5.object({ conversion_customer: z5.string().nullable(), goals: z5.array(z5.record(z5.string(), z5.unknown())), truncated: z5.boolean(), next_cursor: id5.optional(), campaigns: z5.array(z5.record(z5.string(), z5.unknown())).optional(), snapshot_hash: hash3.optional() }), annotations: { readOnly: true }, pagination: { cursorInput: "after_goal_id" }, handler: (input2) => provider.conversionGoals.list(input2) }),
|
|
1224
|
+
write("google_create_custom_conversion_goal", "Create a custom conversion goal from 1\u2013100 enabled conversion action IDs in the conversion-tracking account. Attaches to no campaign.", createGoal, "create"),
|
|
1225
|
+
write("google_set_campaign_conversion_goal", 'Set the conversion goal of 1\u201350 campaigns atomically. goal: CUSTOM_GOAL or ACCOUNT_DEFAULT. standard_goals: "DISABLE_ALL" (optimize only for the custom goal) or category/origin biddable toggles.', setGoal, "update")
|
|
1226
|
+
];
|
|
1227
|
+
}
|
|
1228
|
+
|
|
1229
|
+
// src/data-manager.ts
|
|
1230
|
+
import { createHash as createHash4 } from "crypto";
|
|
1231
|
+
import { AdportError as AdportError7, defineTool as defineTool6, guardedWriteTool as guardedWriteTool6 } from "@adport/core";
|
|
1232
|
+
import { z as z6 } from "zod";
|
|
1233
|
+
var object3 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
1234
|
+
var id6 = z6.string().regex(/^[1-9]\d*$/);
|
|
1235
|
+
var hash4 = z6.string().regex(/^[a-f0-9]{64}$/);
|
|
1236
|
+
var opaque2 = z6.string().min(1).max(4096);
|
|
1237
|
+
var identifierHash = z6.string().regex(/^[a-fA-F0-9]{64}$/);
|
|
1238
|
+
var timestamp2 = z6.iso.datetime({ offset: true }).refine((value) => Number.isFinite(Date.parse(value)) && (value.match(/\.(\d+)/)?.[1]?.length ?? 0) <= 9, "Use a real RFC3339 timestamp with at most nanosecond precision");
|
|
1239
|
+
var consent2 = z6.object({ ad_user_data: z6.enum(["CONSENT_GRANTED", "CONSENT_DENIED"]).optional(), ad_personalization: z6.enum(["CONSENT_GRANTED", "CONSENT_DENIED"]).optional() }).strict();
|
|
1240
|
+
var device = z6.object({ user_agent: opaque2.optional(), ip_address: z6.union([z6.ipv4(), z6.ipv6()]).optional(), category: opaque2.optional(), language_code: z6.string().regex(/^[a-z]{2}$/).optional(), screen_height: z6.number().int().nonnegative().max(2147483647).optional(), screen_width: z6.number().int().nonnegative().max(2147483647).optional(), operating_system: opaque2.optional(), operating_system_version: opaque2.optional(), model: opaque2.optional(), brand: opaque2.optional(), browser: opaque2.optional(), browser_version: opaque2.optional() }).strict();
|
|
1241
|
+
var identifier = z6.union([
|
|
1242
|
+
z6.object({ email_address: identifierHash }).strict(),
|
|
1243
|
+
z6.object({ phone_number: identifierHash }).strict(),
|
|
1244
|
+
z6.object({ address: z6.object({ given_name: identifierHash, family_name: identifierHash, region_code: z6.string().regex(/^[A-Z]{2}$/), postal_code: z6.string().min(1).max(256) }).strict() }).strict()
|
|
936
1245
|
]);
|
|
937
|
-
var variable =
|
|
938
|
-
var event =
|
|
1246
|
+
var variable = z6.object({ variable: z6.string().min(1).max(256), value: z6.string().max(4096) }).strict();
|
|
1247
|
+
var event = z6.object({
|
|
939
1248
|
event_timestamp: timestamp2,
|
|
940
1249
|
last_updated_timestamp: timestamp2.optional(),
|
|
941
1250
|
transaction_id: opaque2.optional(),
|
|
942
|
-
event_source:
|
|
943
|
-
currency:
|
|
944
|
-
conversion_value:
|
|
945
|
-
conversion_count:
|
|
946
|
-
user_data:
|
|
1251
|
+
event_source: z6.enum(["WEB", "APP", "IN_STORE", "PHONE", "MESSAGE", "OTHER"]).optional(),
|
|
1252
|
+
currency: z6.string().regex(/^[A-Z]{3}$/).optional(),
|
|
1253
|
+
conversion_value: z6.number().finite().optional(),
|
|
1254
|
+
conversion_count: z6.number().finite().nonnegative().optional(),
|
|
1255
|
+
user_data: z6.object({ user_identifiers: z6.array(identifier).min(1).max(10) }).strict().optional(),
|
|
947
1256
|
user_id: opaque2.optional(),
|
|
948
1257
|
consent: consent2.optional(),
|
|
949
|
-
ad_identifiers:
|
|
1258
|
+
ad_identifiers: z6.object({ gclid: opaque2.optional(), gbraid: opaque2.optional(), wbraid: opaque2.optional(), session_attributes: z6.string().min(1).max(65536).optional(), landing_page_device_info: device.optional() }).strict().optional(),
|
|
950
1259
|
event_device_info: device.optional(),
|
|
951
|
-
cart_data:
|
|
952
|
-
custom_variables:
|
|
953
|
-
experimental_fields:
|
|
954
|
-
user_properties:
|
|
1260
|
+
cart_data: z6.object({ merchant_id: id6.optional(), merchant_feed_label: opaque2.optional(), merchant_feed_language_code: z6.string().regex(/^[a-z]{2}$/).optional(), transaction_discount: z6.number().finite().optional(), coupon_codes: z6.array(opaque2).max(100).optional(), items: z6.array(z6.object({ item_id: opaque2, merchant_product_id: opaque2, quantity: z6.string().regex(/^[1-9]\d*$/).refine((value) => BigInt(value) <= 9223372036854775807n, "Quantity exceeds int64"), unit_price: z6.number().finite(), conversion_value: z6.number().finite().optional(), custom_variables: z6.array(variable).max(100).optional() }).strict()).min(1).max(1e3) }).strict().optional(),
|
|
1261
|
+
custom_variables: z6.array(variable).max(100).optional(),
|
|
1262
|
+
experimental_fields: z6.array(z6.object({ field: z6.string().min(1).max(256), value: z6.string().max(65536) }).strict()).max(100).optional(),
|
|
1263
|
+
user_properties: z6.object({ customer_type: z6.enum(["NEW", "RETURNING", "REENGAGED"]).optional(), customer_value_bucket: z6.enum(["LOW", "MEDIUM", "HIGH"]).optional() }).strict().optional()
|
|
955
1264
|
}).strict().superRefine((value, ctx) => {
|
|
956
1265
|
const ad = value.ad_identifiers;
|
|
957
1266
|
if (!value.user_data && !ad?.gclid && !ad?.gbraid && !ad?.wbraid && !ad?.session_attributes && !ad?.landing_page_device_info?.ip_address && !value.event_device_info?.ip_address) ctx.addIssue({ code: "custom", message: "Supply captured click/session identifiers, an event or landing IP address, or hashed user data" });
|
|
958
1267
|
});
|
|
959
|
-
var ingest =
|
|
960
|
-
value.events.forEach((
|
|
961
|
-
if (
|
|
1268
|
+
var ingest = z6.object({ conversion_action_id: id6, expected_action_hash: hash4, events: z6.array(event).min(1).max(2e3), consent: consent2.optional() }).strict().superRefine((value, ctx) => {
|
|
1269
|
+
value.events.forEach((record5, index) => {
|
|
1270
|
+
if (record5.user_data && (record5.consent ?? value.consent)?.ad_user_data !== "CONSENT_GRANTED") ctx.addIssue({ code: "custom", path: ["events", index, "consent"], message: "Hashed user data requires explicit CONSENT_GRANTED ad_user_data; never infer consent" });
|
|
962
1271
|
});
|
|
963
1272
|
});
|
|
964
|
-
var account =
|
|
965
|
-
var productAccount =
|
|
966
|
-
var destination =
|
|
967
|
-
var receipt =
|
|
968
|
-
var receiptInput =
|
|
969
|
-
function
|
|
970
|
-
if (Array.isArray(value)) return value.map(
|
|
971
|
-
if (value !== null && typeof value === "object") return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key2, item]) => [key2,
|
|
1273
|
+
var account = z6.string().regex(/^\d{10}$/);
|
|
1274
|
+
var productAccount = z6.object({ accountType: z6.literal("GOOGLE_ADS"), accountId: account }).strict();
|
|
1275
|
+
var destination = z6.object({ operatingAccount: productAccount, loginAccount: productAccount, productDestinationId: id6 }).strict();
|
|
1276
|
+
var receipt = z6.object({ kind: z6.literal("google_conversion_ingestion_v1"), account_id: account, destination, request_id: z6.string().min(1).max(512).regex(/^[^\x00-\x20\x7f]+$/), batch_sha256: hash4, event_count: z6.number().int().min(1).max(2e3), expires_at: z6.number().int().positive().safe() }).strict();
|
|
1277
|
+
var receiptInput = z6.string().min(1).max(4096);
|
|
1278
|
+
function canonical3(value) {
|
|
1279
|
+
if (Array.isArray(value)) return value.map(canonical3);
|
|
1280
|
+
if (value !== null && typeof value === "object") return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key2, item]) => [key2, canonical3(item)]));
|
|
972
1281
|
return value;
|
|
973
1282
|
}
|
|
974
|
-
var
|
|
1283
|
+
var digest3 = (value) => createHash4("sha256").update(JSON.stringify(canonical3(value))).digest("hex");
|
|
975
1284
|
function wire2(value) {
|
|
976
1285
|
if (Array.isArray(value)) return value.map(wire2);
|
|
977
1286
|
if (value !== null && typeof value === "object") return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0).map(([key2, item]) => [key2.replace(/_([a-z])/g, (_match, char) => char.toUpperCase()), wire2(item)]));
|
|
@@ -981,19 +1290,19 @@ function warnings(value) {
|
|
|
981
1290
|
if (value === void 0) return [];
|
|
982
1291
|
if (!Array.isArray(value)) return ["Data Manager returned unrecognized optional-field warnings; inspect diagnostics before relying on all supplied fields."];
|
|
983
1292
|
return value.slice(0, 100).map((item) => {
|
|
984
|
-
const warning =
|
|
1293
|
+
const warning = object3(item), reason = typeof warning.reason === "string" && /^WARNING_REASON_[A-Z0-9_]{1,100}$/.test(warning.reason) ? warning.reason : "WARNING_REASON_UNKNOWN";
|
|
985
1294
|
const field3 = isDataManagerFieldPath(warning.field) ? ` at ${warning.field}` : "";
|
|
986
1295
|
return `Data Manager ${reason}${field3}; optional input may be ignored.`;
|
|
987
1296
|
}).concat(value.length > 100 ? [`${value.length - 100} more field warnings were returned.`] : []);
|
|
988
1297
|
}
|
|
989
1298
|
var count = (value) => typeof value === "string" && /^\d+$/.test(value) ? value : typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? String(value) : void 0;
|
|
990
1299
|
function diagnosticCounts(value, key2) {
|
|
991
|
-
const rows =
|
|
1300
|
+
const rows = object3(value)[key2];
|
|
992
1301
|
if (rows === void 0) return [];
|
|
993
|
-
if (!Array.isArray(rows)) throw new
|
|
1302
|
+
if (!Array.isArray(rows)) throw new AdportError7("PROVIDER_ERROR", "google: malformed Data Manager diagnostic counts");
|
|
994
1303
|
return rows.map((item) => {
|
|
995
|
-
const row2 =
|
|
996
|
-
if (!total || typeof row2.reason !== "string" || !/^PROCESSING_(?:ERROR|WARNING)_[A-Z0-9_]{1,160}$/.test(row2.reason)) throw new
|
|
1304
|
+
const row2 = object3(item), total = count(row2.recordCount ?? "0");
|
|
1305
|
+
if (!total || typeof row2.reason !== "string" || !/^PROCESSING_(?:ERROR|WARNING)_[A-Z0-9_]{1,160}$/.test(row2.reason)) throw new AdportError7("PROVIDER_ERROR", "google: malformed Data Manager diagnostic reason/count");
|
|
997
1306
|
return { reason: row2.reason, record_count: total };
|
|
998
1307
|
});
|
|
999
1308
|
}
|
|
@@ -1009,19 +1318,19 @@ var GoogleDataManagerService = class {
|
|
|
1009
1318
|
return { account_id: selected2, conversion_context: tracking, login_account_id: this.client.dataManagerLoginAccount(selected2), ...access, api_enablement: "NOT_CHECKED", note: "This read checks the existing OAuth response, not API enablement or event eligibility. UNKNOWN means the OAuth server omitted scopes. Enable Data Manager API and explicitly authorize its separate scope before ingestion; no permissions or terms are changed." };
|
|
1010
1319
|
}
|
|
1011
1320
|
async plan(op) {
|
|
1012
|
-
if (op.tool !== "google_ingest_conversion_events") throw new
|
|
1321
|
+
if (op.tool !== "google_ingest_conversion_events") throw new AdportError7("INVALID_INPUT", "google: unsupported Data Manager mutation");
|
|
1013
1322
|
const input2 = ingest.parse(op.payload), selected2 = normalizeCustomerId(op.accountId), current = await this.conversions.get(selected2, input2.conversion_action_id), action2 = current.action;
|
|
1014
|
-
if (current.snapshot_hash !== input2.expected_action_hash) throw new
|
|
1015
|
-
if (action2.status !== "ENABLED" || !current.context.conversion_customer || action2.ownerCustomer !== current.context.conversion_customer || !["UPLOAD_CLICKS", "WEBPAGE"].includes(String(action2.type))) throw new
|
|
1016
|
-
if (input2.events.some((value) => action2.type === "UPLOAD_CLICKS" ? !value.event_source : !value.transaction_id || value.event_source !== void 0 && !["WEB", "APP"].includes(value.event_source))) throw new
|
|
1017
|
-
if (input2.events.some((value) => value.user_data) &&
|
|
1018
|
-
const keys = input2.events.map((value) => value.transaction_id ? `transaction:${value.transaction_id}` :
|
|
1019
|
-
if (new Set(keys).size !== keys.length) throw new
|
|
1020
|
-
const
|
|
1021
|
-
const body = { destinations: [
|
|
1022
|
-
const batchHash =
|
|
1323
|
+
if (current.snapshot_hash !== input2.expected_action_hash) throw new AdportError7("PENDING_MISMATCH", "google: conversion action or tracking context changed; read it again before ingestion");
|
|
1324
|
+
if (action2.status !== "ENABLED" || !current.context.conversion_customer || action2.ownerCustomer !== current.context.conversion_customer || !["UPLOAD_CLICKS", "WEBPAGE"].includes(String(action2.type))) throw new AdportError7("INVALID_INPUT", "google: Data Manager requires an enabled UPLOAD_CLICKS or WEBPAGE action owned by the verified conversion tracking customer");
|
|
1325
|
+
if (input2.events.some((value) => action2.type === "UPLOAD_CLICKS" ? !value.event_source : !value.transaction_id || value.event_source !== void 0 && !["WEB", "APP"].includes(value.event_source))) throw new AdportError7("INVALID_INPUT", "google: offline events require event_source; WEBPAGE events require transaction_id and, if supplied, WEB or APP event_source");
|
|
1326
|
+
if (input2.events.some((value) => value.user_data) && object3(current.context.customer.conversionTrackingSetting).acceptedCustomerDataTerms !== true) throw new AdportError7("INVALID_INPUT", "google: native customer-data terms are not accepted; no user identifiers were uploaded and no terms were accepted");
|
|
1327
|
+
const keys = input2.events.map((value) => value.transaction_id ? `transaction:${value.transaction_id}` : digest3(value));
|
|
1328
|
+
if (new Set(keys).size !== keys.length) throw new AdportError7("INVALID_INPUT", "google: duplicate event identities in this batch; repeated transaction IDs may adjust prior conversions");
|
|
1329
|
+
const target5 = destination.parse({ operatingAccount: { accountType: "GOOGLE_ADS", accountId: current.context.conversion_customer.slice("customers/".length) }, loginAccount: { accountType: "GOOGLE_ADS", accountId: this.client.dataManagerLoginAccount(selected2) }, productDestinationId: input2.conversion_action_id });
|
|
1330
|
+
const body = { destinations: [target5], events: wire2(input2.events), ...input2.consent ? { consent: wire2(input2.consent) } : {}, ...input2.events.some((value) => value.user_data) ? { encoding: "HEX" } : {} };
|
|
1331
|
+
const batchHash = digest3(body), notes2 = ["Preview uses native validateOnly=true and ingests no events. It checks initial validation only; later matching, attribution and processing can still fail.", "Apply accepts a request for asynchronous processing. Use its signed receipt with google_conversion_request_status after the provider-recommended 30 minutes; acceptance is not proof of processed conversions.", "Repeated native transaction IDs may adjust previous events. Event data can affect conversion reporting and automated bidding. Values are whole currency units, not budget micros.", "Preview and audit summaries omit event/user identifiers. The complete payload, destination and snapshot remain bound to the approval token. No automatic retry, permission expansion or terms acceptance."];
|
|
1023
1332
|
let details, resultWarnings = [];
|
|
1024
|
-
return { summary: `Ingest ${input2.events.length} Google conversion event${input2.events.length === 1 ? "" : "s"} with Data Manager`, changes: [`+ ${input2.events.length} ${action2.type} events to conversion action ${input2.conversion_action_id}; operating owner ${
|
|
1333
|
+
return { summary: `Ingest ${input2.events.length} Google conversion event${input2.events.length === 1 ? "" : "s"} with Data Manager`, changes: [`+ ${input2.events.length} ${action2.type} events to conversion action ${input2.conversion_action_id}; operating owner ${target5.operatingAccount.accountId}; login ${target5.loginAccount.accountId}; selected account ${selected2}.`, `Approved batch SHA-256: ${batchHash}. Processing is asynchronous.`], notes: notes2, coercions: [], budgetDeltas: [], resultDetails: () => details, resultWarnings: () => resultWarnings, execute: async (validateOnly) => {
|
|
1025
1334
|
const result2 = await this.client.dataManagerRequest("ingest", { ...body, validateOnly });
|
|
1026
1335
|
resultWarnings = warnings(result2.fieldWarnings);
|
|
1027
1336
|
if (validateOnly) {
|
|
@@ -1029,97 +1338,97 @@ var GoogleDataManagerService = class {
|
|
|
1029
1338
|
return [];
|
|
1030
1339
|
}
|
|
1031
1340
|
const expiresAt = Math.floor(Date.now() / 1e3) + 7 * 86400;
|
|
1032
|
-
const bound = receipt.safeParse({ kind: "google_conversion_ingestion_v1", account_id: selected2, destination:
|
|
1033
|
-
if (!bound.success) throw new
|
|
1341
|
+
const bound = receipt.safeParse({ kind: "google_conversion_ingestion_v1", account_id: selected2, destination: target5, request_id: result2.requestId, batch_sha256: batchHash, event_count: input2.events.length, expires_at: expiresAt });
|
|
1342
|
+
if (!bound.success) throw new AdportError7("PROVIDER_ERROR", "google: ingestion acceptance was not confirmed by a valid request ID; do not retry automatically", { batch_sha256: batchHash, event_count: input2.events.length });
|
|
1034
1343
|
details = { status: "ACCEPTED_FOR_PROCESSING", processed: false, request_id: bound.data.request_id, batch_sha256: batchHash, event_count: input2.events.length, resource_receipt: this.client.dataManagerReceipt(bound.data), receipt_expires_at: new Date(expiresAt * 1e3).toISOString(), next_tool: "google_conversion_request_status", recommended_wait_seconds: 1800, note: "Only request acceptance is confirmed. Inspect status and diagnostics; do not resend this batch automatically." };
|
|
1035
1344
|
return [String(action2.resourceName)];
|
|
1036
1345
|
} };
|
|
1037
1346
|
}
|
|
1038
1347
|
async status(accountId, resourceReceipt) {
|
|
1039
1348
|
const selected2 = normalizeCustomerId(accountId), bound = receipt.safeParse(this.client.verifyDataManagerReceipt(resourceReceipt)), now = Math.floor(Date.now() / 1e3);
|
|
1040
|
-
if (!bound.success || bound.data.account_id !== selected2 || bound.data.expires_at <= now || bound.data.expires_at > now + 7 * 86400) throw new
|
|
1349
|
+
if (!bound.success || bound.data.account_id !== selected2 || bound.data.expires_at <= now || bound.data.expires_at > now + 7 * 86400) throw new AdportError7("INVALID_INPUT", "google: expired or mismatched account ingestion receipt");
|
|
1041
1350
|
const tracking = await this.conversions.context(selected2);
|
|
1042
|
-
if (tracking.conversion_customer !== `customers/${bound.data.destination.operatingAccount.accountId}`) throw new
|
|
1351
|
+
if (tracking.conversion_customer !== `customers/${bound.data.destination.operatingAccount.accountId}`) throw new AdportError7("PENDING_MISMATCH", "google: conversion tracking owner changed since ingestion; status was not requested");
|
|
1043
1352
|
const result2 = await this.client.dataManagerRequest("status", { requestId: bound.data.request_id }), rows = result2.requestStatusPerDestination;
|
|
1044
1353
|
if (rows === void 0 || Array.isArray(rows) && rows.length === 0) return { request_id: bound.data.request_id, batch_sha256: bound.data.batch_sha256, expected_event_count: bound.data.event_count, status: "UNKNOWN", terminal: false, note: "No destination status is available yet. This is not success; wait before checking again. Do not resend events." };
|
|
1045
|
-
if (!Array.isArray(rows) || rows.length !== 1) throw new
|
|
1046
|
-
const row2 =
|
|
1354
|
+
if (!Array.isArray(rows) || rows.length !== 1) throw new AdportError7("PROVIDER_ERROR", "google: Data Manager status destination count differs from the approved request");
|
|
1355
|
+
const row2 = object3(rows[0]), target5 = object3(row2.destination), expected = bound.data.destination;
|
|
1047
1356
|
const matches = (value, wanted) => {
|
|
1048
|
-
const got =
|
|
1357
|
+
const got = object3(value);
|
|
1049
1358
|
return got.accountId === wanted.accountId && (got.accountType === "GOOGLE_ADS" || got.accountType === void 0 && got.product === "GOOGLE_ADS") && (got.product === void 0 || got.product === "GOOGLE_ADS");
|
|
1050
1359
|
};
|
|
1051
|
-
if (!matches(
|
|
1360
|
+
if (!matches(target5.operatingAccount, expected.operatingAccount) || target5.productDestinationId !== expected.productDestinationId || target5.loginAccount !== void 0 && !matches(target5.loginAccount, expected.loginAccount) || target5.linkedAccount !== void 0) throw new AdportError7("PROVIDER_ERROR", "google: Data Manager returned a destination outside the approved ingestion receipt");
|
|
1052
1361
|
const state = typeof row2.requestStatus === "string" && ["SUCCESS", "PARTIAL_SUCCESS", "FAILED", "PROCESSING", "REQUEST_STATUS_UNKNOWN"].includes(row2.requestStatus) ? row2.requestStatus : "UNKNOWN";
|
|
1053
|
-
const terminal = ["SUCCESS", "PARTIAL_SUCCESS", "FAILED"].includes(state), total = count(
|
|
1054
|
-
if (["audienceMembersIngestionStatus", "audienceMembersRemovalStatus", "removeAllAudienceMembersStatus"].some((key2) => row2[key2] !== void 0)) throw new
|
|
1362
|
+
const terminal = ["SUCCESS", "PARTIAL_SUCCESS", "FAILED"].includes(state), total = count(object3(row2.eventsIngestionStatus).recordCount), errors = diagnosticCounts(row2.errorInfo, "errorCounts"), fieldWarnings = diagnosticCounts(row2.warningInfo, "warningCounts");
|
|
1363
|
+
if (["audienceMembersIngestionStatus", "audienceMembersRemovalStatus", "removeAllAudienceMembersStatus"].some((key2) => row2[key2] !== void 0)) throw new AdportError7("PROVIDER_ERROR", "google: non-event Data Manager status returned for an event receipt");
|
|
1055
1364
|
const expectedCount = String(bound.data.event_count), consistent = !terminal || total === expectedCount && [...errors, ...fieldWarnings].every((value) => BigInt(value.record_count) <= BigInt(expectedCount)) && (state !== "SUCCESS" || !errors.some((value) => BigInt(value.record_count) > 0n));
|
|
1056
1365
|
return { request_id: bound.data.request_id, batch_sha256: bound.data.batch_sha256, expected_event_count: bound.data.event_count, status: consistent ? state : "UNKNOWN", native_status: state, terminal: terminal && consistent, ...total !== void 0 ? { record_count: total } : {}, counts_match: terminal ? consistent : null, errors, warnings: fieldWarnings, note: consistent ? "record_count includes successful and failed records. Error and warning reasons can overlap; do not subtract their counts to invent a successful count. SUCCESS may still have warnings." : "Native processed-record count is missing or differs from the approved batch; do not assume completion or resend automatically." };
|
|
1057
1366
|
}
|
|
1058
1367
|
};
|
|
1059
1368
|
function googleDataManagerTools(provider) {
|
|
1060
1369
|
return [
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1370
|
+
defineTool6({ name: "google_data_manager_context", namespace: "google", description: "Read the verified conversion owner, configured login account and existing OAuth Data Manager scope status. Does not change grants, enable APIs, accept terms or upload events.", input: z6.object({ account_id: z6.string() }), annotations: { readOnly: true }, handler: (input2) => provider.dataManager.context(input2.account_id) }),
|
|
1371
|
+
guardedWriteTool6({ name: "google_ingest_conversion_events", namespace: "google", provider: "google", kind: "create", payload: ingest, description: "Ingest 1\u20132000 offline UPLOAD_CLICKS or multi-source WEBPAGE conversion events with Data Manager v1. Requires its separate OAuth scope/API enablement and an action snapshot. Native validateOnly preview; apply returns asynchronous acceptance and an account-bound status receipt. Hashed user data is HEX with explicit consent. No automatic retry." }),
|
|
1372
|
+
defineTool6({ name: "google_conversion_request_status", namespace: "google", description: "Read Data Manager processing status and error/warning counts using the signed receipt from this account\u2019s approved ingestion. Native request IDs alone do not authorize this account-less endpoint. Wait about 30 minutes after acceptance; do not resubmit a processing batch.", input: z6.object({ account_id: z6.string(), resource_receipt: receiptInput }), annotations: { readOnly: true }, handler: (input2) => provider.dataManager.status(input2.account_id, input2.resource_receipt) })
|
|
1064
1373
|
];
|
|
1065
1374
|
}
|
|
1066
1375
|
|
|
1067
1376
|
// src/experiments.ts
|
|
1068
|
-
import { createHash as
|
|
1069
|
-
import { AdportError as
|
|
1070
|
-
import { z as
|
|
1071
|
-
var
|
|
1377
|
+
import { createHash as createHash5 } from "crypto";
|
|
1378
|
+
import { AdportError as AdportError8, defineTool as defineTool7, guardedWriteTool as guardedWriteTool7 } from "@adport/core";
|
|
1379
|
+
import { z as z7 } from "zod";
|
|
1380
|
+
var object4 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
1072
1381
|
var list = (value) => Array.isArray(value) ? value : [];
|
|
1073
|
-
var
|
|
1074
|
-
var
|
|
1075
|
-
var name3 =
|
|
1076
|
-
var date =
|
|
1077
|
-
var systemType =
|
|
1078
|
-
var metricGoal =
|
|
1079
|
-
var experimentRef = { experiment_id:
|
|
1080
|
-
var settings = { name: name3.optional(), description:
|
|
1081
|
-
var performanceMax =
|
|
1382
|
+
var id7 = z7.string().regex(/^[1-9]\d*$/);
|
|
1383
|
+
var hash5 = z7.string().regex(/^[a-f0-9]{64}$/);
|
|
1384
|
+
var name3 = z7.string().trim().min(1).max(1024);
|
|
1385
|
+
var date = z7.iso.date();
|
|
1386
|
+
var systemType = z7.enum(["SEARCH_CUSTOM", "DISPLAY_CUSTOM", "HOTEL_CUSTOM", "YOUTUBE_CUSTOM", "PMAX_REPLACEMENT_SHOPPING"]);
|
|
1387
|
+
var metricGoal = z7.object({ metric: z7.enum(["CLICKS", "IMPRESSIONS", "COST", "CONVERSIONS_PER_INTERACTION_RATE", "COST_PER_CONVERSION", "CONVERSIONS_VALUE_PER_COST", "AVERAGE_CPC", "CTR", "INCREMENTAL_CONVERSIONS", "COMPLETED_VIDEO_VIEWS", "CUSTOM_ALGORITHMS", "CONVERSIONS", "CONVERSION_VALUE"]), direction: z7.enum(["NO_CHANGE", "INCREASE", "DECREASE", "NO_CHANGE_OR_INCREASE", "NO_CHANGE_OR_DECREASE"]) }).strict();
|
|
1388
|
+
var experimentRef = { experiment_id: id7, expected_experiment_hash: hash5 };
|
|
1389
|
+
var settings = { name: name3.optional(), description: z7.string().max(2048).optional(), start_date: date.optional(), end_date: date.optional(), goals: z7.array(metricGoal).max(20).optional() };
|
|
1390
|
+
var performanceMax = z7.object({ budget_amount_micros: z7.number().int().positive().safe(), bidding_strategy_type: z7.enum(["MAXIMIZE_CONVERSIONS", "MAXIMIZE_CONVERSION_VALUE", "TARGET_CPA", "TARGET_ROAS"]), target_cpa_micros: z7.number().int().positive().safe().optional(), target_roas: z7.number().finite().positive().optional() }).strict().superRefine((value, ctx) => {
|
|
1082
1391
|
const cpa = ["MAXIMIZE_CONVERSIONS", "TARGET_CPA"].includes(value.bidding_strategy_type);
|
|
1083
1392
|
if (cpa ? value.target_roas !== void 0 : value.target_cpa_micros !== void 0) ctx.addIssue({ code: "custom", message: "Bidding target must match the selected strategy" });
|
|
1084
1393
|
if (value.bidding_strategy_type === "TARGET_CPA" && value.target_cpa_micros === void 0 || value.bidding_strategy_type === "TARGET_ROAS" && value.target_roas === void 0) ctx.addIssue({ code: "custom", message: "Target bidding strategy requires its matching target" });
|
|
1085
1394
|
});
|
|
1086
|
-
var treatment =
|
|
1087
|
-
var create2 =
|
|
1395
|
+
var treatment = z7.object({ name: name3, traffic_split_percent: z7.number().int().min(1).max(99), performance_max: performanceMax.optional() }).strict();
|
|
1396
|
+
var create2 = z7.object({ ...settings, name: name3, base_campaign_id: id7, expected_base_hash: hash5, type: systemType, suffix: z7.string().min(1).max(100), control_name: name3.default("Control"), control_traffic_split_percent: z7.number().int().min(1).max(99), treatments: z7.array(treatment).min(1).max(20), sync_enabled: z7.boolean().optional(), video_experiment_subtype: z7.enum(["ASSET", "ASSET_UPLIFT", "DEMAND_GEN_ASSET"]).optional() }).strict().superRefine((value, ctx) => {
|
|
1088
1397
|
if (value.control_traffic_split_percent + value.treatments.reduce((sum, arm) => sum + arm.traffic_split_percent, 0) !== 100) ctx.addIssue({ code: "custom", message: "Control and treatment traffic shares must total 100" });
|
|
1089
1398
|
if ((/* @__PURE__ */ new Set([value.control_name, ...value.treatments.map((arm) => arm.name)])).size !== value.treatments.length + 1) ctx.addIssue({ code: "custom", message: "Arm names must be unique within this experiment" });
|
|
1090
1399
|
if (value.type === "YOUTUBE_CUSTOM" ? !value.video_experiment_subtype : value.video_experiment_subtype !== void 0) ctx.addIssue({ code: "custom", message: "Video subtype is required only for YOUTUBE_CUSTOM" });
|
|
1091
1400
|
if (value.type !== "PMAX_REPLACEMENT_SHOPPING" && value.treatments.some((arm) => arm.performance_max)) ctx.addIssue({ code: "custom", message: "Performance Max settings apply only to PMAX_REPLACEMENT_SHOPPING" });
|
|
1092
1401
|
if (value.start_date && value.end_date && value.start_date > value.end_date) ctx.addIssue({ code: "custom", message: "End date must not precede start date" });
|
|
1093
1402
|
});
|
|
1094
|
-
var update2 =
|
|
1095
|
-
var armPatch =
|
|
1096
|
-
var patchArms =
|
|
1097
|
-
var addArms =
|
|
1098
|
-
var removeArms =
|
|
1099
|
-
var action =
|
|
1100
|
-
var graduate = action.safeExtend({ campaign_id:
|
|
1403
|
+
var update2 = z7.object({ ...experimentRef, ...settings }).strict().refine((value) => Object.entries(value).some(([key2, item]) => !["experiment_id", "expected_experiment_hash"].includes(key2) && item !== void 0), "Supply an editable experiment field");
|
|
1404
|
+
var armPatch = z7.object({ arm_id: id7, name: name3.optional(), traffic_split_percent: z7.number().int().min(1).max(99).optional() }).strict();
|
|
1405
|
+
var patchArms = z7.object({ ...experimentRef, arms: z7.array(armPatch).min(1).max(100) }).strict();
|
|
1406
|
+
var addArms = z7.object({ ...experimentRef, treatments: z7.array(treatment).min(1).max(20), existing_arms: z7.array(armPatch).min(1).max(100) }).strict();
|
|
1407
|
+
var removeArms = z7.object({ ...experimentRef, arm_ids: z7.array(id7).min(1).max(100), remaining_arms: z7.array(armPatch).max(100) }).strict();
|
|
1408
|
+
var action = z7.object({ ...experimentRef, confirm_serving_changes: z7.literal(true) }).strict();
|
|
1409
|
+
var graduate = action.safeExtend({ campaign_id: id7, campaign_budget_id: id7, expected_budget_hash: hash5 });
|
|
1101
1410
|
var exFields = "experiment.resource_name, experiment.experiment_id, experiment.name, experiment.description, experiment.suffix, experiment.type, experiment.status, experiment.start_date, experiment.end_date, experiment.sync_enabled, experiment.goals, experiment.video_experiment.video_experiment_subtype, experiment.optimize_assets_experiment.optimize_assets_experiment_subtype, experiment.long_running_operation, experiment.promote_status";
|
|
1102
1411
|
var armFields = "experiment_arm.resource_name, experiment_arm.experiment, experiment_arm.name, experiment_arm.control, experiment_arm.traffic_split, experiment_arm.campaigns, experiment_arm.in_design_campaigns";
|
|
1103
1412
|
var budgetFields = "campaign_budget.resource_name, campaign_budget.id, campaign_budget.name, campaign_budget.status, campaign_budget.amount_micros, campaign_budget.total_amount_micros, campaign_budget.explicitly_shared, campaign_budget.reference_count, campaign_budget.period, campaign_budget.delivery_method";
|
|
1104
1413
|
var campaignFields = `campaign.resource_name, campaign.id, campaign.name, campaign.status, campaign.advertising_channel_type, campaign.experiment_type, campaign.base_campaign, campaign.campaign_budget, campaign.bidding_strategy_type, campaign.bidding_strategy, campaign.manual_cpc.enhanced_cpc_enabled, campaign.maximize_conversions.target_cpa_micros, campaign.maximize_conversion_value.target_roas, campaign.target_cpa.target_cpa_micros, campaign.target_roas.target_roas, campaign.target_spend.cpc_bid_ceiling_micros, ${budgetFields}`;
|
|
1105
1414
|
var kinds = { google_create_experiment: "create", google_update_experiment: "update", google_add_experiment_arms: "create", google_update_experiment_arms: "update", google_remove_experiment_arms: "remove", google_remove_experiment: "remove", google_schedule_experiment: "update", google_end_experiment: "update", google_promote_experiment: "update", google_graduate_experiment: "update" };
|
|
1106
1415
|
var GOOGLE_EXPERIMENT_WRITES = new Set(Object.keys(kinds));
|
|
1107
|
-
function
|
|
1108
|
-
if (Array.isArray(value)) return value.map(
|
|
1109
|
-
if (value !== null && typeof value === "object") return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key2, item]) => [key2,
|
|
1416
|
+
function canonical4(value) {
|
|
1417
|
+
if (Array.isArray(value)) return value.map(canonical4);
|
|
1418
|
+
if (value !== null && typeof value === "object") return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key2, item]) => [key2, canonical4(item)]));
|
|
1110
1419
|
return value;
|
|
1111
1420
|
}
|
|
1112
|
-
var
|
|
1421
|
+
var digest4 = (value) => createHash5("sha256").update(JSON.stringify(canonical4(value))).digest("hex");
|
|
1113
1422
|
var camel2 = (key2) => key2.replace(/_([a-z])/g, (_match, char) => char.toUpperCase());
|
|
1114
1423
|
function micros(value) {
|
|
1115
|
-
if (typeof value !== "string" || !/^\d+$/.test(value) || BigInt(value) > BigInt(Number.MAX_SAFE_INTEGER)) throw new
|
|
1424
|
+
if (typeof value !== "string" || !/^\d+$/.test(value) || BigInt(value) > BigInt(Number.MAX_SAFE_INTEGER)) throw new AdportError8("PROVIDER_ERROR", "google: experiment budget micros are missing or outside the shared policy integer range");
|
|
1116
1425
|
return Number(value);
|
|
1117
1426
|
}
|
|
1118
1427
|
function statusError(value) {
|
|
1119
|
-
const row2 =
|
|
1120
|
-
return { code: typeof row2.code === "number" && Number.isInteger(row2.code) ? row2.code : null, errors: list(row2.details).flatMap((detail) => list(
|
|
1121
|
-
const error =
|
|
1122
|
-
return { codes: Object.entries(
|
|
1428
|
+
const row2 = object4(value);
|
|
1429
|
+
return { code: typeof row2.code === "number" && Number.isInteger(row2.code) ? row2.code : null, errors: list(row2.details).flatMap((detail) => list(object4(detail).errors)).map((value2) => {
|
|
1430
|
+
const error = object4(value2);
|
|
1431
|
+
return { codes: Object.entries(object4(error.errorCode)).flatMap(([key2, val]) => typeof val === "string" && /^[A-Z_]+$/.test(val) ? [`${key2}.${val}`] : []), fields: list(object4(error.location).fieldPathElements).flatMap((item) => typeof object4(item).fieldName === "string" && /^[a-z][a-zA-Z0-9_]*$/.test(String(object4(item).fieldName)) ? [object4(item).fieldName] : []) };
|
|
1123
1432
|
}) };
|
|
1124
1433
|
}
|
|
1125
1434
|
var GoogleExperimentService = class {
|
|
@@ -1128,72 +1437,72 @@ var GoogleExperimentService = class {
|
|
|
1128
1437
|
}
|
|
1129
1438
|
client;
|
|
1130
1439
|
async account(accountId) {
|
|
1131
|
-
const selected2 = normalizeCustomerId(accountId), rows = await this.client.search(selected2, "SELECT customer.resource_name, customer.id, customer.currency_code, customer.time_zone FROM customer LIMIT 2", { maxRows: 2 }), customer =
|
|
1132
|
-
if (rows.length !== 1 || customer.id !== selected2 || customer.resourceName !== `customers/${selected2}` || typeof customer.currencyCode !== "string" || !/^[A-Z]{3}$/.test(customer.currencyCode) || typeof customer.timeZone !== "string" || !customer.timeZone) throw new
|
|
1440
|
+
const selected2 = normalizeCustomerId(accountId), rows = await this.client.search(selected2, "SELECT customer.resource_name, customer.id, customer.currency_code, customer.time_zone FROM customer LIMIT 2", { maxRows: 2 }), customer = object4(rows[0]?.customer);
|
|
1441
|
+
if (rows.length !== 1 || customer.id !== selected2 || customer.resourceName !== `customers/${selected2}` || typeof customer.currencyCode !== "string" || !/^[A-Z]{3}$/.test(customer.currencyCode) || typeof customer.timeZone !== "string" || !customer.timeZone) throw new AdportError8("PROVIDER_ERROR", "google: invalid experiment customer identity, currency or timezone");
|
|
1133
1442
|
return customer;
|
|
1134
1443
|
}
|
|
1135
1444
|
experiment(value, selected2) {
|
|
1136
|
-
const row2 =
|
|
1137
|
-
if (!match || row2.experimentId !== match[1] || typeof row2.name !== "string" || typeof row2.type !== "string" || typeof row2.status !== "string") throw new
|
|
1445
|
+
const row2 = object4(value), match = typeof row2.resourceName === "string" ? row2.resourceName.match(new RegExp(`^customers/${selected2}/experiments/([1-9]\\d*)$`)) : null;
|
|
1446
|
+
if (!match || row2.experimentId !== match[1] || typeof row2.name !== "string" || typeof row2.type !== "string" || typeof row2.status !== "string") throw new AdportError8("PROVIDER_ERROR", "google: invalid experiment identity or configuration");
|
|
1138
1447
|
return row2;
|
|
1139
1448
|
}
|
|
1140
1449
|
campaignName(value, selected2) {
|
|
1141
|
-
if (typeof value !== "string" || !new RegExp(`^customers/${selected2}/campaigns/[1-9]\\d*$`).test(value)) throw new
|
|
1450
|
+
if (typeof value !== "string" || !new RegExp(`^customers/${selected2}/campaigns/[1-9]\\d*$`).test(value)) throw new AdportError8("PROVIDER_ERROR", "google: experiment refers to a campaign outside the selected account");
|
|
1142
1451
|
return value;
|
|
1143
1452
|
}
|
|
1144
1453
|
async campaigns(selected2, names) {
|
|
1145
1454
|
const wanted = [...new Set(names.map((value) => this.campaignName(value, selected2)))].sort();
|
|
1146
1455
|
if (!wanted.length) return [];
|
|
1147
|
-
if (wanted.length > 1e3) throw new
|
|
1456
|
+
if (wanted.length > 1e3) throw new AdportError8("INVALID_INPUT", "google: experiment campaign context exceeds the complete-read bound");
|
|
1148
1457
|
const rows = await this.client.search(selected2, `SELECT ${campaignFields} FROM campaign WHERE campaign.resource_name IN (${wanted.map((value) => `'${value}'`).join(", ")}) LIMIT ${wanted.length + 1}`, { maxRows: wanted.length + 1, includeDrafts: true });
|
|
1149
1458
|
const result2 = rows.map((value) => {
|
|
1150
|
-
const campaign =
|
|
1151
|
-
if (!wanted.includes(resource) || campaign.id !== resource.split("/").at(-1) || !["ENABLED", "PAUSED", "REMOVED"].includes(String(campaign.status)) || campaign.campaignBudget !== budget.resourceName || typeof budget.resourceName !== "string" || !new RegExp(`^customers/${selected2}/campaignBudgets/[1-9]\\d*$`).test(budget.resourceName) || budget.period !== "DAILY") throw new
|
|
1459
|
+
const campaign = object4(value.campaign), budget = object4(value.campaignBudget), resource = this.campaignName(campaign.resourceName, selected2);
|
|
1460
|
+
if (!wanted.includes(resource) || campaign.id !== resource.split("/").at(-1) || !["ENABLED", "PAUSED", "REMOVED"].includes(String(campaign.status)) || campaign.campaignBudget !== budget.resourceName || typeof budget.resourceName !== "string" || !new RegExp(`^customers/${selected2}/campaignBudgets/[1-9]\\d*$`).test(budget.resourceName) || budget.period !== "DAILY") throw new AdportError8("PROVIDER_ERROR", "google: incomplete experiment campaign identity, status or daily budget");
|
|
1152
1461
|
return { campaign, budget, budget_micros: micros(budget.amountMicros ?? "0") };
|
|
1153
1462
|
});
|
|
1154
|
-
if (result2.length !== wanted.length || new Set(result2.map((value) => value.campaign.resourceName)).size !== result2.length) throw new
|
|
1463
|
+
if (result2.length !== wanted.length || new Set(result2.map((value) => value.campaign.resourceName)).size !== result2.length) throw new AdportError8("INVALID_INPUT", "google: complete experiment campaign context was not available, including native drafts");
|
|
1155
1464
|
return result2.sort((a, b) => String(a.campaign.resourceName).localeCompare(String(b.campaign.resourceName)));
|
|
1156
1465
|
}
|
|
1157
1466
|
async list(input2) {
|
|
1158
|
-
const selected2 = normalizeCustomerId(input2.account_id), predicates = [...!input2.include_removed ? ["experiment.status != 'REMOVED'"] : [], ...input2.after_experiment_id ? [`experiment.experiment_id > ${
|
|
1467
|
+
const selected2 = normalizeCustomerId(input2.account_id), predicates = [...!input2.include_removed ? ["experiment.status != 'REMOVED'"] : [], ...input2.after_experiment_id ? [`experiment.experiment_id > ${id7.parse(input2.after_experiment_id)}`] : []];
|
|
1159
1468
|
const rows = await this.client.search(selected2, `SELECT ${exFields} FROM experiment${predicates.length ? ` WHERE ${predicates.join(" AND ")}` : ""} ORDER BY experiment.experiment_id ASC LIMIT ${input2.limit + 1}`, { maxRows: input2.limit + 1 }), experiments = rows.map((value) => this.experiment(value.experiment, selected2));
|
|
1160
|
-
if (experiments.some((value, index) => BigInt(String(value.experimentId)) <= BigInt(index ? String(experiments[index - 1].experimentId) : input2.after_experiment_id ?? "0"))) throw new
|
|
1469
|
+
if (experiments.some((value, index) => BigInt(String(value.experimentId)) <= BigInt(index ? String(experiments[index - 1].experimentId) : input2.after_experiment_id ?? "0"))) throw new AdportError8("PROVIDER_ERROR", "google: experiment continuation did not advance");
|
|
1161
1470
|
return { experiments: experiments.slice(0, input2.limit), truncated: experiments.length > input2.limit, ...experiments.length > input2.limit ? { next_cursor: String(experiments[input2.limit - 1].experimentId) } : {} };
|
|
1162
1471
|
}
|
|
1163
1472
|
async context(input2) {
|
|
1164
1473
|
const selected2 = normalizeCustomerId(input2.account_id), customer = await this.account(selected2);
|
|
1165
1474
|
let experiment, arms = [], related = [];
|
|
1166
1475
|
if (input2.experiment_id) {
|
|
1167
|
-
|
|
1476
|
+
id7.parse(input2.experiment_id);
|
|
1168
1477
|
const resource = `customers/${selected2}/experiments/${input2.experiment_id}`, rows = await this.client.search(selected2, `SELECT ${exFields} FROM experiment WHERE experiment.resource_name = '${resource}' LIMIT 2`, { maxRows: 2 });
|
|
1169
|
-
if (rows.length !== 1) throw new
|
|
1478
|
+
if (rows.length !== 1) throw new AdportError8("INVALID_INPUT", "google: experiment was not available in the selected account");
|
|
1170
1479
|
experiment = this.experiment(rows[0].experiment, selected2);
|
|
1171
|
-
if (experiment.resourceName !== resource) throw new
|
|
1480
|
+
if (experiment.resourceName !== resource) throw new AdportError8("PROVIDER_ERROR", "google: experiment ID mismatch");
|
|
1172
1481
|
const armRows = await this.client.search(selected2, `SELECT ${armFields} FROM experiment_arm WHERE experiment_arm.experiment = '${resource}' LIMIT 1001`, { maxRows: 1001 });
|
|
1173
|
-
if (armRows.length > 1e3) throw new
|
|
1482
|
+
if (armRows.length > 1e3) throw new AdportError8("INVALID_INPUT", "google: complete arm context exceeds the read bound");
|
|
1174
1483
|
arms = armRows.map((value) => {
|
|
1175
|
-
const arm =
|
|
1176
|
-
if (typeof arm.resourceName !== "string" || !new RegExp(`^customers/${selected2}/experimentArms/${input2.experiment_id}~[1-9]\\d*$`).test(arm.resourceName) || arm.experiment !== resource || typeof arm.name !== "string" || !/^\d+$/.test(String(arm.trafficSplit ?? "0")) || BigInt(String(arm.trafficSplit ?? "0")) > 100n) throw new
|
|
1484
|
+
const arm = object4(value.experimentArm);
|
|
1485
|
+
if (typeof arm.resourceName !== "string" || !new RegExp(`^customers/${selected2}/experimentArms/${input2.experiment_id}~[1-9]\\d*$`).test(arm.resourceName) || arm.experiment !== resource || typeof arm.name !== "string" || !/^\d+$/.test(String(arm.trafficSplit ?? "0")) || BigInt(String(arm.trafficSplit ?? "0")) > 100n) throw new AdportError8("PROVIDER_ERROR", "google: invalid experiment arm identity or traffic split");
|
|
1177
1486
|
const campaigns = list(arm.campaigns).map((value2) => this.campaignName(value2, selected2)).sort(), drafts = list(arm.inDesignCampaigns).map((value2) => this.campaignName(value2, selected2)).sort();
|
|
1178
1487
|
return { ...arm, resourceName: arm.resourceName, control: arm.control === true, campaigns, inDesignCampaigns: drafts };
|
|
1179
1488
|
}).sort((a, b) => String(a.resourceName).localeCompare(String(b.resourceName)));
|
|
1180
|
-
if (new Set(arms.map((value) => value.resourceName)).size !== arms.length) throw new
|
|
1489
|
+
if (new Set(arms.map((value) => value.resourceName)).size !== arms.length) throw new AdportError8("PROVIDER_ERROR", "google: duplicate experiment arms");
|
|
1181
1490
|
related = await this.campaigns(selected2, arms.flatMap((arm) => [...list(arm.campaigns), ...list(arm.inDesignCampaigns)]).map(String));
|
|
1182
1491
|
}
|
|
1183
|
-
const base2 = input2.base_campaign_id ? (await this.campaigns(selected2, [`customers/${selected2}/campaigns/${
|
|
1492
|
+
const base2 = input2.base_campaign_id ? (await this.campaigns(selected2, [`customers/${selected2}/campaigns/${id7.parse(input2.base_campaign_id)}`]))[0] : void 0;
|
|
1184
1493
|
let budget;
|
|
1185
1494
|
if (input2.campaign_budget_id) {
|
|
1186
|
-
const resource = `customers/${selected2}/campaignBudgets/${
|
|
1187
|
-
budget =
|
|
1188
|
-
if (rows.length !== 1 || budget.resourceName !== resource || budget.period !== "DAILY") throw new
|
|
1495
|
+
const resource = `customers/${selected2}/campaignBudgets/${id7.parse(input2.campaign_budget_id)}`, rows = await this.client.search(selected2, `SELECT ${budgetFields} FROM campaign_budget WHERE campaign_budget.resource_name = '${resource}' LIMIT 2`, { maxRows: 2 });
|
|
1496
|
+
budget = object4(rows[0]?.campaignBudget);
|
|
1497
|
+
if (rows.length !== 1 || budget.resourceName !== resource || budget.period !== "DAILY") throw new AdportError8("INVALID_INPUT", "google: graduation daily budget was not available in the selected account");
|
|
1189
1498
|
micros(budget.amountMicros ?? "0");
|
|
1190
1499
|
}
|
|
1191
|
-
return { account: customer, ...experiment ? { experiment, arms, campaigns: related, experiment_snapshot_hash:
|
|
1500
|
+
return { account: customer, ...experiment ? { experiment, arms, campaigns: related, experiment_snapshot_hash: digest4({ customer, experiment, arms, campaigns: related }) } : {}, ...base2 ? { base_campaign: base2, base_snapshot_hash: digest4({ customer, base: base2 }) } : {}, ...budget ? { graduation_budget: budget, budget_snapshot_hash: digest4({ customer, budget }) } : {}, note: "Snapshots cover the returned experiment/arms, campaign status/bidding and budget configuration; they do not freeze all underlying ads, keywords or targeting, and Google provides no atomic compare-and-set. Dates use the account timezone. Intra-campaign, asset-optimization and campaign-mix creation require separate native workflows." };
|
|
1192
1501
|
}
|
|
1193
1502
|
async checked(accountId, value) {
|
|
1194
1503
|
const context = await this.context({ account_id: accountId, experiment_id: value.experiment_id, ..."campaign_budget_id" in value ? { campaign_budget_id: value.campaign_budget_id } : {} });
|
|
1195
|
-
if (context.experiment_snapshot_hash !== value.expected_experiment_hash) throw new
|
|
1196
|
-
if (context.experiment.status === "REMOVED") throw new
|
|
1504
|
+
if (context.experiment_snapshot_hash !== value.expected_experiment_hash) throw new AdportError8("PENDING_MISMATCH", "google: experiment, arms or campaign/budget context changed; read it again");
|
|
1505
|
+
if (context.experiment.status === "REMOVED") throw new AdportError8("INVALID_INPUT", "google: removed experiment cannot be changed");
|
|
1197
1506
|
return context;
|
|
1198
1507
|
}
|
|
1199
1508
|
fields(value) {
|
|
@@ -1205,11 +1514,11 @@ var GoogleExperimentService = class {
|
|
|
1205
1514
|
if (validateOnly) return [];
|
|
1206
1515
|
const ids2 = result2.results?.map((value) => value.resourceName);
|
|
1207
1516
|
if (!ids2 || ids2.length !== operations.length || ids2.some((value, index) => {
|
|
1208
|
-
const operation = operations[index],
|
|
1209
|
-
const armExperiment = String(
|
|
1210
|
-
const pattern = service === "experiments" ? `^customers/${selected2}/experiments/[1-9]\\d*$` : `^customers/${selected2}/experimentArms/${
|
|
1211
|
-
return typeof value !== "string" || !new RegExp(pattern).test(value) ||
|
|
1212
|
-
})) throw new
|
|
1517
|
+
const operation = operations[index], target5 = expected?.[index] ?? object4(operation.update).resourceName ?? operation.remove;
|
|
1518
|
+
const armExperiment = String(object4(operation.create).experiment ?? "").split("/").at(-1);
|
|
1519
|
+
const pattern = service === "experiments" ? `^customers/${selected2}/experiments/[1-9]\\d*$` : `^customers/${selected2}/experimentArms/${target5 ? "[1-9]\\d*" : armExperiment}~[1-9]\\d*$`;
|
|
1520
|
+
return typeof value !== "string" || !new RegExp(pattern).test(value) || target5 !== void 0 && value !== target5;
|
|
1521
|
+
})) throw new AdportError8("PROVIDER_ERROR", "google: experiment mutation receipt was not confirmed; reconcile before retrying", { resource_ids: ids2?.filter((value) => typeof value === "string") ?? [] });
|
|
1213
1522
|
return ids2;
|
|
1214
1523
|
} };
|
|
1215
1524
|
}
|
|
@@ -1218,48 +1527,48 @@ var GoogleExperimentService = class {
|
|
|
1218
1527
|
}
|
|
1219
1528
|
async pauseDrafts(selected2, experimentId, createdArms, base2, treatmentBounds, forcePaused) {
|
|
1220
1529
|
const context = await this.context({ account_id: selected2, experiment_id: experimentId }), fresh = createdArms.map((resource) => context.arms.find((value) => value.resourceName === resource)), treatments = fresh.filter((value) => Boolean(value) && !value.control), drafts = treatments.flatMap((value) => list(value.inDesignCampaigns).map(String));
|
|
1221
|
-
if (context.experiment.status !== "SETUP" || fresh.some((value) => !value) || fresh.some((value) => value?.control && (list(value.campaigns).length !== 1 || list(value.campaigns)[0] !== base2.campaign.resourceName)) || treatments.length !== treatmentBounds.length || treatments.some((value) => list(value.inDesignCampaigns).length !== 1 || list(value.campaigns).length > 0) || drafts.length !== treatments.length || new Set(drafts).size !== drafts.length || drafts.includes(String(base2.campaign.resourceName))) throw new
|
|
1530
|
+
if (context.experiment.status !== "SETUP" || fresh.some((value) => !value) || fresh.some((value) => value?.control && (list(value.campaigns).length !== 1 || list(value.campaigns)[0] !== base2.campaign.resourceName)) || treatments.length !== treatmentBounds.length || treatments.some((value) => list(value.inDesignCampaigns).length !== 1 || list(value.campaigns).length > 0) || drafts.length !== treatments.length || new Set(drafts).size !== drafts.length || drafts.includes(String(base2.campaign.resourceName))) throw new AdportError8("PROVIDER_ERROR", "google: generated treatment drafts were not confirmed; inspect the SETUP experiment before retrying", { resource_ids: [String(context.experiment.resourceName), ...createdArms] });
|
|
1222
1531
|
const copies = context.campaigns.filter((value) => drafts.includes(String(value.campaign.resourceName)));
|
|
1223
|
-
if (copies.length !== drafts.length || copies.some((value) => value.campaign.experimentType !== "DRAFT" || value.campaign.baseCampaign && value.campaign.baseCampaign !== base2.campaign.resourceName)) throw new
|
|
1532
|
+
if (copies.length !== drafts.length || copies.some((value) => value.campaign.experimentType !== "DRAFT" || value.campaign.baseCampaign && value.campaign.baseCampaign !== base2.campaign.resourceName)) throw new AdportError8("PROVIDER_ERROR", "google: native generated campaign ownership/type mismatch; SETUP was not scheduled", { resource_ids: [...createdArms, ...drafts] });
|
|
1224
1533
|
if (forcePaused) {
|
|
1225
1534
|
const operations = copies.filter((value) => value.campaign.status !== "PAUSED").map((value) => ({ update: { resourceName: value.campaign.resourceName, status: "PAUSED" }, updateMask: "status" }));
|
|
1226
1535
|
if (operations.length) {
|
|
1227
1536
|
await this.client.mutate(selected2, "campaigns", operations, { validateOnly: true });
|
|
1228
1537
|
const result2 = await this.client.mutate(selected2, "campaigns", operations, { validateOnly: false }), names = result2.results?.map((value) => value.resourceName);
|
|
1229
|
-
if (!names || names.length !== operations.length || names.some((value, index) => value !== operations[index].update.resourceName)) throw new
|
|
1538
|
+
if (!names || names.length !== operations.length || names.some((value, index) => value !== operations[index].update.resourceName)) throw new AdportError8("PROVIDER_ERROR", "google: draft pause was not confirmed; inspect these SETUP drafts before retrying", { resource_ids: drafts });
|
|
1230
1539
|
}
|
|
1231
1540
|
}
|
|
1232
1541
|
const after = await this.campaigns(selected2, drafts);
|
|
1233
|
-
if (after.some((value) => forcePaused && value.campaign.status !== "PAUSED" || value.budget_micros > treatmentBounds[drafts.indexOf(String(value.campaign.resourceName))])) throw new
|
|
1542
|
+
if (after.some((value) => forcePaused && value.campaign.status !== "PAUSED" || value.budget_micros > treatmentBounds[drafts.indexOf(String(value.campaign.resourceName))])) throw new AdportError8("PROVIDER_ERROR", "google: copied draft status or budget exceeds the approved plan; the experiment remains unscheduled", { resource_ids: drafts });
|
|
1234
1543
|
return drafts;
|
|
1235
1544
|
}
|
|
1236
1545
|
async plan(op, guard) {
|
|
1237
|
-
if (!GOOGLE_EXPERIMENT_WRITES.has(op.tool) || op.provider !== "google" || op.kind !== kinds[op.tool]) throw new
|
|
1546
|
+
if (!GOOGLE_EXPERIMENT_WRITES.has(op.tool) || op.provider !== "google" || op.kind !== kinds[op.tool]) throw new AdportError8("INVALID_INPUT", "google: invalid experiment operation kind");
|
|
1238
1547
|
const selected2 = normalizeCustomerId(op.accountId);
|
|
1239
1548
|
if (op.tool === "google_create_experiment") return this.create(selected2, create2.parse(op.payload), guard);
|
|
1240
1549
|
if (["google_add_experiment_arms", "google_update_experiment_arms", "google_remove_experiment_arms"].includes(op.tool)) return this.changeArms(selected2, op, guard);
|
|
1241
|
-
const input2 = op.tool === "google_update_experiment" ? update2.parse(op.payload) : op.tool === "google_graduate_experiment" ? graduate.parse(op.payload) : ["google_schedule_experiment", "google_promote_experiment"].includes(op.tool) ? action.parse(op.payload) :
|
|
1550
|
+
const input2 = op.tool === "google_update_experiment" ? update2.parse(op.payload) : op.tool === "google_graduate_experiment" ? graduate.parse(op.payload) : ["google_schedule_experiment", "google_promote_experiment"].includes(op.tool) ? action.parse(op.payload) : z7.object(experimentRef).strict().parse(op.payload);
|
|
1242
1551
|
const context = await this.checked(selected2, input2), experiment = context.experiment, resource = String(experiment.resourceName);
|
|
1243
1552
|
if (op.tool === "google_remove_experiment") return this.mutation(selected2, "experiments", [{ remove: resource }], `Remove Google experiment \u201C${String(experiment.name)}\u201D`, [`- ${resource}; arms ${context.arms.map((value) => value.resourceName).join(", ")}. Native removal may also remove its draft/treatment copies; base campaigns are retained.`], [resource]);
|
|
1244
1553
|
if (op.tool === "google_update_experiment") {
|
|
1245
1554
|
const { experiment_id: _id, expected_experiment_hash: _hash, ...settings2 } = update2.parse(input2), fields5 = this.fields(settings2), masks = Object.keys(settings2).filter((key2) => settings2[key2] !== void 0);
|
|
1246
1555
|
const start = fields5.startDate ?? experiment.startDate, end = fields5.endDate ?? experiment.endDate;
|
|
1247
|
-
if (typeof start === "string" && typeof end === "string" && start > end) throw new
|
|
1556
|
+
if (typeof start === "string" && typeof end === "string" && start > end) throw new AdportError8("INVALID_INPUT", "google: end date precedes start date");
|
|
1248
1557
|
const plan = this.mutation(selected2, "experiments", [{ update: { resourceName: resource, ...fields5 }, updateMask: masks.join(",") }], `Update Google experiment \u201C${String(experiment.name)}\u201D`, masks.map((key2) => `~ ${key2}: ${JSON.stringify(experiment[camel2(key2)] ?? null)} \u2192 ${JSON.stringify(fields5[camel2(key2)])}`), [resource]);
|
|
1249
1558
|
return { ...plan, fieldChanges: masks.map((key2) => ({ field: key2, before: JSON.stringify(experiment[camel2(key2)] ?? null), after: JSON.stringify(fields5[camel2(key2)]) })) };
|
|
1250
1559
|
}
|
|
1251
|
-
if (op.tool === "google_schedule_experiment" && guard.forcePausedCreation) throw new
|
|
1560
|
+
if (op.tool === "google_schedule_experiment" && guard.forcePausedCreation) throw new AdportError8("POLICY_VIOLATION", "google: ScheduleExperiment can materialize serving campaigns and exposes no paused-creation flag. paused_creation blocks this native active workflow; no schedule request was sent.");
|
|
1252
1561
|
const methods = { google_schedule_experiment: "scheduleExperiment", google_end_experiment: "endExperiment", google_promote_experiment: "promoteExperiment", google_graduate_experiment: "graduateExperiment" };
|
|
1253
1562
|
const method = methods[op.tool];
|
|
1254
|
-
if (!method) throw new
|
|
1563
|
+
if (!method) throw new AdportError8("INVALID_INPUT", "google: unsupported experiment lifecycle action");
|
|
1255
1564
|
let payload = {}, deltas = [];
|
|
1256
1565
|
if (op.tool === "google_graduate_experiment") {
|
|
1257
|
-
const value = graduate.parse(input2),
|
|
1566
|
+
const value = graduate.parse(input2), target5 = `customers/${selected2}/campaigns/${value.campaign_id}`, campaign = context.campaigns.find((value2) => value2.campaign.resourceName === target5), treatmentNames = context.arms.filter((value2) => !value2.control).flatMap((value2) => list(value2.campaigns));
|
|
1258
1567
|
const budget = context.graduation_budget;
|
|
1259
|
-
if (!campaign || !treatmentNames.includes(
|
|
1260
|
-
if (budget.status !== "ENABLED" || budget.explicitlyShared === true || BigInt(String(budget.referenceCount ?? "0")) > (campaign.campaign.campaignBudget === budget.resourceName ? 1n : 0n)) throw new
|
|
1568
|
+
if (!campaign || !treatmentNames.includes(target5) || campaign.campaign.experimentType !== "EXPERIMENT" || context.budget_snapshot_hash !== value.expected_budget_hash) throw new AdportError8("PENDING_MISMATCH", "google: graduation campaign or budget does not match the current treatment and budget snapshot");
|
|
1569
|
+
if (budget.status !== "ENABLED" || budget.explicitlyShared === true || BigInt(String(budget.referenceCount ?? "0")) > (campaign.campaign.campaignBudget === budget.resourceName ? 1n : 0n)) throw new AdportError8("INVALID_INPUT", "google: graduation needs an available non-shared budget unused by other campaigns");
|
|
1261
1570
|
deltas = [{ target: `graduated campaign ${value.campaign_id} daily budget`, fromMicros: campaign.budget_micros, toMicros: micros(budget.amountMicros ?? "0") }];
|
|
1262
|
-
payload = { campaignBudgetMappings: [{ experimentCampaign:
|
|
1571
|
+
payload = { campaignBudgetMappings: [{ experimentCampaign: target5, campaignBudget: budget.resourceName }] };
|
|
1263
1572
|
} else if (op.tool !== "google_end_experiment") {
|
|
1264
1573
|
const maximum = Math.max(0, ...context.campaigns.map((value) => value.budget_micros));
|
|
1265
1574
|
deltas = context.campaigns.map((value) => ({ target: `${String(value.campaign.name)} native lifecycle daily budget ceiling`, fromMicros: value.budget_micros, toMicros: maximum }));
|
|
@@ -1270,7 +1579,7 @@ var GoogleExperimentService = class {
|
|
|
1270
1579
|
if (validateOnly) return [];
|
|
1271
1580
|
if (method === "scheduleExperiment" || method === "promoteExperiment") {
|
|
1272
1581
|
const operation = result2.name;
|
|
1273
|
-
if (typeof operation !== "string" || !new RegExp(`^customers/${selected2}/operations/[^\\s/\\\\?#%]{1,512}$`).test(operation) || [".", ".."].includes(operation.split("/").at(-1)) ||
|
|
1582
|
+
if (typeof operation !== "string" || !new RegExp(`^customers/${selected2}/operations/[^\\s/\\\\?#%]{1,512}$`).test(operation) || [".", ".."].includes(operation.split("/").at(-1)) || object4(result2.metadata).experiment !== void 0 && object4(result2.metadata).experiment !== resource) throw new AdportError8("PROVIDER_ERROR", "google: experiment operation acknowledgement was not confirmed; inspect native state before retrying", { resource_ids: [resource] });
|
|
1274
1583
|
details = { status: "ACCEPTED_FOR_PROCESSING", processed: false, operation_name: operation, experiment_id: experiment.experimentId, next_tool: "google_experiment_operation", note: "Only native submission is confirmed. Poll the operation and inspect experiment async errors; do not resubmit automatically." };
|
|
1275
1584
|
} else details = { status: "NATIVE_ACTION_ACCEPTED", experiment_id: experiment.experimentId, next_tool: "google_experiment_context", note: "The synchronous native command returned successfully. Read current experiment/campaign state before further changes." };
|
|
1276
1585
|
return [resource];
|
|
@@ -1278,9 +1587,9 @@ var GoogleExperimentService = class {
|
|
|
1278
1587
|
}
|
|
1279
1588
|
async create(selected2, input2, guard) {
|
|
1280
1589
|
const context = await this.context({ account_id: selected2, base_campaign_id: input2.base_campaign_id }), base2 = context.base_campaign;
|
|
1281
|
-
if (context.base_snapshot_hash !== input2.expected_base_hash) throw new
|
|
1590
|
+
if (context.base_snapshot_hash !== input2.expected_base_hash) throw new AdportError8("PENDING_MISMATCH", "google: experiment base campaign or budget changed; read its context again");
|
|
1282
1591
|
const channels = { SEARCH_CUSTOM: ["SEARCH"], DISPLAY_CUSTOM: ["DISPLAY"], HOTEL_CUSTOM: ["HOTEL"], YOUTUBE_CUSTOM: ["VIDEO", "DEMAND_GEN"], PMAX_REPLACEMENT_SHOPPING: ["SHOPPING"] };
|
|
1283
|
-
if (base2.campaign.experimentType !== "BASE" || !["ENABLED", "PAUSED"].includes(String(base2.campaign.status)) || !channels[input2.type].includes(String(base2.campaign.advertisingChannelType)) || base2.budget.explicitlyShared === true || base2.budget.status !== "ENABLED") throw new
|
|
1592
|
+
if (base2.campaign.experimentType !== "BASE" || !["ENABLED", "PAUSED"].includes(String(base2.campaign.status)) || !channels[input2.type].includes(String(base2.campaign.advertisingChannelType)) || base2.budget.explicitlyShared === true || base2.budget.status !== "ENABLED") throw new AdportError8("INVALID_INPUT", "google: system-managed experiment needs an available base campaign of the matching channel with a non-shared enabled daily budget");
|
|
1284
1593
|
const temporary = `customers/${selected2}/experiments/-1`;
|
|
1285
1594
|
const metadata2 = { resourceName: temporary, name: input2.name, type: input2.type, status: "SETUP", suffix: input2.suffix, ...this.fields({ description: input2.description, start_date: input2.start_date, end_date: input2.end_date, goals: input2.goals, sync_enabled: input2.sync_enabled }), ...input2.video_experiment_subtype ? { videoExperiment: { videoExperimentSubtype: input2.video_experiment_subtype } } : {} };
|
|
1286
1595
|
const arms = this.armInput(temporary, input2.control_name, input2.control_traffic_split_percent, String(base2.campaign.resourceName), input2.treatments), operations = [{ experimentOperation: { create: metadata2 } }, ...arms.map((value) => ({ experimentArmOperation: { create: value } }))];
|
|
@@ -1289,30 +1598,30 @@ var GoogleExperimentService = class {
|
|
|
1289
1598
|
return { summary: `Create Google ${input2.type} experiment \u201C${input2.name}\u201D in SETUP`, changes: [`+ Experiment, one control arm and ${input2.treatments.length} treatment arm(s) in one atomic native transaction. Base ${String(base2.campaign.name)} (${input2.base_campaign_id}) stays ${String(base2.campaign.status)}.`, `+ Control traffic ${input2.control_traffic_split_percent}%; treatments ${input2.treatments.map((value) => `${value.name}: ${value.traffic_split_percent}%`).join(", ")}.`, "Native treatment arms generate in-design draft campaigns. SETUP is unscheduled and cannot serve experiment traffic. Scheduling is a separate guarded operation."], coercions: guard.forcePausedCreation ? ["Generated treatment campaign status is coerced to PAUSED after native creation, while the experiment remains SETUP (paused_creation)."] : [], budgetDeltas: bounds.map((value, index) => ({ target: `new treatment \u201C${input2.treatments[index].name}\u201D daily configuration upper bound`, fromMicros: 0, toMicros: value })), serverValidated: !guard.forcePausedCreation, notes: ["Native validateOnly checks the atomic experiment/arm creation. Generated draft IDs do not exist in a preview, so a required follow-up pause cannot be server-validated until apply; serverValidated=false reports that limit.", "Apply confirms the created identities, validates/applies any required pause, and verifies the draft status and configured daily budget bound. A partial follow-up failure returns resource IDs for reconciliation and never schedules or retries the experiment.", "Configured draft budget bounds are conservative policy inputs; native experiment traffic/budget sharing is not a promise of independent additional spend. Dates use the customer timezone."], resultDetails: () => details, execute: async (validateOnly) => {
|
|
1290
1599
|
const result2 = await this.client.googleAdsMutate(selected2, operations, { validateOnly, responseContentType: "MUTABLE_RESOURCE" });
|
|
1291
1600
|
if (validateOnly) return [];
|
|
1292
|
-
const response = result2.mutateOperationResponses, experiment =
|
|
1293
|
-
const created = response?.slice(1).map((value) =>
|
|
1294
|
-
if (!response || response.length !== operations.length || typeof resource !== "string" || !new RegExp(`^customers/${selected2}/experiments/[1-9]\\d*$`).test(resource) || !created || created.some((value) => typeof value !== "string" || !new RegExp(`^customers/${selected2}/experimentArms/${resource.split("/").at(-1)}~[1-9]\\d*$`).test(value)) || new Set(created).size !== created.length) throw new
|
|
1601
|
+
const response = result2.mutateOperationResponses, experiment = object4(response?.[0]?.experimentResult), resource = experiment.resourceName;
|
|
1602
|
+
const created = response?.slice(1).map((value) => object4(value.experimentArmResult).resourceName);
|
|
1603
|
+
if (!response || response.length !== operations.length || typeof resource !== "string" || !new RegExp(`^customers/${selected2}/experiments/[1-9]\\d*$`).test(resource) || !created || created.some((value) => typeof value !== "string" || !new RegExp(`^customers/${selected2}/experimentArms/${resource.split("/").at(-1)}~[1-9]\\d*$`).test(value)) || new Set(created).size !== created.length) throw new AdportError8("PROVIDER_ERROR", "google: atomic experiment creation receipt was not confirmed; find this experiment before another create", { resource_ids: [resource, ...created ?? []].filter((value) => typeof value === "string") });
|
|
1295
1604
|
const experimentId = resource.split("/").at(-1), ids2 = created;
|
|
1296
1605
|
try {
|
|
1297
1606
|
const current = await this.context({ account_id: selected2, experiment_id: experimentId });
|
|
1298
1607
|
if (current.experiment.name !== input2.name || current.experiment.type !== input2.type || current.experiment.status !== "SETUP" || ids2.some((value, index) => {
|
|
1299
1608
|
const arm = current.arms.find((arm2) => arm2.resourceName === value), wanted = arms[index];
|
|
1300
1609
|
return !arm || arm.name !== wanted.name || arm.control !== wanted.control || arm.trafficSplit !== wanted.trafficSplit;
|
|
1301
|
-
})) throw new
|
|
1610
|
+
})) throw new AdportError8("PROVIDER_ERROR", "google: experiment creation readback differs from the approved setup");
|
|
1302
1611
|
const drafts = await this.pauseDrafts(selected2, experimentId, ids2, base2, bounds, guard.forcePausedCreation);
|
|
1303
1612
|
details = { status: "SETUP", experiment_id: experimentId, arm_ids: ids2, draft_campaign_ids: drafts, paused_by_policy: guard.forcePausedCreation, scheduled: false, next_tool: "google_experiment_context" };
|
|
1304
1613
|
return [resource, ...ids2, ...drafts];
|
|
1305
1614
|
} catch (error) {
|
|
1306
|
-
throw new
|
|
1615
|
+
throw new AdportError8("PROVIDER_ERROR", `${error instanceof Error ? error.message : "google: setup follow-up was not confirmed"}. Creation was acknowledged but not retried; inspect this unscheduled experiment and its drafts.`, { resource_ids: [resource, ...ids2] });
|
|
1307
1616
|
}
|
|
1308
1617
|
} };
|
|
1309
1618
|
}
|
|
1310
1619
|
patchedArms(selected2, experimentId, current, patches) {
|
|
1311
|
-
if (new Set(patches.map((value) => value.arm_id)).size !== patches.length) throw new
|
|
1620
|
+
if (new Set(patches.map((value) => value.arm_id)).size !== patches.length) throw new AdportError8("INVALID_INPUT", "google: duplicate arm IDs");
|
|
1312
1621
|
const operations = [], after = current.map((value) => ({ ...value }));
|
|
1313
1622
|
for (const patch of patches) {
|
|
1314
1623
|
const resource = `customers/${selected2}/experimentArms/${experimentId}~${patch.arm_id}`, arm = after.find((value) => value.resourceName === resource);
|
|
1315
|
-
if (!arm) throw new
|
|
1624
|
+
if (!arm) throw new AdportError8("INVALID_INPUT", "google: arm does not belong to this experiment");
|
|
1316
1625
|
const values = { ...patch.name !== void 0 ? { name: patch.name } : {}, ...patch.traffic_split_percent !== void 0 ? { trafficSplit: String(patch.traffic_split_percent) } : {} };
|
|
1317
1626
|
if (!Object.keys(values).length) continue;
|
|
1318
1627
|
Object.assign(arm, values);
|
|
@@ -1321,33 +1630,33 @@ var GoogleExperimentService = class {
|
|
|
1321
1630
|
return { operations, after };
|
|
1322
1631
|
}
|
|
1323
1632
|
validArms(arms) {
|
|
1324
|
-
if (arms.length && (arms.filter((value) => value.control).length !== 1 || arms.reduce((sum, value) => sum + Number(value.trafficSplit), 0) !== 100 || new Set(arms.map((value) => value.name)).size !== arms.length)) throw new
|
|
1633
|
+
if (arms.length && (arms.filter((value) => value.control).length !== 1 || arms.reduce((sum, value) => sum + Number(value.trafficSplit), 0) !== 100 || new Set(arms.map((value) => value.name)).size !== arms.length)) throw new AdportError8("INVALID_INPUT", "google: final arm set must have one control, unique names and traffic totaling 100");
|
|
1325
1634
|
}
|
|
1326
1635
|
async changeArms(selected2, op, guard) {
|
|
1327
1636
|
const input2 = op.tool === "google_add_experiment_arms" ? addArms.parse(op.payload) : op.tool === "google_remove_experiment_arms" ? removeArms.parse(op.payload) : patchArms.parse(op.payload), context = await this.checked(selected2, input2), experiment = context.experiment, arms = context.arms;
|
|
1328
|
-
if (experiment.status !== "SETUP" || !systemType.safeParse(experiment.type).success) throw new
|
|
1637
|
+
if (experiment.status !== "SETUP" || !systemType.safeParse(experiment.type).success) throw new AdportError8("INVALID_INPUT", "google: arm setup tools require an unscheduled system-managed SETUP experiment");
|
|
1329
1638
|
const patches = "existing_arms" in input2 ? input2.existing_arms : "remaining_arms" in input2 ? input2.remaining_arms : input2.arms;
|
|
1330
1639
|
const patched = this.patchedArms(selected2, input2.experiment_id, arms, patches);
|
|
1331
1640
|
let operations = patched.operations, bounds = [], newArms = [], base2;
|
|
1332
1641
|
if ("treatments" in input2) {
|
|
1333
1642
|
const controls = arms.filter((value) => value.control), names = controls.flatMap((value) => list(value.campaigns));
|
|
1334
|
-
if (controls.length !== 1 || names.length !== 1) throw new
|
|
1643
|
+
if (controls.length !== 1 || names.length !== 1) throw new AdportError8("INVALID_INPUT", "google: treatment creation requires one verified control campaign");
|
|
1335
1644
|
base2 = context.campaigns.find((value) => value.campaign.resourceName === names[0]);
|
|
1336
|
-
if (!base2 || base2.campaign.experimentType !== "BASE" || base2.budget.explicitlyShared === true) throw new
|
|
1337
|
-
if (experiment.type !== "PMAX_REPLACEMENT_SHOPPING" && input2.treatments.some((value) => value.performance_max)) throw new
|
|
1645
|
+
if (!base2 || base2.campaign.experimentType !== "BASE" || base2.budget.explicitlyShared === true) throw new AdportError8("INVALID_INPUT", "google: base campaign or non-shared budget was not available");
|
|
1646
|
+
if (experiment.type !== "PMAX_REPLACEMENT_SHOPPING" && input2.treatments.some((value) => value.performance_max)) throw new AdportError8("INVALID_INPUT", "google: Performance Max settings do not match this experiment type");
|
|
1338
1647
|
newArms = this.armInput(String(experiment.resourceName), "", 0, "", input2.treatments).slice(1);
|
|
1339
1648
|
bounds = input2.treatments.map((value) => value.performance_max?.budget_amount_micros ?? base2.budget_micros);
|
|
1340
1649
|
this.validArms([...patched.after, ...newArms]);
|
|
1341
1650
|
operations = [...operations, ...newArms.map((value) => ({ create: value }))];
|
|
1342
1651
|
} else if ("arm_ids" in input2) {
|
|
1343
|
-
if (new Set(input2.arm_ids).size !== input2.arm_ids.length) throw new
|
|
1652
|
+
if (new Set(input2.arm_ids).size !== input2.arm_ids.length) throw new AdportError8("INVALID_INPUT", "google: duplicate removed arm IDs");
|
|
1344
1653
|
const removed = input2.arm_ids.map((value) => `customers/${selected2}/experimentArms/${input2.experiment_id}~${value}`);
|
|
1345
|
-
if (removed.some((value) => !arms.some((arm) => arm.resourceName === value)) || patches.some((value) => input2.arm_ids.includes(value.arm_id))) throw new
|
|
1654
|
+
if (removed.some((value) => !arms.some((arm) => arm.resourceName === value)) || patches.some((value) => input2.arm_ids.includes(value.arm_id))) throw new AdportError8("INVALID_INPUT", "google: removed arms must belong to this experiment and cannot also be updated");
|
|
1346
1655
|
this.validArms(patched.after.filter((value) => !removed.includes(String(value.resourceName))));
|
|
1347
1656
|
operations = [...operations, ...removed.map((resource) => ({ remove: resource }))];
|
|
1348
1657
|
} else {
|
|
1349
1658
|
this.validArms(patched.after);
|
|
1350
|
-
if (!operations.length) throw new
|
|
1659
|
+
if (!operations.length) throw new AdportError8("INVALID_INPUT", "google: supply arm names or traffic shares to update");
|
|
1351
1660
|
}
|
|
1352
1661
|
const plan = this.mutation(selected2, "experimentArms", operations, `${op.tool === "google_add_experiment_arms" ? "Add" : op.tool === "google_remove_experiment_arms" ? "Remove" : "Update"} Google experiment arms`, operations.map((value) => `~ ${JSON.stringify(value)}`));
|
|
1353
1662
|
if (!newArms.length) return plan;
|
|
@@ -1361,31 +1670,31 @@ var GoogleExperimentService = class {
|
|
|
1361
1670
|
details = { status: "SETUP", experiment_id: input2.experiment_id, arm_ids: created, draft_campaign_ids: drafts, paused_by_policy: guard.forcePausedCreation, scheduled: false, next_tool: "google_experiment_context" };
|
|
1362
1671
|
return [...ids2, ...drafts];
|
|
1363
1672
|
} catch (error) {
|
|
1364
|
-
throw new
|
|
1673
|
+
throw new AdportError8("PROVIDER_ERROR", `${error instanceof Error ? error.message : "google: arm follow-up was not confirmed"}. The native arm request was acknowledged; inspect SETUP before retrying.`, { resource_ids: [String(experiment.resourceName), ...ids2] });
|
|
1365
1674
|
}
|
|
1366
1675
|
} };
|
|
1367
1676
|
}
|
|
1368
1677
|
async asyncErrors(input2) {
|
|
1369
1678
|
const context = await this.context(input2), result2 = await this.client.experimentAsyncErrors(input2.account_id, input2.experiment_id, input2.page_size, input2.page_token);
|
|
1370
|
-
if (result2.errors !== void 0 && !Array.isArray(result2.errors) || result2.nextPageToken !== void 0 && (typeof result2.nextPageToken !== "string" || !result2.nextPageToken || result2.nextPageToken === input2.page_token)) throw new
|
|
1679
|
+
if (result2.errors !== void 0 && !Array.isArray(result2.errors) || result2.nextPageToken !== void 0 && (typeof result2.nextPageToken !== "string" || !result2.nextPageToken || result2.nextPageToken === input2.page_token)) throw new AdportError8("PROVIDER_ERROR", "google: invalid experiment async error page or nonadvancing cursor");
|
|
1371
1680
|
return { experiment_id: input2.experiment_id, status: context.experiment.status, errors: list(result2.errors).map(statusError), truncated: Boolean(result2.nextPageToken), ...typeof result2.nextPageToken === "string" ? { next_page_token: result2.nextPageToken } : {} };
|
|
1372
1681
|
}
|
|
1373
1682
|
async operation(input2) {
|
|
1374
1683
|
const context = await this.context(input2), experiment = context.experiment, current = experiment.longRunningOperation;
|
|
1375
1684
|
if (typeof current !== "string" || !current) return { experiment_id: input2.experiment_id, experiment_status: experiment.status, state: "NO_OPERATION_REPORTED", note: "The experiment has no current long-running operation. This is not proof of successful scheduling or promotion." };
|
|
1376
|
-
const result2 = await this.client.experimentOperation(input2.account_id, current), metadata2 =
|
|
1377
|
-
if (result2.name !== current || metadata2.experiment !== void 0 && metadata2.experiment !== experiment.resourceName || result2.done !== void 0 && typeof result2.done !== "boolean" || result2.done !== true && (result2.error !== void 0 || result2.response !== void 0) || result2.error !== void 0 && result2.response !== void 0) throw new
|
|
1685
|
+
const result2 = await this.client.experimentOperation(input2.account_id, current), metadata2 = object4(result2.metadata);
|
|
1686
|
+
if (result2.name !== current || metadata2.experiment !== void 0 && metadata2.experiment !== experiment.resourceName || result2.done !== void 0 && typeof result2.done !== "boolean" || result2.done !== true && (result2.error !== void 0 || result2.response !== void 0) || result2.error !== void 0 && result2.response !== void 0) throw new AdportError8("PROVIDER_ERROR", "google: experiment operation identity or completion result mismatch");
|
|
1378
1687
|
const done = result2.done === true, error = result2.error !== void 0 ? statusError(result2.error) : void 0;
|
|
1379
1688
|
return { experiment_id: input2.experiment_id, operation_name: current, experiment_status: experiment.status, state: !done ? "PROCESSING" : error ? "FAILED" : result2.response !== void 0 ? "SUCCEEDED" : "UNKNOWN", done, ...error ? { error } : {}, note: "Inspect native asynchronous experiment errors even after a completed operation. Operation completion alone does not guarantee campaign serving or experiment performance." };
|
|
1380
1689
|
}
|
|
1381
1690
|
};
|
|
1382
1691
|
function googleExperimentTools(provider) {
|
|
1383
|
-
const ref =
|
|
1692
|
+
const ref = z7.object(experimentRef).strict();
|
|
1384
1693
|
return [
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1694
|
+
defineTool7({ name: "google_experiments", namespace: "google", description: "List account-owned experiment configuration, lifecycle and latest operation. Continue next_cursor as after_experiment_id. No campaigns are created or scheduled.", input: z7.object({ account_id: z7.string(), limit: z7.number().int().positive().max(100).default(25), after_experiment_id: id7.optional(), include_removed: z7.boolean().default(false) }), annotations: { readOnly: true }, pagination: { cursorInput: "after_experiment_id" }, handler: (input2) => provider.experiments.list(input2) }),
|
|
1695
|
+
defineTool7({ name: "google_experiment_context", namespace: "google", description: "Read experiment/arms and their scoped base/draft/trial campaigns, daily budgets, currency/timezone and snapshot hashes. Supply base_campaign_id before create, experiment_id before edits/actions, and campaign_budget_id for graduation. Hashes cover returned configuration, not every underlying ad/keyword/target.", input: z7.object({ account_id: z7.string(), experiment_id: id7.optional(), base_campaign_id: id7.optional(), campaign_budget_id: id7.optional() }), annotations: { readOnly: true }, handler: (input2) => provider.experiments.context(input2) }),
|
|
1696
|
+
defineTool7({ name: "google_experiment_async_errors", namespace: "google", description: "Read the selected experiment\u2019s native scheduling/promotion errors. Returns enum/field diagnostics without sensitive native value echoes; continue next_page_token with identical selection.", input: z7.object({ account_id: z7.string(), experiment_id: id7, page_size: z7.number().int().positive().max(1e3).default(100), page_token: z7.string().min(1).max(16384).optional() }), annotations: { readOnly: true }, pagination: { cursorInput: "page_token" }, handler: (input2) => provider.experiments.asyncErrors(input2) }),
|
|
1697
|
+
defineTool7({ name: "google_experiment_operation", namespace: "google", description: "Read only the current account-scoped operation named by this verified experiment. Distinguishes PROCESSING, SUCCEEDED, FAILED and UNKNOWN; no scheduling, cancellation or retry.", input: z7.object({ account_id: z7.string(), experiment_id: id7 }), annotations: { readOnly: true }, handler: (input2) => provider.experiments.operation(input2) }),
|
|
1389
1698
|
...[
|
|
1390
1699
|
["google_create_experiment", "Create an unscheduled system-managed experiment with control/treatment arms in one native atomic request. Native draft copies are verified and paused by policy before success; no base pause, scheduling or serving. Requires expected_base_hash. Budget bounds use micros. Deferred draft pausing is reported as not fully server-validated.", create2],
|
|
1391
1700
|
["google_update_experiment", "Edit supplied experiment name/description/dates/goals through exact masks and expected_experiment_hash. Type and sync choice stay immutable; lifecycle transitions use their named actions.", update2],
|
|
@@ -1397,50 +1706,50 @@ function googleExperimentTools(provider) {
|
|
|
1397
1706
|
["google_end_experiment", "Immediately end the verified experiment through native EndExperiment, with validateOnly preview. Treatment campaigns stop serving but are retained; no campaign is promoted or graduated.", ref],
|
|
1398
1707
|
["google_promote_experiment", "Apply the current treatment configuration to its base through native promotion. Explicit serving confirmation and expected_experiment_hash required. Preview includes conservative daily budget ceilings; async submission is separate from completion.", action],
|
|
1399
1708
|
["google_graduate_experiment", "Graduate one verified treatment campaign to an independent campaign using an owned, unused non-shared daily budget. Requires current experiment/budget hashes and explicit serving confirmation; reports the budget delta in micros.", graduate]
|
|
1400
|
-
].map(([tool, description, payload]) =>
|
|
1709
|
+
].map(([tool, description, payload]) => guardedWriteTool7({ name: tool, namespace: "google", provider: "google", kind: kinds[tool], description, payload, ...tool === "google_create_experiment" ? { destructive: false } : {} }))
|
|
1401
1710
|
];
|
|
1402
1711
|
}
|
|
1403
1712
|
|
|
1404
1713
|
// src/pmax.ts
|
|
1405
|
-
import { createHash as
|
|
1406
|
-
import { AdportError as
|
|
1407
|
-
import { z as
|
|
1714
|
+
import { createHash as createHash6 } from "crypto";
|
|
1715
|
+
import { AdportError as AdportError9, creativeStatusAction, creativesOutput as creativesOutput2, defineTool as defineTool8, guardedWriteTool as guardedWriteTool8 } from "@adport/core";
|
|
1716
|
+
import { z as z8 } from "zod";
|
|
1408
1717
|
var row = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
1409
1718
|
var array = (value) => Array.isArray(value) ? value : [];
|
|
1410
|
-
var
|
|
1411
|
-
var
|
|
1412
|
-
var name4 =
|
|
1413
|
-
var url2 =
|
|
1719
|
+
var id8 = z8.string().regex(/^[1-9]\d*$/);
|
|
1720
|
+
var hash6 = z8.string().regex(/^[a-f0-9]{64}$/);
|
|
1721
|
+
var name4 = z8.string().trim().min(1).max(128);
|
|
1722
|
+
var url2 = z8.string().url().refine((value) => {
|
|
1414
1723
|
const u = new URL(value);
|
|
1415
1724
|
return ["https:", "http:"].includes(u.protocol) && !u.username && !u.password;
|
|
1416
1725
|
});
|
|
1417
|
-
var fieldType =
|
|
1418
|
-
var textType =
|
|
1419
|
-
var asset =
|
|
1420
|
-
var assetKey =
|
|
1421
|
-
var level =
|
|
1422
|
-
var dimension =
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1726
|
+
var fieldType = z8.enum(["HEADLINE", "LONG_HEADLINE", "DESCRIPTION", "BUSINESS_NAME", "MARKETING_IMAGE", "SQUARE_MARKETING_IMAGE", "PORTRAIT_MARKETING_IMAGE", "LOGO", "LANDSCAPE_LOGO", "YOUTUBE_VIDEO"]);
|
|
1727
|
+
var textType = z8.enum(["HEADLINE", "LONG_HEADLINE", "DESCRIPTION", "BUSINESS_NAME"]);
|
|
1728
|
+
var asset = z8.union([z8.object({ field_type: fieldType, asset_id: id8 }).strict(), z8.object({ field_type: textType, text: z8.string().min(1).max(2048) }).strict()]);
|
|
1729
|
+
var assetKey = z8.object({ field_type: fieldType, asset_id: id8 }).strict();
|
|
1730
|
+
var level = z8.enum(["LEVEL1", "LEVEL2", "LEVEL3", "LEVEL4", "LEVEL5"]);
|
|
1731
|
+
var dimension = z8.discriminatedUnion("dimension", [
|
|
1732
|
+
z8.object({ dimension: z8.literal("product_brand"), value: z8.string().max(1e3).optional() }).strict(),
|
|
1733
|
+
z8.object({ dimension: z8.literal("product_item_id"), value: z8.string().max(1e3).optional() }).strict(),
|
|
1734
|
+
z8.object({ dimension: z8.literal("product_category"), category_id: id8.optional(), level }).strict(),
|
|
1735
|
+
z8.object({ dimension: z8.literal("product_type"), value: z8.string().max(1e3).optional(), level }).strict(),
|
|
1736
|
+
z8.object({ dimension: z8.literal("product_custom_attribute"), value: z8.string().max(1e3).optional(), index: z8.enum(["INDEX0", "INDEX1", "INDEX2", "INDEX3", "INDEX4"]) }).strict(),
|
|
1737
|
+
z8.object({ dimension: z8.literal("product_channel"), channel: z8.enum(["ONLINE", "LOCAL"]).optional() }).strict(),
|
|
1738
|
+
z8.object({ dimension: z8.literal("product_condition"), condition: z8.enum(["NEW", "USED", "REFURBISHED"]).optional() }).strict()
|
|
1430
1739
|
]);
|
|
1431
|
-
var filterNode =
|
|
1432
|
-
var signal =
|
|
1433
|
-
var groupSettings = { name: name4.optional(), final_urls:
|
|
1434
|
-
var groupCreate =
|
|
1435
|
-
var campaignCreate =
|
|
1436
|
-
var groupRef = { asset_group_id:
|
|
1437
|
-
var groupUpdate =
|
|
1438
|
-
var copyUpdate =
|
|
1439
|
-
var assetsUpdate =
|
|
1440
|
-
var brandUpdate =
|
|
1441
|
-
var signalsAdd =
|
|
1442
|
-
var signalsRemove =
|
|
1443
|
-
var listingReplace =
|
|
1740
|
+
var filterNode = z8.object({ key: z8.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,39}$/), parent_key: z8.string().optional(), type: z8.enum(["SUBDIVISION", "UNIT_INCLUDED", "UNIT_EXCLUDED"]), case_value: dimension.optional() }).strict();
|
|
1741
|
+
var signal = z8.discriminatedUnion("type", [z8.object({ type: z8.literal("AUDIENCE"), audience_id: id8 }).strict(), z8.object({ type: z8.literal("SEARCH_THEME"), text: z8.string().trim().min(1).max(2e3) }).strict()]);
|
|
1742
|
+
var groupSettings = { name: name4.optional(), final_urls: z8.array(url2).max(10).optional(), final_mobile_urls: z8.array(url2).max(10).optional(), path1: z8.string().max(15).optional(), path2: z8.string().max(15).optional(), tracking_url_template: z8.string().max(2048).optional(), final_url_suffix: z8.string().max(2048).optional(), url_custom_parameters: z8.array(z8.object({ key: z8.string().min(1).max(16), value: z8.string().max(200) }).strict()).max(8).optional() };
|
|
1743
|
+
var groupCreate = z8.object({ ...groupSettings, name: name4, status: z8.enum(["PAUSED", "ENABLED"]).default("PAUSED"), assets: z8.array(asset).max(120), signals: z8.array(signal).max(100).default([]), listing_filters: z8.array(filterNode).min(1).max(1e3).optional() }).strict();
|
|
1744
|
+
var campaignCreate = z8.object({ name: name4, daily_budget_micros: z8.number().int().positive().safe(), status: z8.enum(["PAUSED", "ENABLED"]).default("PAUSED"), bidding: z8.discriminatedUnion("strategy", [z8.object({ strategy: z8.literal("MAXIMIZE_CONVERSIONS"), target_cpa_micros: z8.number().int().positive().safe().optional() }).strict(), z8.object({ strategy: z8.literal("MAXIMIZE_CONVERSION_VALUE"), target_roas: z8.number().finite().positive().optional() }).strict()]), merchant: z8.object({ merchant_id: id8, feed_label: z8.string().min(1).max(100).optional() }).strict().optional(), brand_guidelines: z8.object({ main_color: z8.string().regex(/^#[a-fA-F0-9]{6}$/), accent_color: z8.string().regex(/^#[a-fA-F0-9]{6}$/), predefined_font_family: z8.enum(["Open Sans", "Roboto", "Montserrat", "Poppins", "Lato", "Oswald", "Playfair Display", "Roboto Slab"]).optional() }).strict().optional(), allow_final_url_expansion: z8.boolean().default(false), location_ids: z8.array(id8).max(100).default([]), language_ids: z8.array(id8).max(100).default([]), contains_eu_political_advertising: z8.enum(["CONTAINS_EU_POLITICAL_ADVERTISING", "DOES_NOT_CONTAIN_EU_POLITICAL_ADVERTISING"]).default("DOES_NOT_CONTAIN_EU_POLITICAL_ADVERTISING"), asset_group: groupCreate }).strict();
|
|
1745
|
+
var groupRef = { asset_group_id: id8, expected_group_hash: hash6 };
|
|
1746
|
+
var groupUpdate = z8.object({ ...groupRef, ...groupSettings }).strict().refine((value) => Object.entries(value).some(([key2, item]) => !["asset_group_id", "expected_group_hash"].includes(key2) && item !== void 0), "Supply asset-group metadata to update");
|
|
1747
|
+
var copyUpdate = z8.object({ asset_group_id: id8, expected_assets_hash: hash6, headlines: z8.array(z8.string().min(1).max(2048)).min(3).max(15).optional(), long_headlines: z8.array(z8.string().min(1).max(2048)).min(1).max(5).optional(), descriptions: z8.array(z8.string().min(1).max(2048)).min(2).max(5).optional() }).strict().refine((value) => value.headlines || value.long_headlines || value.descriptions, "Supply text copy to replace");
|
|
1748
|
+
var assetsUpdate = z8.object({ asset_group_id: id8, expected_assets_hash: hash6, add: z8.array(asset).max(120).default([]), remove: z8.array(assetKey).max(120).default([]) }).strict().refine((value) => value.add.length + value.remove.length > 0, "Supply asset links to add or remove");
|
|
1749
|
+
var brandUpdate = z8.object({ campaign_id: id8, expected_campaign_hash: hash6, add: z8.array(asset).max(30).default([]), remove: z8.array(assetKey).max(30).default([]) }).strict().refine((value) => value.add.length + value.remove.length > 0 && [...value.add, ...value.remove].every((value2) => ["BUSINESS_NAME", "LOGO", "LANDSCAPE_LOGO"].includes(value2.field_type)), "Supply campaign brand placements to add or remove");
|
|
1750
|
+
var signalsAdd = z8.object({ asset_group_id: id8, expected_signals_hash: hash6, signals: z8.array(signal).min(1).max(100) }).strict();
|
|
1751
|
+
var signalsRemove = z8.object({ asset_group_id: id8, expected_signals_hash: hash6, signal_ids: z8.array(id8).min(1).max(100) }).strict();
|
|
1752
|
+
var listingReplace = z8.object({ asset_group_id: id8, expected_listing_hash: hash6, listing_filters: z8.array(filterNode).min(1).max(1e3) }).strict();
|
|
1444
1753
|
var campaignFields2 = "campaign.resource_name, campaign.id, campaign.name, campaign.status, campaign.advertising_channel_type, campaign.advertising_channel_sub_type, campaign.brand_guidelines_enabled, campaign.shopping_setting.merchant_id, campaign.shopping_setting.feed_label, campaign.asset_automation_settings, campaign.campaign_budget, campaign.bidding_strategy_type, campaign.maximize_conversions.target_cpa_micros, campaign.maximize_conversion_value.target_roas, campaign_budget.resource_name, campaign_budget.amount_micros, campaign_budget.explicitly_shared";
|
|
1445
1754
|
var groupFields = "asset_group.resource_name, asset_group.id, asset_group.campaign, asset_group.name, asset_group.status, asset_group.final_urls, asset_group.final_mobile_urls, asset_group.path1, asset_group.path2, asset_group.primary_status, asset_group.primary_status_reasons, asset_group.ad_strength, asset_group.tracking_url_template, asset_group.final_url_suffix, asset_group.url_custom_parameters";
|
|
1446
1755
|
var assetFields = "asset.resource_name, asset.id, asset.type, asset.name, asset.text_asset.text, asset.image_asset.full_size.url, asset.image_asset.full_size.width_pixels, asset.image_asset.full_size.height_pixels, asset.youtube_video_asset.youtube_video_id";
|
|
@@ -1452,7 +1761,7 @@ var fields3 = (value) => Object.fromEntries(Object.entries(value).filter(([, ite
|
|
|
1452
1761
|
function sorted(value) {
|
|
1453
1762
|
return Array.isArray(value) ? value.map(sorted) : value && typeof value === "object" ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key2, item]) => [key2, sorted(item)])) : value;
|
|
1454
1763
|
}
|
|
1455
|
-
var
|
|
1764
|
+
var digest5 = (value) => createHash6("sha256").update(JSON.stringify(sorted(value))).digest("hex");
|
|
1456
1765
|
var kinds2 = { google_create_performance_max_campaign: "create", google_create_asset_group: "create", google_update_asset_group: "update", google_set_asset_group_status: "update", google_remove_asset_group: "remove", google_update_asset_group_assets: "update", google_update_asset_group_copy: "update", google_update_performance_max_brand_assets: "update", google_add_asset_group_signals: "create", google_remove_asset_group_signals: "remove", google_replace_asset_group_listing_filters: "update" };
|
|
1457
1766
|
var GOOGLE_PMAX_WRITES = new Set(Object.keys(kinds2));
|
|
1458
1767
|
var brandTypes = /* @__PURE__ */ new Set(["BUSINESS_NAME", "LOGO", "LANDSCAPE_LOGO"]);
|
|
@@ -1462,67 +1771,67 @@ var GooglePerformanceMaxService = class {
|
|
|
1462
1771
|
}
|
|
1463
1772
|
client;
|
|
1464
1773
|
resource(account2, service, value) {
|
|
1465
|
-
return `customers/${account2}/${service}/${
|
|
1774
|
+
return `customers/${account2}/${service}/${id8.parse(value)}`;
|
|
1466
1775
|
}
|
|
1467
1776
|
async customer(account2) {
|
|
1468
1777
|
const rows = await this.client.search(account2, "SELECT customer.resource_name, customer.id, customer.currency_code, customer.time_zone FROM customer LIMIT 2", { maxRows: 2 }), value = row(rows[0]?.customer);
|
|
1469
|
-
if (rows.length !== 1 || value.id !== account2 || value.resourceName !== `customers/${account2}` || typeof value.currencyCode !== "string" || !/^[A-Z]{3}$/.test(value.currencyCode) || typeof value.timeZone !== "string") throw new
|
|
1778
|
+
if (rows.length !== 1 || value.id !== account2 || value.resourceName !== `customers/${account2}` || typeof value.currencyCode !== "string" || !/^[A-Z]{3}$/.test(value.currencyCode) || typeof value.timeZone !== "string") throw new AdportError9("PROVIDER_ERROR", "google: invalid Performance Max customer context");
|
|
1470
1779
|
return value;
|
|
1471
1780
|
}
|
|
1472
1781
|
group(value, account2) {
|
|
1473
1782
|
const group = row(value);
|
|
1474
|
-
if (!
|
|
1783
|
+
if (!id8.safeParse(group.id).success || group.resourceName !== this.resource(account2, "assetGroups", String(group.id)) || typeof group.campaign !== "string" || !new RegExp(`^customers/${account2}/campaigns/[1-9]\\d*$`).test(group.campaign) || typeof group.name !== "string" || !["PAUSED", "ENABLED", "REMOVED"].includes(String(group.status))) throw new AdportError9("PROVIDER_ERROR", "google: invalid asset-group identity or status");
|
|
1475
1784
|
return group;
|
|
1476
1785
|
}
|
|
1477
1786
|
async campaignContext(input2) {
|
|
1478
1787
|
const account2 = normalizeCustomerId(input2.account_id), customer = await this.customer(account2), resource = this.resource(account2, "campaigns", input2.campaign_id);
|
|
1479
1788
|
const rows = await this.client.search(account2, `SELECT ${campaignFields2} FROM campaign WHERE campaign.resource_name = '${resource}' LIMIT 2`, { maxRows: 2, includeDrafts: true }), campaign = row(rows[0]?.campaign), budget = row(rows[0]?.campaignBudget);
|
|
1480
|
-
if (rows.length !== 1 || campaign.resourceName !== resource || campaign.id !== input2.campaign_id || campaign.advertisingChannelType !== "PERFORMANCE_MAX" || campaign.status === "REMOVED" || campaign.campaignBudget !== budget.resourceName || !new RegExp(`^customers/${account2}/campaignBudgets/[1-9]\\d*$`).test(String(budget.resourceName))) throw new
|
|
1789
|
+
if (rows.length !== 1 || campaign.resourceName !== resource || campaign.id !== input2.campaign_id || campaign.advertisingChannelType !== "PERFORMANCE_MAX" || campaign.status === "REMOVED" || campaign.campaignBudget !== budget.resourceName || !new RegExp(`^customers/${account2}/campaignBudgets/[1-9]\\d*$`).test(String(budget.resourceName))) throw new AdportError9("INVALID_INPUT", "google: an available Performance Max campaign with an owned budget is required");
|
|
1481
1790
|
const brands = await this.client.search(account2, `SELECT campaign.id, campaign_asset.resource_name, campaign_asset.campaign, campaign_asset.asset, campaign_asset.field_type, campaign_asset.status, ${assetFields} FROM campaign_asset WHERE campaign_asset.campaign = '${resource}' AND campaign_asset.field_type IN ('BUSINESS_NAME','LOGO','LANDSCAPE_LOGO') AND campaign_asset.status != 'REMOVED' LIMIT 101`, { maxRows: 101, includeDrafts: true });
|
|
1482
|
-
if (brands.length > 100) throw new
|
|
1791
|
+
if (brands.length > 100) throw new AdportError9("PROVIDER_ERROR", "google: complete campaign brand context exceeds the read bound");
|
|
1483
1792
|
const brandAssets = brands.map((value) => {
|
|
1484
1793
|
const link = row(value.campaignAsset), asset2 = row(value.asset);
|
|
1485
1794
|
this.assetIdentity(asset2, account2);
|
|
1486
|
-
if (link.campaign !== resource || link.asset !== asset2.resourceName || !brandTypes.has(String(link.fieldType)) || link.resourceName !== `customers/${account2}/campaignAssets/${input2.campaign_id}~${asset2.id}~${link.fieldType}`) throw new
|
|
1795
|
+
if (link.campaign !== resource || link.asset !== asset2.resourceName || !brandTypes.has(String(link.fieldType)) || link.resourceName !== `customers/${account2}/campaignAssets/${input2.campaign_id}~${asset2.id}~${link.fieldType}`) throw new AdportError9("PROVIDER_ERROR", "google: campaign brand asset ownership mismatch");
|
|
1487
1796
|
return { link, asset: asset2 };
|
|
1488
1797
|
}).sort((a, b) => String(a.link.resourceName).localeCompare(String(b.link.resourceName)));
|
|
1489
|
-
return { account: customer, campaign, budget, brand_assets: brandAssets, campaign_snapshot_hash:
|
|
1798
|
+
return { account: customer, campaign, budget, brand_assets: brandAssets, campaign_snapshot_hash: digest5({ customer, campaign, budget, brandAssets }), note: "Hashes cover returned campaign/group configuration, not performance or every campaign criterion. Native validation remains authoritative; Google has no atomic compare-and-set. Existing media assets are reused without downloading their bytes." };
|
|
1490
1799
|
}
|
|
1491
1800
|
assetIdentity(asset2, account2) {
|
|
1492
|
-
if (!
|
|
1801
|
+
if (!id8.safeParse(asset2.id).success || asset2.resourceName !== this.resource(account2, "assets", String(asset2.id)) || typeof asset2.type !== "string") throw new AdportError9("PROVIDER_ERROR", "google: asset ownership or identity mismatch");
|
|
1493
1802
|
}
|
|
1494
1803
|
async list(input2) {
|
|
1495
|
-
const account2 = normalizeCustomerId(input2.account_id), campaign = this.resource(account2, "campaigns", input2.campaign_id), predicates = [`asset_group.campaign = '${campaign}'`, ...!input2.include_removed ? ["asset_group.status != 'REMOVED'"] : [], ...input2.after_asset_group_id ? [`asset_group.id > ${
|
|
1804
|
+
const account2 = normalizeCustomerId(input2.account_id), campaign = this.resource(account2, "campaigns", input2.campaign_id), predicates = [`asset_group.campaign = '${campaign}'`, ...!input2.include_removed ? ["asset_group.status != 'REMOVED'"] : [], ...input2.after_asset_group_id ? [`asset_group.id > ${id8.parse(input2.after_asset_group_id)}`] : []];
|
|
1496
1805
|
const rows = await this.client.search(account2, `SELECT ${groupFields} FROM asset_group WHERE ${predicates.join(" AND ")} ORDER BY asset_group.id ASC LIMIT ${input2.limit + 1}`, { maxRows: input2.limit + 1, includeDrafts: true }), groups = rows.map((value) => this.group(value.assetGroup, account2));
|
|
1497
|
-
if (groups.some((value, index) => value.campaign !== campaign || BigInt(String(value.id)) <= BigInt(index ? String(groups[index - 1].id) : input2.after_asset_group_id ?? "0"))) throw new
|
|
1806
|
+
if (groups.some((value, index) => value.campaign !== campaign || BigInt(String(value.id)) <= BigInt(index ? String(groups[index - 1].id) : input2.after_asset_group_id ?? "0"))) throw new AdportError9("PROVIDER_ERROR", "google: asset-group continuation or campaign scope mismatch");
|
|
1498
1807
|
return { asset_groups: groups.slice(0, input2.limit), truncated: groups.length > input2.limit, ...groups.length > input2.limit ? { next_cursor: String(groups[input2.limit - 1].id) } : {} };
|
|
1499
1808
|
}
|
|
1500
1809
|
async context(input2) {
|
|
1501
1810
|
const account2 = normalizeCustomerId(input2.account_id), resource = this.resource(account2, "assetGroups", input2.asset_group_id), rows = await this.client.search(account2, `SELECT ${groupFields} FROM asset_group WHERE asset_group.resource_name = '${resource}' LIMIT 2`, { maxRows: 2, includeDrafts: true });
|
|
1502
|
-
if (rows.length !== 1) throw new
|
|
1811
|
+
if (rows.length !== 1) throw new AdportError9("INVALID_INPUT", "google: asset group was not available in this account");
|
|
1503
1812
|
const group = this.group(rows[0]?.assetGroup, account2);
|
|
1504
|
-
if (group.resourceName !== resource) throw new
|
|
1813
|
+
if (group.resourceName !== resource) throw new AdportError9("PROVIDER_ERROR", "google: asset-group selection mismatch");
|
|
1505
1814
|
const campaign = await this.campaignContext({ account_id: account2, campaign_id: String(group.campaign).split("/").at(-1) });
|
|
1506
1815
|
const [links, signals, filters] = await Promise.all([
|
|
1507
1816
|
this.client.search(account2, `SELECT ${linkFields}, ${assetFields} FROM asset_group_asset WHERE asset_group_asset.asset_group = '${resource}' AND asset_group_asset.status != 'REMOVED' LIMIT 501`, { maxRows: 501, includeDrafts: true }),
|
|
1508
1817
|
this.client.search(account2, `SELECT ${signalFields} FROM asset_group_signal WHERE asset_group_signal.asset_group = '${resource}' LIMIT 1001`, { maxRows: 1001, includeDrafts: true }),
|
|
1509
1818
|
this.client.search(account2, `SELECT ${filterFields} FROM asset_group_listing_group_filter WHERE asset_group_listing_group_filter.asset_group = '${resource}' LIMIT 1001`, { maxRows: 1001, includeDrafts: true })
|
|
1510
1819
|
]);
|
|
1511
|
-
if (links.length > 500 || signals.length > 1e3 || filters.length > 1e3) throw new
|
|
1820
|
+
if (links.length > 500 || signals.length > 1e3 || filters.length > 1e3) throw new AdportError9("INVALID_INPUT", "google: complete asset-group context exceeds the read bound");
|
|
1512
1821
|
const assets = links.map((value) => {
|
|
1513
1822
|
const link = row(value.assetGroupAsset), asset2 = row(value.asset);
|
|
1514
1823
|
this.assetIdentity(asset2, account2);
|
|
1515
|
-
if (link.assetGroup !== resource || link.asset !== asset2.resourceName || link.resourceName !== `customers/${account2}/assetGroupAssets/${input2.asset_group_id}~${asset2.id}~${link.fieldType}` || !["ENABLED", "PAUSED"].includes(String(link.status))) throw new
|
|
1824
|
+
if (link.assetGroup !== resource || link.asset !== asset2.resourceName || link.resourceName !== `customers/${account2}/assetGroupAssets/${input2.asset_group_id}~${asset2.id}~${link.fieldType}` || !["ENABLED", "PAUSED"].includes(String(link.status))) throw new AdportError9("PROVIDER_ERROR", "google: asset-group link identity or status mismatch");
|
|
1516
1825
|
return { link, asset: asset2 };
|
|
1517
1826
|
}).sort((a, b) => String(a.link.resourceName).localeCompare(String(b.link.resourceName)));
|
|
1518
1827
|
const owned = (values, key2, service) => values.map((value) => {
|
|
1519
1828
|
const item = row(value[key2]);
|
|
1520
|
-
if (item.assetGroup !== resource || !new RegExp(`^customers/${account2}/${service}/${input2.asset_group_id}~[1-9]\\d*$`).test(String(item.resourceName))) throw new
|
|
1829
|
+
if (item.assetGroup !== resource || !new RegExp(`^customers/${account2}/${service}/${input2.asset_group_id}~[1-9]\\d*$`).test(String(item.resourceName))) throw new AdportError9("PROVIDER_ERROR", "google: signal/filter ownership mismatch");
|
|
1521
1830
|
return item;
|
|
1522
1831
|
}).sort((a, b) => String(a.resourceName).localeCompare(String(b.resourceName)));
|
|
1523
|
-
const nativeSignals = owned(signals, "assetGroupSignal", "assetGroupSignals"), listing = owned(filters, "assetGroupListingGroupFilter", "assetGroupListingGroupFilters"), groupHash =
|
|
1524
|
-
if (new Set(assets.map((value) => value.link.resourceName)).size !== assets.length || new Set(nativeSignals.map((value) => value.resourceName)).size !== nativeSignals.length || new Set(listing.map((value) => value.resourceName)).size !== listing.length) throw new
|
|
1525
|
-
return { ...campaign, asset_group: group, assets, signals: nativeSignals, listing_filters: listing, group_snapshot_hash: groupHash, assets_snapshot_hash:
|
|
1832
|
+
const nativeSignals = owned(signals, "assetGroupSignal", "assetGroupSignals"), listing = owned(filters, "assetGroupListingGroupFilter", "assetGroupListingGroupFilters"), groupHash = digest5({ parent: campaign.campaign_snapshot_hash, group });
|
|
1833
|
+
if (new Set(assets.map((value) => value.link.resourceName)).size !== assets.length || new Set(nativeSignals.map((value) => value.resourceName)).size !== nativeSignals.length || new Set(listing.map((value) => value.resourceName)).size !== listing.length) throw new AdportError9("PROVIDER_ERROR", "google: duplicate asset-group configuration rows");
|
|
1834
|
+
return { ...campaign, asset_group: group, assets, signals: nativeSignals, listing_filters: listing, group_snapshot_hash: groupHash, assets_snapshot_hash: digest5({ groupHash, assets }), signals_snapshot_hash: digest5({ groupHash, signals: nativeSignals }), listing_snapshot_hash: digest5({ groupHash, filters: listing }) };
|
|
1526
1835
|
}
|
|
1527
1836
|
async creatives(input2) {
|
|
1528
1837
|
const context = await this.context(input2), group = context.asset_group, account2 = normalizeCustomerId(input2.account_id);
|
|
@@ -1547,9 +1856,9 @@ var GooglePerformanceMaxService = class {
|
|
|
1547
1856
|
const resources = responses?.map((value) => Object.values(value).map((value2) => value2.resourceName));
|
|
1548
1857
|
const services = { assetOperation: "assets", campaignBudgetOperation: "campaignBudgets", campaignOperation: "campaigns", campaignAssetOperation: "campaignAssets", campaignCriterionOperation: "campaignCriteria", assetGroupOperation: "assetGroups", assetGroupAssetOperation: "assetGroupAssets", assetGroupSignalOperation: "assetGroupSignals", assetGroupListingGroupFilterOperation: "assetGroupListingGroupFilters" };
|
|
1549
1858
|
if (!resources || resources.length !== operations.length || resources.some((values, index) => {
|
|
1550
|
-
const [type, raw] = Object.entries(operations[index])[0], operation = row(raw),
|
|
1551
|
-
return values.length !== 1 || typeof values[0] !== "string" || !service || !new RegExp(`^customers/${account2}/${service}/[1-9]\\d*(?:~[1-9]\\d*)?(?:~[A-Z_]+)?$`).test(values[0]) ||
|
|
1552
|
-
})) throw new
|
|
1859
|
+
const [type, raw] = Object.entries(operations[index])[0], operation = row(raw), target5 = row(operation.update).resourceName ?? operation.remove, service = services[type];
|
|
1860
|
+
return values.length !== 1 || typeof values[0] !== "string" || !service || !new RegExp(`^customers/${account2}/${service}/[1-9]\\d*(?:~[1-9]\\d*)?(?:~[A-Z_]+)?$`).test(values[0]) || target5 !== void 0 && target5 !== values[0];
|
|
1861
|
+
})) throw new AdportError9("PROVIDER_ERROR", "google: Performance Max atomic acknowledgement was not confirmed; reconcile before another mutation", { resource_ids: resources?.flat().filter((value) => typeof value === "string") ?? [] });
|
|
1553
1862
|
return resources.flat();
|
|
1554
1863
|
} };
|
|
1555
1864
|
}
|
|
@@ -1560,10 +1869,10 @@ var GooglePerformanceMaxService = class {
|
|
|
1560
1869
|
for (const value of rows) {
|
|
1561
1870
|
const item = row(value.asset);
|
|
1562
1871
|
this.assetIdentity(item, account2);
|
|
1563
|
-
if (!ids2.includes(String(item.id)) || native.has(String(item.id))) throw new
|
|
1872
|
+
if (!ids2.includes(String(item.id)) || native.has(String(item.id))) throw new AdportError9("PROVIDER_ERROR", "google: asset selection returned unexpected or duplicate IDs");
|
|
1564
1873
|
native.set(String(item.id), item);
|
|
1565
1874
|
}
|
|
1566
|
-
if (native.size !== ids2.length) throw new
|
|
1875
|
+
if (native.size !== ids2.length) throw new AdportError9("INVALID_INPUT", "google: all supplied assets must be available in the selected account");
|
|
1567
1876
|
}
|
|
1568
1877
|
const operations = [], textResources = /* @__PURE__ */ new Map();
|
|
1569
1878
|
const assets = input2.map((value) => {
|
|
@@ -1579,51 +1888,51 @@ var GooglePerformanceMaxService = class {
|
|
|
1579
1888
|
item = { resourceName: resource, type: "TEXT", textAsset: { text: value.text } };
|
|
1580
1889
|
}
|
|
1581
1890
|
const expectedType = textType.safeParse(value.field_type).success ? "TEXT" : value.field_type === "YOUTUBE_VIDEO" ? "YOUTUBE_VIDEO" : "IMAGE";
|
|
1582
|
-
if (item.type !== expectedType) throw new
|
|
1891
|
+
if (item.type !== expectedType) throw new AdportError9("INVALID_INPUT", `google: ${value.field_type} requires ${expectedType}, not the selected asset type`);
|
|
1583
1892
|
return { link: { fieldType: value.field_type, asset: item.resourceName, status: "ENABLED" }, asset: item };
|
|
1584
1893
|
});
|
|
1585
|
-
if (new Set(assets.map((value) => `${value.link.fieldType}:${value.link.asset}`)).size !== assets.length) throw new
|
|
1894
|
+
if (new Set(assets.map((value) => `${value.link.fieldType}:${value.link.asset}`)).size !== assets.length) throw new AdportError9("INVALID_INPUT", "google: duplicate asset and placement");
|
|
1586
1895
|
return { assets, operations };
|
|
1587
1896
|
}
|
|
1588
1897
|
requirements(groupAssets, brands, brandGuidelines, retail, finalUrls) {
|
|
1589
1898
|
if (retail && groupAssets.every((value) => value.asset.type === "MEDIA_BUNDLE")) return;
|
|
1590
|
-
if (!array(finalUrls).length) throw new
|
|
1899
|
+
if (!array(finalUrls).length) throw new AdportError9("INVALID_INPUT", "google: custom asset groups need at least one final URL, including retail campaigns");
|
|
1591
1900
|
const count2 = (values, type) => values.filter((value) => value.link.fieldType === type).length;
|
|
1592
1901
|
for (const [type, min, max] of [["HEADLINE", 3, 15], ["LONG_HEADLINE", 1, 5], ["DESCRIPTION", 2, 5], ["MARKETING_IMAGE", 1, 20], ["SQUARE_MARKETING_IMAGE", 1, 20], ["PORTRAIT_MARKETING_IMAGE", 0, 20], ["YOUTUBE_VIDEO", 0, 5]]) {
|
|
1593
1902
|
const size = count2(groupAssets, type);
|
|
1594
|
-
if (size < min || size > max) throw new
|
|
1903
|
+
if (size < min || size > max) throw new AdportError9("INVALID_INPUT", `google: ${type} needs ${min}\u2013${max} linked assets in the final atomic set`);
|
|
1595
1904
|
}
|
|
1596
1905
|
const branding = brandGuidelines ? brands : groupAssets;
|
|
1597
|
-
if (count2(branding, "BUSINESS_NAME") !== 1 || count2(branding, "LOGO") < 1 || count2(branding, "LOGO") > 5) throw new
|
|
1598
|
-
if (brandGuidelines && groupAssets.some((value) => brandTypes.has(String(value.link.fieldType)))) throw new
|
|
1906
|
+
if (count2(branding, "BUSINESS_NAME") !== 1 || count2(branding, "LOGO") < 1 || count2(branding, "LOGO") > 5) throw new AdportError9("INVALID_INPUT", `google: exactly one BUSINESS_NAME and one to five LOGO assets are required at ${brandGuidelines ? "campaign" : "asset-group"} level`);
|
|
1907
|
+
if (brandGuidelines && groupAssets.some((value) => brandTypes.has(String(value.link.fieldType)))) throw new AdportError9("INVALID_INPUT", "google: brand-guidelines campaigns require brand assets at campaign level");
|
|
1599
1908
|
}
|
|
1600
1909
|
groupWire(value) {
|
|
1601
1910
|
const result2 = fields3(value), path1 = result2.path1, path2 = result2.path2;
|
|
1602
|
-
if (path2 && !path1) throw new
|
|
1911
|
+
if (path2 && !path1) throw new AdportError9("INVALID_INPUT", "google: path2 requires path1");
|
|
1603
1912
|
if (Array.isArray(value.url_custom_parameters)) result2.urlCustomParameters = value.url_custom_parameters;
|
|
1604
1913
|
return result2;
|
|
1605
1914
|
}
|
|
1606
1915
|
async signalOperations(account2, group, values) {
|
|
1607
|
-
if (new Set(values.map((value) => JSON.stringify(value))).size !== values.length) throw new
|
|
1916
|
+
if (new Set(values.map((value) => JSON.stringify(value))).size !== values.length) throw new AdportError9("INVALID_INPUT", "google: duplicate signals");
|
|
1608
1917
|
for (const audienceId of new Set(values.flatMap((value) => value.type === "AUDIENCE" ? [value.audience_id] : []))) {
|
|
1609
1918
|
const resource = this.resource(account2, "audiences", audienceId), rows = await this.client.search(account2, `SELECT audience.resource_name, audience.status FROM audience WHERE audience.resource_name = '${resource}' LIMIT 2`, { maxRows: 2 });
|
|
1610
|
-
if (rows.length !== 1 || row(rows[0]?.audience).resourceName !== resource || row(rows[0]?.audience).status !== "ENABLED") throw new
|
|
1919
|
+
if (rows.length !== 1 || row(rows[0]?.audience).resourceName !== resource || row(rows[0]?.audience).status !== "ENABLED") throw new AdportError9("INVALID_INPUT", "google: signal audience must be an available account-owned audience");
|
|
1611
1920
|
}
|
|
1612
1921
|
return values.map((value) => ({ assetGroupSignalOperation: { create: { assetGroup: group, ...value.type === "AUDIENCE" ? { audience: { audience: this.resource(account2, "audiences", value.audience_id) } } : { searchTheme: { text: value.text } } } } }));
|
|
1613
1922
|
}
|
|
1614
1923
|
listingOperations(account2, group, values) {
|
|
1615
1924
|
const byKey = new Map(values.map((value) => [value.key, value]));
|
|
1616
|
-
if (byKey.size !== values.length || values.filter((value) => !value.parent_key).length !== 1) throw new
|
|
1925
|
+
if (byKey.size !== values.length || values.filter((value) => !value.parent_key).length !== 1) throw new AdportError9("INVALID_INPUT", "google: shopping listing tree requires unique keys and one root");
|
|
1617
1926
|
const ordered = [], visiting = /* @__PURE__ */ new Set(), visited = /* @__PURE__ */ new Set();
|
|
1618
1927
|
const visit = (node) => {
|
|
1619
|
-
if (visiting.has(node.key)) throw new
|
|
1928
|
+
if (visiting.has(node.key)) throw new AdportError9("INVALID_INPUT", "google: cycle in listing filters");
|
|
1620
1929
|
if (visited.has(node.key)) return;
|
|
1621
1930
|
visiting.add(node.key);
|
|
1622
1931
|
if (node.parent_key) {
|
|
1623
1932
|
const parent = byKey.get(node.parent_key);
|
|
1624
|
-
if (!parent || parent.type !== "SUBDIVISION" || !node.case_value) throw new
|
|
1933
|
+
if (!parent || parent.type !== "SUBDIVISION" || !node.case_value) throw new AdportError9("INVALID_INPUT", "google: child listing filter requires a subdivision parent and case value");
|
|
1625
1934
|
visit(parent);
|
|
1626
|
-
} else if (node.case_value) throw new
|
|
1935
|
+
} else if (node.case_value) throw new AdportError9("INVALID_INPUT", "google: shopping root has no case value");
|
|
1627
1936
|
visiting.delete(node.key);
|
|
1628
1937
|
visited.add(node.key);
|
|
1629
1938
|
ordered.push(node);
|
|
@@ -1631,7 +1940,7 @@ var GooglePerformanceMaxService = class {
|
|
|
1631
1940
|
for (const value of values) visit(value);
|
|
1632
1941
|
for (const value of values) {
|
|
1633
1942
|
const children = values.filter((child) => child.parent_key === value.key);
|
|
1634
|
-
if (value.type !== "SUBDIVISION" && children.length || value.type === "SUBDIVISION" && children.length < 2) throw new
|
|
1943
|
+
if (value.type !== "SUBDIVISION" && children.length || value.type === "SUBDIVISION" && children.length < 2) throw new AdportError9("INVALID_INPUT", "google: subdivision needs explicit and other children; units cannot have children");
|
|
1635
1944
|
if (!children.length) continue;
|
|
1636
1945
|
const dimensions = children.map((child) => {
|
|
1637
1946
|
const c = child.case_value;
|
|
@@ -1642,7 +1951,7 @@ var GooglePerformanceMaxService = class {
|
|
|
1642
1951
|
const c = child.case_value;
|
|
1643
1952
|
return !Object.keys(c).some((key2) => ["value", "category_id", "channel", "condition"].includes(key2));
|
|
1644
1953
|
});
|
|
1645
|
-
if (new Set(dimensions).size !== 1 || new Set(cases).size !== cases.length || other.length !== 1) throw new
|
|
1954
|
+
if (new Set(dimensions).size !== 1 || new Set(cases).size !== cases.length || other.length !== 1) throw new AdportError9("INVALID_INPUT", "google: siblings require one dimension/level, distinct cases and exactly one other case");
|
|
1646
1955
|
}
|
|
1647
1956
|
const groupId = group.split("/").at(-1), names = new Map(ordered.map((value, index) => [value.key, `customers/${account2}/assetGroupListingGroupFilters/${groupId}~-${2e4 + index}`]));
|
|
1648
1957
|
return ordered.map((value) => {
|
|
@@ -1654,9 +1963,9 @@ var GooglePerformanceMaxService = class {
|
|
|
1654
1963
|
const { assets: _assets, signals: _signals, listing_filters: _filters, status: _status, ...settings2 } = input2;
|
|
1655
1964
|
return [{ assetGroupOperation: { create: { resourceName: group, campaign, ...this.groupWire(settings2), status } } }, ...assets.map((value) => ({ assetGroupAssetOperation: { create: { assetGroup: group, asset: value.link.asset, fieldType: value.link.fieldType, status: "ENABLED" } } }))];
|
|
1656
1965
|
}
|
|
1657
|
-
createdStatus(value, guard,
|
|
1966
|
+
createdStatus(value, guard, target5, coercions) {
|
|
1658
1967
|
if (guard.forcePausedCreation && value !== "PAUSED") {
|
|
1659
|
-
coercions.push(`${
|
|
1968
|
+
coercions.push(`${target5} status coerced to PAUSED by policy (paused_creation)`);
|
|
1660
1969
|
return "PAUSED";
|
|
1661
1970
|
}
|
|
1662
1971
|
return value;
|
|
@@ -1672,7 +1981,7 @@ var GooglePerformanceMaxService = class {
|
|
|
1672
1981
|
const current = await this.context({ account_id: account2, asset_group_id: group.split("/").at(-1) });
|
|
1673
1982
|
if (current.asset_group.resourceName !== group || current.asset_group.campaign !== campaign || current.asset_group.name !== groupName || current.asset_group.status !== groupStatus || current.campaign.name !== expectedName || campaignStatus && current.campaign.status !== campaignStatus) throw new Error("created group/parent state differs from the approved plan");
|
|
1674
1983
|
} catch {
|
|
1675
|
-
throw new
|
|
1984
|
+
throw new AdportError9("PROVIDER_ERROR", "google: creation was acknowledged but readback could not confirm the approved campaign/group. Reconcile these IDs before another create; nothing was automatically retried.", { resource_ids: ids2 });
|
|
1676
1985
|
}
|
|
1677
1986
|
return ids2;
|
|
1678
1987
|
} };
|
|
@@ -1680,7 +1989,7 @@ var GooglePerformanceMaxService = class {
|
|
|
1680
1989
|
async createCampaign(account2, input2, guard) {
|
|
1681
1990
|
const customer = await this.customer(account2), resolved = await this.resolveAssets(account2, input2.asset_group.assets), brandAssets = resolved.assets.filter((value) => brandTypes.has(String(value.link.fieldType))), groupAssets = resolved.assets.filter((value) => !brandTypes.has(String(value.link.fieldType))), retail = Boolean(input2.merchant);
|
|
1682
1991
|
this.requirements(groupAssets, brandAssets, true, retail, input2.asset_group.final_urls);
|
|
1683
|
-
if (Boolean(input2.asset_group.listing_filters) !== retail) throw new
|
|
1992
|
+
if (Boolean(input2.asset_group.listing_filters) !== retail) throw new AdportError9("INVALID_INPUT", "google: retail campaigns require a SHOPPING product listing tree; non-retail campaigns must omit it");
|
|
1684
1993
|
const budget = `customers/${account2}/campaignBudgets/-10001`, campaign = `customers/${account2}/campaigns/-10002`, group = `customers/${account2}/assetGroups/-10003`, coercions = [];
|
|
1685
1994
|
const status = this.createdStatus(input2.status, guard, "Campaign", coercions), groupStatus = this.createdStatus(input2.asset_group.status, guard, "Asset group", coercions);
|
|
1686
1995
|
const bidding = input2.bidding.strategy === "MAXIMIZE_CONVERSIONS" ? { maximizeConversions: { ...input2.bidding.target_cpa_micros !== void 0 ? { targetCpaMicros: String(input2.bidding.target_cpa_micros) } : {} } } : { maximizeConversionValue: { ...input2.bidding.target_roas !== void 0 ? { targetRoas: input2.bidding.target_roas } : {} } };
|
|
@@ -1699,53 +2008,53 @@ var GooglePerformanceMaxService = class {
|
|
|
1699
2008
|
return this.verifyCreation(plan, account2, input2.name, input2.asset_group.name, groupStatus, void 0, status);
|
|
1700
2009
|
}
|
|
1701
2010
|
async createGroup(account2, payload, guard) {
|
|
1702
|
-
const input2 = groupCreate.safeExtend({ campaign_id:
|
|
1703
|
-
if (context.campaign_snapshot_hash !== input2.expected_campaign_hash) throw new
|
|
2011
|
+
const input2 = groupCreate.safeExtend({ campaign_id: id8, expected_campaign_hash: hash6 }).parse(payload), context = await this.campaignContext({ account_id: account2, campaign_id: input2.campaign_id });
|
|
2012
|
+
if (context.campaign_snapshot_hash !== input2.expected_campaign_hash) throw new AdportError9("PENDING_MISMATCH", "google: campaign, budget or brand assets changed; read Performance Max context again");
|
|
1704
2013
|
const { campaign_id: _campaign, expected_campaign_hash: _hash, ...settings2 } = input2, resolved = await this.resolveAssets(account2, input2.assets), brands = context.campaign.brandGuidelinesEnabled === true, retail = Boolean(row(context.campaign.shoppingSetting).merchantId);
|
|
1705
|
-
if (brands && resolved.assets.some((value) => brandTypes.has(String(value.link.fieldType)))) throw new
|
|
2014
|
+
if (brands && resolved.assets.some((value) => brandTypes.has(String(value.link.fieldType)))) throw new AdportError9("INVALID_INPUT", "google: use google_update_performance_max_brand_assets for campaign-level brand changes before creating a group");
|
|
1706
2015
|
this.requirements(resolved.assets, context.brand_assets, brands, retail, input2.final_urls);
|
|
1707
|
-
if (Boolean(input2.listing_filters) !== retail) throw new
|
|
2016
|
+
if (Boolean(input2.listing_filters) !== retail) throw new AdportError9("INVALID_INPUT", "google: only retail groups require a SHOPPING product tree");
|
|
1708
2017
|
const group = `customers/${account2}/assetGroups/-10003`, coercions = [], status = this.createdStatus(input2.status, guard, "Asset group", coercions);
|
|
1709
2018
|
const operations = [...resolved.operations, ...this.groupOperations(account2, group, String(context.campaign.resourceName), settings2, resolved.assets, status), ...await this.signalOperations(account2, group, input2.signals), ...input2.listing_filters ? this.listingOperations(account2, group, input2.listing_filters) : []];
|
|
1710
2019
|
const plan = this.atomic(account2, operations, `Create Performance Max asset group \u201C${input2.name}\u201D (${status})`, [`+ Group in campaign ${input2.campaign_id}, with ${resolved.assets.length} atomic creative links, ${input2.signals.length} signals and ${input2.listing_filters?.length ?? 0} product filters.`, "Campaign status, budget and campaign-level brand links are preserved. Child links are enabled within the new group; a paused group cannot serve."], coercions);
|
|
1711
2020
|
return this.verifyCreation(plan, account2, String(context.campaign.name), input2.name, status, String(context.campaign.resourceName));
|
|
1712
2021
|
}
|
|
1713
2022
|
async updateAssets(account2, input2, context) {
|
|
1714
|
-
if (context.assets_snapshot_hash !== input2.expected_assets_hash) throw new
|
|
2023
|
+
if (context.assets_snapshot_hash !== input2.expected_assets_hash) throw new AdportError9("PENDING_MISMATCH", "google: group, parent, assets or brand configuration changed; read context again");
|
|
1715
2024
|
const remove2 = input2.remove.map((value) => `customers/${account2}/assetGroupAssets/${input2.asset_group_id}~${value.asset_id}~${value.field_type}`);
|
|
1716
|
-
if (new Set(remove2).size !== remove2.length || remove2.some((value) => !context.assets.some((item) => item.link.resourceName === value))) throw new
|
|
2025
|
+
if (new Set(remove2).size !== remove2.length || remove2.some((value) => !context.assets.some((item) => item.link.resourceName === value))) throw new AdportError9("INVALID_INPUT", "google: every removed asset association must belong to this group exactly once");
|
|
1717
2026
|
const resolved = await this.resolveAssets(account2, input2.add), remain = context.assets.filter((value) => !remove2.includes(String(value.link.resourceName))), after = [...remain, ...resolved.assets];
|
|
1718
|
-
if (new Set(after.map((value) => `${value.link.asset}:${value.link.fieldType}`)).size !== after.length) throw new
|
|
2027
|
+
if (new Set(after.map((value) => `${value.link.asset}:${value.link.fieldType}`)).size !== after.length) throw new AdportError9("INVALID_INPUT", "google: final asset set contains duplicate links");
|
|
1719
2028
|
this.requirements(after, context.brand_assets, context.campaign.brandGuidelinesEnabled === true, Boolean(row(context.campaign.shoppingSetting).merchantId), context.asset_group.finalUrls);
|
|
1720
2029
|
const operations = [...resolved.operations, ...remove2.map((resource) => ({ assetGroupAssetOperation: { remove: resource } })), ...resolved.assets.map((value) => ({ assetGroupAssetOperation: { create: { assetGroup: context.asset_group.resourceName, asset: value.link.asset, fieldType: value.link.fieldType, status: "ENABLED" } } }))];
|
|
1721
2030
|
return this.atomic(account2, operations, `Update creative assets in group \u201C${String(context.asset_group.name)}\u201D`, [`- ${remove2.length} exact associations; + ${resolved.assets.length} associations in one atomic set. Shared source assets are retained.`, `Group stays ${String(context.asset_group.status)}; parent campaign stays ${String(context.campaign.status)}. New links are enabled as part of this explicit creative edit and can affect serving combinations.`, ...resolved.assets.map((value) => `+ ${String(value.link.fieldType)} ${String(row(value.asset.textAsset).text ?? value.link.asset)}`)]);
|
|
1722
2031
|
}
|
|
1723
2032
|
async plan(op, guard) {
|
|
1724
|
-
if (op.provider !== "google" || !GOOGLE_PMAX_WRITES.has(op.tool) || op.kind !== kinds2[op.tool]) throw new
|
|
2033
|
+
if (op.provider !== "google" || !GOOGLE_PMAX_WRITES.has(op.tool) || op.kind !== kinds2[op.tool]) throw new AdportError9("INVALID_INPUT", "google: invalid Performance Max operation kind");
|
|
1725
2034
|
const account2 = normalizeCustomerId(op.accountId);
|
|
1726
2035
|
if (op.tool === "google_create_performance_max_campaign") return this.createCampaign(account2, campaignCreate.parse(op.payload), guard);
|
|
1727
2036
|
if (op.tool === "google_create_asset_group") return this.createGroup(account2, op.payload, guard);
|
|
1728
2037
|
if (op.tool === "google_update_performance_max_brand_assets") return this.updateBrandAssets(account2, op.payload);
|
|
1729
|
-
const payload = row(op.payload), groupId =
|
|
1730
|
-
if (group.status === "REMOVED") throw new
|
|
2038
|
+
const payload = row(op.payload), groupId = id8.parse(payload.asset_group_id), context = await this.context({ account_id: account2, asset_group_id: groupId }), group = context.asset_group, resource = String(group.resourceName);
|
|
2039
|
+
if (group.status === "REMOVED") throw new AdportError9("INVALID_INPUT", "google: removed asset group cannot be changed");
|
|
1731
2040
|
if (op.tool === "google_update_asset_group_assets") return this.updateAssets(account2, assetsUpdate.parse(payload), context);
|
|
1732
2041
|
if (op.tool === "google_update_asset_group_copy") {
|
|
1733
2042
|
const input3 = copyUpdate.parse(payload), changes = { asset_group_id: groupId, expected_assets_hash: input3.expected_assets_hash, add: [], remove: [] };
|
|
1734
2043
|
for (const [key2, type] of [["headlines", "HEADLINE"], ["long_headlines", "LONG_HEADLINE"], ["descriptions", "DESCRIPTION"]]) {
|
|
1735
2044
|
const wanted = input3[key2];
|
|
1736
2045
|
if (!wanted) continue;
|
|
1737
|
-
if (new Set(wanted).size !== wanted.length) throw new
|
|
2046
|
+
if (new Set(wanted).size !== wanted.length) throw new AdportError9("INVALID_INPUT", "google: duplicate copy within a placement");
|
|
1738
2047
|
const current = context.assets.filter((value) => value.link.fieldType === type), existing = current.map((value) => row(value.asset.textAsset).text);
|
|
1739
2048
|
changes.add.push(...wanted.filter((value) => !existing.includes(value)).map((text2) => ({ field_type: type, text: text2 })));
|
|
1740
2049
|
changes.remove.push(...current.filter((value) => !wanted.includes(String(row(value.asset.textAsset).text))).map((value) => ({ asset_id: String(value.asset.id), field_type: type })));
|
|
1741
2050
|
}
|
|
1742
|
-
if (!changes.add.length && !changes.remove.length) throw new
|
|
2051
|
+
if (!changes.add.length && !changes.remove.length) throw new AdportError9("INVALID_INPUT", "google: supplied copy already matches this group");
|
|
1743
2052
|
return this.updateAssets(account2, changes, context);
|
|
1744
2053
|
}
|
|
1745
2054
|
if (op.tool === "google_add_asset_group_signals" || op.tool === "google_remove_asset_group_signals") return this.changeSignals(account2, op, context);
|
|
1746
2055
|
if (op.tool === "google_replace_asset_group_listing_filters") return this.replaceFilters(account2, payload, context);
|
|
1747
|
-
const input2 = op.tool === "google_update_asset_group" ? groupUpdate.parse(payload) : op.tool === "google_set_asset_group_status" ?
|
|
1748
|
-
if (context.group_snapshot_hash !== input2.expected_group_hash) throw new
|
|
2056
|
+
const input2 = op.tool === "google_update_asset_group" ? groupUpdate.parse(payload) : op.tool === "google_set_asset_group_status" ? z8.object({ ...groupRef, status: z8.enum(["ENABLED", "PAUSED"]) }).strict().parse(payload) : z8.object(groupRef).strict().parse(payload);
|
|
2057
|
+
if (context.group_snapshot_hash !== input2.expected_group_hash) throw new AdportError9("PENDING_MISMATCH", "google: asset-group or parent configuration changed; read context again");
|
|
1749
2058
|
if (op.tool === "google_remove_asset_group") return this.atomic(account2, [{ assetGroupOperation: { remove: resource } }], `Remove asset group \u201C${String(group.name)}\u201D`, [`- ${resource}; its associations, signals and listing filters may also be removed. Shared assets, parent campaign and budget are retained.`]);
|
|
1750
2059
|
const { asset_group_id: _id, expected_group_hash: _hash, ...settings2 } = input2, merged = { ...group, ...fields3(settings2) };
|
|
1751
2060
|
const pausing = op.tool === "google_set_asset_group_status" && "status" in input2 && input2.status === "PAUSED";
|
|
@@ -1757,41 +2066,41 @@ var GooglePerformanceMaxService = class {
|
|
|
1757
2066
|
}
|
|
1758
2067
|
async updateBrandAssets(account2, payload) {
|
|
1759
2068
|
const input2 = brandUpdate.parse(payload), context = await this.campaignContext({ account_id: account2, campaign_id: input2.campaign_id });
|
|
1760
|
-
if (context.campaign_snapshot_hash !== input2.expected_campaign_hash) throw new
|
|
1761
|
-
if (context.campaign.brandGuidelinesEnabled !== true) throw new
|
|
2069
|
+
if (context.campaign_snapshot_hash !== input2.expected_campaign_hash) throw new AdportError9("PENDING_MISMATCH", "google: campaign, budget or brand assets changed; read context again");
|
|
2070
|
+
if (context.campaign.brandGuidelinesEnabled !== true) throw new AdportError9("INVALID_INPUT", "google: campaign brand edits require native brand guidelines enabled; disabled campaigns keep branding on each group");
|
|
1762
2071
|
const remove2 = input2.remove.map((value) => `customers/${account2}/campaignAssets/${input2.campaign_id}~${value.asset_id}~${value.field_type}`);
|
|
1763
|
-
if (new Set(remove2).size !== remove2.length || remove2.some((value) => !context.brand_assets.some((item) => item.link.resourceName === value))) throw new
|
|
2072
|
+
if (new Set(remove2).size !== remove2.length || remove2.some((value) => !context.brand_assets.some((item) => item.link.resourceName === value))) throw new AdportError9("INVALID_INPUT", "google: every removed brand link must belong to this campaign exactly once");
|
|
1764
2073
|
const resolved = await this.resolveAssets(account2, input2.add), after = [...context.brand_assets.filter((value) => !remove2.includes(String(value.link.resourceName))), ...resolved.assets];
|
|
1765
|
-
if (new Set(after.map((value) => `${value.link.fieldType}:${value.link.asset}`)).size !== after.length || after.filter((value) => value.link.fieldType === "BUSINESS_NAME").length !== 1 || after.filter((value) => value.link.fieldType === "LOGO").length < 1 || after.filter((value) => value.link.fieldType === "LOGO").length > 5) throw new
|
|
2074
|
+
if (new Set(after.map((value) => `${value.link.fieldType}:${value.link.asset}`)).size !== after.length || after.filter((value) => value.link.fieldType === "BUSINESS_NAME").length !== 1 || after.filter((value) => value.link.fieldType === "LOGO").length < 1 || after.filter((value) => value.link.fieldType === "LOGO").length > 5) throw new AdportError9("INVALID_INPUT", "google: final campaign branding requires distinct links, one business name and one to five logos");
|
|
1766
2075
|
return this.atomic(account2, [...resolved.operations, ...remove2.map((resource) => ({ campaignAssetOperation: { remove: resource } })), ...resolved.assets.map((value) => ({ campaignAssetOperation: { create: { campaign: context.campaign.resourceName, asset: value.link.asset, fieldType: value.link.fieldType, status: "ENABLED" } } }))], `Update shared Performance Max branding for campaign \u201C${String(context.campaign.name)}\u201D`, [`- ${remove2.length} exact brand links; + ${resolved.assets.length} links atomically. Source assets are retained.`, "Brand changes affect every asset group in this campaign, including serving creative combinations. Campaign/group statuses and budget are preserved."]);
|
|
1767
2076
|
}
|
|
1768
2077
|
async changeSignals(account2, op, context) {
|
|
1769
2078
|
const input2 = op.tool === "google_add_asset_group_signals" ? signalsAdd.parse(op.payload) : signalsRemove.parse(op.payload);
|
|
1770
|
-
if (context.signals_snapshot_hash !== input2.expected_signals_hash) throw new
|
|
2079
|
+
if (context.signals_snapshot_hash !== input2.expected_signals_hash) throw new AdportError9("PENDING_MISMATCH", "google: group, parent or signals changed; read context again");
|
|
1771
2080
|
let operations;
|
|
1772
2081
|
if ("signals" in input2) {
|
|
1773
2082
|
const key2 = (value) => value.audience ? `audience:${String(row(value.audience).audience)}` : `theme:${String(row(value.searchTheme).text)}`;
|
|
1774
2083
|
operations = await this.signalOperations(account2, String(context.asset_group.resourceName), input2.signals);
|
|
1775
|
-
if (operations.some((value) => context.signals.some((existing) => key2(existing) === key2(row(row(value.assetGroupSignalOperation).create))))) throw new
|
|
2084
|
+
if (operations.some((value) => context.signals.some((existing) => key2(existing) === key2(row(row(value.assetGroupSignalOperation).create))))) throw new AdportError9("INVALID_INPUT", "google: a supplied audience or search theme is already linked");
|
|
1776
2085
|
} else {
|
|
1777
2086
|
const names = input2.signal_ids.map((value) => `customers/${account2}/assetGroupSignals/${input2.asset_group_id}~${value}`);
|
|
1778
|
-
if (new Set(names).size !== names.length || names.some((value) => !context.signals.some((existing) => existing.resourceName === value))) throw new
|
|
2087
|
+
if (new Set(names).size !== names.length || names.some((value) => !context.signals.some((existing) => existing.resourceName === value))) throw new AdportError9("INVALID_INPUT", "google: every removed signal must belong to this group exactly once");
|
|
1779
2088
|
operations = names.map((resource) => ({ assetGroupSignalOperation: { remove: resource } }));
|
|
1780
2089
|
}
|
|
1781
2090
|
return this.atomic(account2, operations, `${"signals" in input2 ? "Add" : "Remove"} ${operations.length} Performance Max signals`, ["Signals guide optimization and can change delivery, but audiences/search themes do not restrict targeting to only these users or queries.", "This workflow does not upload customer records, create an audience or change campaign/group status or budget."]);
|
|
1782
2091
|
}
|
|
1783
2092
|
replaceFilters(account2, payload, context) {
|
|
1784
2093
|
const input2 = listingReplace.parse(payload);
|
|
1785
|
-
if (context.listing_snapshot_hash !== input2.expected_listing_hash) throw new
|
|
1786
|
-
if (!row(context.campaign.shoppingSetting).merchantId || context.listing_filters.some((value) => value.listingSource !== "SHOPPING")) throw new
|
|
2094
|
+
if (context.listing_snapshot_hash !== input2.expected_listing_hash) throw new AdportError9("PENDING_MISMATCH", "google: group, parent or listing filters changed; read context again");
|
|
2095
|
+
if (!row(context.campaign.shoppingSetting).merchantId || context.listing_filters.some((value) => value.listingSource !== "SHOPPING")) throw new AdportError9("INVALID_INPUT", "google: this workflow replaces only SHOPPING product filters in an existing retail campaign; webpage/retail-bundle filters are separate native workflows");
|
|
1787
2096
|
const byName = new Map(context.listing_filters.map((value) => [String(value.resourceName), value]));
|
|
1788
2097
|
const depth = (value, seen = /* @__PURE__ */ new Set()) => {
|
|
1789
2098
|
const resource = String(value.resourceName);
|
|
1790
|
-
if (seen.has(resource)) throw new
|
|
2099
|
+
if (seen.has(resource)) throw new AdportError9("PROVIDER_ERROR", "google: cycle in current native listing tree");
|
|
1791
2100
|
seen.add(resource);
|
|
1792
2101
|
if (!value.parentListingGroupFilter) return 0;
|
|
1793
2102
|
const parent = byName.get(String(value.parentListingGroupFilter));
|
|
1794
|
-
if (!parent) throw new
|
|
2103
|
+
if (!parent) throw new AdportError9("PROVIDER_ERROR", "google: current native listing tree has an unavailable parent");
|
|
1795
2104
|
return 1 + depth(parent, seen);
|
|
1796
2105
|
};
|
|
1797
2106
|
const remove2 = [...context.listing_filters].sort((a, b) => depth(b) - depth(a)).map((value) => ({ assetGroupListingGroupFilterOperation: { remove: value.resourceName } }));
|
|
@@ -1799,66 +2108,66 @@ var GooglePerformanceMaxService = class {
|
|
|
1799
2108
|
}
|
|
1800
2109
|
};
|
|
1801
2110
|
function googlePerformanceMaxTools(provider) {
|
|
1802
|
-
const ref =
|
|
2111
|
+
const ref = z8.object({ account_id: z8.string(), asset_group_id: id8 });
|
|
1803
2112
|
return [
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
2113
|
+
defineTool8({ name: "google_performance_max_context", namespace: "google", description: "Read an owned Performance Max campaign, budget, brand-guidelines state, automation settings and campaign brand links. Supply campaign_snapshot_hash to guarded group/brand changes. Does not enable a campaign or access Merchant Center records.", input: z8.object({ account_id: z8.string(), campaign_id: id8 }), annotations: { readOnly: true }, handler: (input2) => provider.performanceMax.campaignContext(input2) }),
|
|
2114
|
+
defineTool8({ name: "google_asset_groups", namespace: "google", description: "List owned Performance Max asset groups in one campaign with status, actual landing URLs and native eligibility/ad-strength reasons. Continue next_cursor as after_asset_group_id; use context/creatives for one group.", input: z8.object({ account_id: z8.string(), campaign_id: id8, limit: z8.number().int().positive().max(100).default(25), after_asset_group_id: id8.optional(), include_removed: z8.boolean().default(false) }), annotations: { readOnly: true }, pagination: { cursorInput: "after_asset_group_id" }, handler: (input2) => provider.performanceMax.list(input2) }),
|
|
2115
|
+
defineTool8({ name: "google_asset_group_context", namespace: "google", description: "Read one owned group, complete scoped creative/brand associations, signals and listing filters with separate group/assets/signals/listing snapshot hashes. Includes draft groups. Fails if a complete context exceeds its bounded read.", input: ref, annotations: { readOnly: true }, handler: (input2) => provider.performanceMax.context(input2) }),
|
|
2116
|
+
defineTool8({ name: "google_asset_group_creatives", namespace: "google", description: "View actual Performance Max group copy, owned image previews and landing URLs, with guarded status/copy-edit actions. The group generates creative combinations; it is not one fixed rendered ad. Previews omit unsupported media origins.", input: ref, output: creativesOutput2, presentation: "creatives", annotations: { readOnly: true }, handler: (input2) => provider.performanceMax.creatives(input2) }),
|
|
1808
2117
|
...[
|
|
1809
2118
|
["google_create_performance_max_campaign", "Create a Performance Max campaign in an authorized Google Ads account with a dedicated budget and one asset group. Checks existing assets in that account and sends one atomic request after approval. The preview uses Google Ads validateOnly. Workspace policy may require paused creation; final URL expansion defaults off.", campaignCreate],
|
|
1810
|
-
["google_create_asset_group", "Create a complete owned-campaign Performance Max group with atomic creative links, optional audience/search-theme signals and a retail product tree. Requires expected_campaign_hash. New group obeys paused policy; enabled child links cannot serve inside a paused group. Brand-guidelines campaigns need existing campaign-level branding.", groupCreate.safeExtend({ campaign_id:
|
|
2119
|
+
["google_create_asset_group", "Create a complete owned-campaign Performance Max group with atomic creative links, optional audience/search-theme signals and a retail product tree. Requires expected_campaign_hash. New group obeys paused policy; enabled child links cannot serve inside a paused group. Brand-guidelines campaigns need existing campaign-level branding.", groupCreate.safeExtend({ campaign_id: id8, expected_campaign_hash: hash6 })],
|
|
1811
2120
|
["google_update_asset_group", "Edit only supplied group name, URLs, display paths and tracking fields with exact masks and expected_group_hash. Omission preserves values. Existing statuses, creative sources, campaign budget and parent are retained.", groupUpdate],
|
|
1812
|
-
["google_set_asset_group_status", "Enable or pause a verified owned asset group with expected_group_hash. Enabling can serve its generated combinations if the parent campaign is enabled. Does not change campaign status or budget.",
|
|
1813
|
-
["google_remove_asset_group", "Remove a verified asset group and its native child associations/signals/filter tree, using expected_group_hash. Parent campaign, budget and shared source assets are retained. Native constraints still apply.",
|
|
2121
|
+
["google_set_asset_group_status", "Enable or pause a verified owned asset group with expected_group_hash. Enabling can serve its generated combinations if the parent campaign is enabled. Does not change campaign status or budget.", z8.object({ ...groupRef, status: z8.enum(["ENABLED", "PAUSED"]) }).strict()],
|
|
2122
|
+
["google_remove_asset_group", "Remove a verified asset group and its native child associations/signals/filter tree, using expected_group_hash. Parent campaign, budget and shared source assets are retained. Native constraints still apply.", z8.object(groupRef).strict()],
|
|
1814
2123
|
["google_update_asset_group_assets", "Atomically add supplied creative placements/text assets and remove exact owned associations, using expected_assets_hash. Preserves source assets and parent/group status. New links are enabled as an explicit creative edit; serving combinations can change. Final set must meet native minimums; retail can unlink all custom assets to return to feed-only.", assetsUpdate],
|
|
1815
2124
|
["google_update_asset_group_copy", "Replace supplied headline/long-headline/description sets atomically with expected_assets_hash. Retains matching existing text and all unsupplied placements. New immutable text assets precede consecutive association changes; shared old sources are retained. Can affect serving combinations.", copyUpdate],
|
|
1816
2125
|
["google_update_performance_max_brand_assets", "Atomically change campaign-level BUSINESS_NAME/LOGO/LANDSCAPE_LOGO links for brand-guidelines campaigns with expected_campaign_hash. Affects every group in the campaign, including serving creative combinations. Preserves sources/status/budget and native minimum branding.", brandUpdate],
|
|
1817
2126
|
["google_add_asset_group_signals", "Add account-owned audience references or search themes with expected_signals_hash. These guide optimization rather than restrict targeting. No records are uploaded, audiences created or serving statuses changed.", signalsAdd],
|
|
1818
2127
|
["google_remove_asset_group_signals", "Remove exact owned signal IDs from the selected group with expected_signals_hash. Does not delete audiences or upload customer records. Native minimum-signal rules remain authoritative.", signalsRemove],
|
|
1819
2128
|
["google_replace_asset_group_listing_filters", "Replace a retail SHOPPING product tree atomically with expected_listing_hash. Typed brand/category/product type/custom-label/item/channel/condition nodes require unique keys, one root and complete subdivisions. Old children are removed first; new parents created first. Can alter eligible products in serving groups; feeds/status/budgets are retained.", listingReplace]
|
|
1820
|
-
].map(([tool, description, payload]) =>
|
|
2129
|
+
].map(([tool, description, payload]) => guardedWriteTool8({ name: tool, namespace: "google", provider: "google", kind: kinds2[tool], description, payload }))
|
|
1821
2130
|
];
|
|
1822
2131
|
}
|
|
1823
2132
|
|
|
1824
2133
|
// src/targeting.ts
|
|
1825
|
-
import { createHash as
|
|
1826
|
-
import { AdportError as
|
|
1827
|
-
import { z as
|
|
2134
|
+
import { createHash as createHash7 } from "crypto";
|
|
2135
|
+
import { AdportError as AdportError10, defineTool as defineTool9, guardedWriteTool as guardedWriteTool9 } from "@adport/core";
|
|
2136
|
+
import { z as z10 } from "zod";
|
|
1828
2137
|
|
|
1829
2138
|
// src/targeting-schemas.ts
|
|
1830
|
-
import { z as
|
|
1831
|
-
var targetingId =
|
|
1832
|
-
var
|
|
1833
|
-
var ids =
|
|
1834
|
-
var delta =
|
|
1835
|
-
var locationChanges =
|
|
1836
|
-
var targetingDevice =
|
|
1837
|
-
var bidMultiplier =
|
|
1838
|
-
var scheduleDay =
|
|
1839
|
-
var minute =
|
|
1840
|
-
var adSchedule =
|
|
1841
|
-
var schedules =
|
|
2139
|
+
import { z as z9 } from "zod";
|
|
2140
|
+
var targetingId = z9.string().regex(/^[1-9]\d*$/).max(30);
|
|
2141
|
+
var unique2 = (values) => new Set(values).size === values.length;
|
|
2142
|
+
var ids = z9.array(targetingId).max(1e3).refine(unique2, "Use unique IDs");
|
|
2143
|
+
var delta = z9.object({ add_ids: ids.default([]), remove_ids: ids.default([]) }).strict().refine((value) => value.add_ids.length + value.remove_ids.length > 0, "Supply additions or removals").refine((value) => !value.add_ids.some((id11) => value.remove_ids.includes(id11)), "An ID cannot be added and removed together");
|
|
2144
|
+
var locationChanges = z9.object({ include: delta.optional(), exclude: delta.optional() }).strict().refine((value) => value.include !== void 0 || value.exclude !== void 0, "Supply included or excluded location changes");
|
|
2145
|
+
var targetingDevice = z9.enum(["DESKTOP", "MOBILE", "TABLET", "CONNECTED_TV", "OTHER"]);
|
|
2146
|
+
var bidMultiplier = z9.number().finite().min(0.1).max(10);
|
|
2147
|
+
var scheduleDay = z9.enum(["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY"]);
|
|
2148
|
+
var minute = z9.union([z9.literal(0), z9.literal(15), z9.literal(30), z9.literal(45)]);
|
|
2149
|
+
var adSchedule = z9.object({ day: scheduleDay, start_hour: z9.number().int().min(0).max(23), start_minute: minute, end_hour: z9.number().int().min(0).max(24), end_minute: minute, bid_modifier: bidMultiplier.optional() }).strict().refine((value) => value.end_hour !== 24 || value.end_minute === 0, "24:00 must end at minute0").refine((value) => value.end_hour * 60 + value.end_minute > value.start_hour * 60 + value.start_minute, "End must follow start within the same account-local day; split overnight schedules");
|
|
2150
|
+
var schedules = z9.array(adSchedule).max(42).superRefine((values, ctx) => {
|
|
1842
2151
|
for (const day of scheduleDay.options) {
|
|
1843
2152
|
const rows = values.filter((value) => value.day === day).sort((a, b) => a.start_hour * 60 + a.start_minute - b.start_hour * 60 - b.start_minute);
|
|
1844
2153
|
if (rows.length > 6) ctx.addIssue({ code: "custom", message: "Native maximum: six schedules per day" });
|
|
1845
2154
|
if (rows.some((value, index) => index && value.start_hour * 60 + value.start_minute < rows[index - 1].end_hour * 60 + rows[index - 1].end_minute)) ctx.addIssue({ code: "custom", message: "Schedules on a day must not overlap" });
|
|
1846
2155
|
}
|
|
1847
2156
|
});
|
|
1848
|
-
var targetingUpdate =
|
|
2157
|
+
var targetingUpdate = z9.object({
|
|
1849
2158
|
campaign_id: targetingId,
|
|
1850
|
-
expected_snapshot_hash:
|
|
1851
|
-
acknowledge_delivery_effects:
|
|
2159
|
+
expected_snapshot_hash: z9.string().regex(/^[a-f0-9]{64}$/),
|
|
2160
|
+
acknowledge_delivery_effects: z9.literal(true),
|
|
1852
2161
|
locations: locationChanges.optional(),
|
|
1853
2162
|
languages: delta.optional(),
|
|
1854
2163
|
ad_schedules: schedules.optional().describe("Replaces weekly schedule; [] removes its time restrictions. Account timezone; omitted intervals retain their existing modifier only when unchanged."),
|
|
1855
|
-
device_bid_modifiers:
|
|
1856
|
-
positive_geo_target_type:
|
|
1857
|
-
negative_geo_target_type:
|
|
2164
|
+
device_bid_modifiers: z9.array(z9.object({ device: targetingDevice, bid_modifier: z9.union([z9.literal(0), bidMultiplier]) }).strict()).min(1).max(5).refine((values) => unique2(values.map((value) => value.device)), "Use unique device types").optional(),
|
|
2165
|
+
positive_geo_target_type: z9.enum(["PRESENCE", "PRESENCE_OR_INTEREST", "SEARCH_INTEREST"]).optional(),
|
|
2166
|
+
negative_geo_target_type: z9.enum(["PRESENCE", "PRESENCE_OR_INTEREST"]).optional()
|
|
1858
2167
|
}).strict().refine((value) => ["locations", "languages", "ad_schedules", "device_bid_modifiers", "positive_geo_target_type", "negative_geo_target_type"].some((key2) => value[key2] !== void 0), "Supply a targeting change");
|
|
1859
|
-
var targetingList =
|
|
1860
|
-
var nativeSchedule =
|
|
1861
|
-
var nativeTargetingCriterion =
|
|
2168
|
+
var targetingList = z9.object({ account_id: z9.string(), campaign_id: targetingId, page_size: z9.number().int().positive().max(200).default(50), cursor: z9.string().min(1).max(1024).regex(/^[A-Za-z0-9_-]+$/).optional() }).strict();
|
|
2169
|
+
var nativeSchedule = z9.object({ dayOfWeek: scheduleDay, startHour: z9.number().int().min(0).max(23), startMinute: z9.enum(["ZERO", "FIFTEEN", "THIRTY", "FORTY_FIVE"]), endHour: z9.number().int().min(0).max(24), endMinute: z9.enum(["ZERO", "FIFTEEN", "THIRTY", "FORTY_FIVE"]) }).strict();
|
|
2170
|
+
var nativeTargetingCriterion = z9.object({ resourceName: z9.string(), criterionId: targetingId, campaign: z9.string(), type: z9.enum(["LOCATION", "LANGUAGE", "DEVICE", "AD_SCHEDULE", "LOCATION_GROUP", "PROXIMITY"]), status: z9.enum(["ENABLED", "PAUSED"]), negative: z9.boolean().default(false), bidModifier: z9.number().finite().optional(), location: z9.object({ geoTargetConstant: z9.string().regex(/^geoTargetConstants\/[1-9]\d*$/) }).optional(), language: z9.object({ languageConstant: z9.string().regex(/^languageConstants\/[1-9]\d*$/) }).optional(), device: z9.object({ type: z9.string() }).optional(), adSchedule: nativeSchedule.optional() }).strict();
|
|
1862
2171
|
|
|
1863
2172
|
// src/targeting.ts
|
|
1864
2173
|
var BOUND = 2e4;
|
|
@@ -1866,13 +2175,13 @@ var fields4 = ["resource_name", "criterion_id", "campaign", "type", "status", "n
|
|
|
1866
2175
|
var types = ["LOCATION", "LANGUAGE", "DEVICE", "AD_SCHEDULE", "LOCATION_GROUP", "PROXIMITY"];
|
|
1867
2176
|
var infoFields = { LOCATION: "location", LANGUAGE: "language", DEVICE: "device", AD_SCHEDULE: "adSchedule" };
|
|
1868
2177
|
var minuteWire = ["ZERO", "FIFTEEN", "THIRTY", "FORTY_FIVE"];
|
|
1869
|
-
var
|
|
1870
|
-
var
|
|
1871
|
-
var
|
|
1872
|
-
var equal = (a, b) =>
|
|
2178
|
+
var object5 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
2179
|
+
var canonical5 = (value) => Array.isArray(value) ? value.map(canonical5) : value && typeof value === "object" ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key2, item]) => [key2, canonical5(item)])) : value;
|
|
2180
|
+
var digest6 = (value) => createHash7("sha256").update(JSON.stringify(canonical5(value))).digest("hex");
|
|
2181
|
+
var equal = (a, b) => digest6(a) === digest6(b);
|
|
1873
2182
|
var float = (value) => typeof value === "number" ? Math.fround(value) : value;
|
|
1874
2183
|
var comparable = (value) => ({ ...value, ...value.bidModifier !== void 0 ? { bidModifier: float(value.bidModifier) } : {} });
|
|
1875
|
-
var key = (value) => `${value.type}:${value.negative}:${value.location?.geoTargetConstant ?? value.language?.languageConstant ?? value.device?.type ?? (value.adSchedule ?
|
|
2184
|
+
var key = (value) => `${value.type}:${value.negative}:${value.location?.geoTargetConstant ?? value.language?.languageConstant ?? value.device?.type ?? (value.adSchedule ? digest6(value.adSchedule) : value.criterionId)}`;
|
|
1876
2185
|
var scheduleWire = (value) => ({ dayOfWeek: value.day, startHour: value.start_hour, startMinute: minuteWire[value.start_minute / 15], endHour: value.end_hour, endMinute: minuteWire[value.end_minute / 15] });
|
|
1877
2186
|
var scheduleText = (value) => `${value.dayOfWeek} ${String(value.startHour).padStart(2, "0")}:${String(minuteWire.indexOf(value.startMinute) * 15).padStart(2, "0")}\u2013${String(value.endHour).padStart(2, "0")}:${String(minuteWire.indexOf(value.endMinute) * 15).padStart(2, "0")}`;
|
|
1878
2187
|
var multiplierText = (value) => value === void 0 ? "Not reported" : `${Number(value.toPrecision(7))}\xD7`;
|
|
@@ -1885,25 +2194,25 @@ var GoogleTargetingService = class {
|
|
|
1885
2194
|
async context(accountId, campaignId) {
|
|
1886
2195
|
const account2 = normalizeCustomerId(accountId), campaignResource = `customers/${account2}/campaigns/${campaignId}`;
|
|
1887
2196
|
const customerRows = await this.client.search(account2, "SELECT customer.resource_name, customer.id, customer.currency_code, customer.time_zone FROM customer LIMIT 2", { maxRows: 2 });
|
|
1888
|
-
const customer =
|
|
1889
|
-
if (customerRows.length !== 1 || customer.id !== account2 || customer.resourceName !== `customers/${account2}` || typeof customer.timeZone !== "string" || typeof customer.currencyCode !== "string") throw new
|
|
2197
|
+
const customer = object5(customerRows[0]?.customer);
|
|
2198
|
+
if (customerRows.length !== 1 || customer.id !== account2 || customer.resourceName !== `customers/${account2}` || typeof customer.timeZone !== "string" || typeof customer.currencyCode !== "string") throw new AdportError10("PROVIDER_ERROR", "google: exact customer currency/timezone context was not returned");
|
|
1890
2199
|
const rows = await this.client.search(account2, `SELECT campaign.resource_name, campaign.id, campaign.name, campaign.status, campaign.advertising_channel_type, campaign.advertising_channel_sub_type, campaign.bidding_strategy_type, campaign.campaign_budget, campaign.geo_target_type_setting.positive_geo_target_type, campaign.geo_target_type_setting.negative_geo_target_type, campaign_budget.resource_name, campaign_budget.amount_micros, campaign_budget.total_amount_micros, campaign_budget.period, campaign_budget.explicitly_shared FROM campaign WHERE campaign.id = ${campaignId} LIMIT 2`, { maxRows: 2, includeDrafts: true });
|
|
1891
|
-
const campaign =
|
|
1892
|
-
if (rows.length !== 1 || campaign.id !== campaignId || campaign.resourceName !== campaignResource || !["ENABLED", "PAUSED"].includes(String(campaign.status)) || typeof campaign.advertisingChannelType !== "string" || campaign.campaignBudget !== budget.resourceName || !new RegExp(`^customers/${account2}/campaignBudgets/[1-9]\\d*$`).test(String(budget.resourceName))) throw new
|
|
2200
|
+
const campaign = object5(rows[0]?.campaign), budget = object5(rows[0]?.campaignBudget);
|
|
2201
|
+
if (rows.length !== 1 || campaign.id !== campaignId || campaign.resourceName !== campaignResource || !["ENABLED", "PAUSED"].includes(String(campaign.status)) || typeof campaign.advertisingChannelType !== "string" || campaign.campaignBudget !== budget.resourceName || !new RegExp(`^customers/${account2}/campaignBudgets/[1-9]\\d*$`).test(String(budget.resourceName))) throw new AdportError10("INVALID_INPUT", "google: available campaign and owned budget configuration are required");
|
|
1893
2202
|
const native = await this.client.search(account2, `SELECT campaign.id, ${fields4.join(", ")} FROM campaign_criterion WHERE campaign.id = ${campaignId} AND campaign_criterion.status != 'REMOVED' AND campaign_criterion.type IN (${types.map((type) => `'${type}'`).join(",")}) ORDER BY campaign_criterion.criterion_id ASC LIMIT ${BOUND + 1}`, { maxRows: BOUND + 1, includeDrafts: true });
|
|
1894
|
-
if (native.length > BOUND) throw new
|
|
2203
|
+
if (native.length > BOUND) throw new AdportError10("PROVIDER_ERROR", "google: complete targeting context exceeds the20,000 criterion safety bound");
|
|
1895
2204
|
const seen = /* @__PURE__ */ new Set(), selections = /* @__PURE__ */ new Set(), criteria = native.map((value) => {
|
|
1896
2205
|
const parsed = nativeTargetingCriterion.safeParse(value.campaignCriterion);
|
|
1897
|
-
if (!parsed.success) throw new
|
|
2206
|
+
if (!parsed.success) throw new AdportError10("PROVIDER_ERROR", "google: targeting criterion configuration is incomplete or unsupported");
|
|
1898
2207
|
const row2 = parsed.data, info = infoFields[row2.type];
|
|
1899
|
-
if (
|
|
1900
|
-
if (selections.has(key(row2))) throw new
|
|
2208
|
+
if (object5(value.campaign).id !== campaignId || row2.campaign !== campaignResource || row2.resourceName !== `customers/${account2}/campaignCriteria/${campaignId}~${row2.criterionId}` || seen.has(row2.criterionId) || info && !row2[info] || ["location", "language", "device", "adSchedule"].filter((field3) => row2[field3] !== void 0).length !== (info ? 1 : 0) || row2.negative && ["LANGUAGE", "DEVICE", "AD_SCHEDULE", "PROXIMITY", "LOCATION_GROUP"].includes(row2.type)) throw new AdportError10("PROVIDER_ERROR", "google: criterion identity, hierarchy, type or polarity mismatch");
|
|
2209
|
+
if (selections.has(key(row2))) throw new AdportError10("PROVIDER_ERROR", "google: duplicate semantic targeting criteria prevent a reliable update");
|
|
1901
2210
|
seen.add(row2.criterionId);
|
|
1902
2211
|
selections.add(key(row2));
|
|
1903
2212
|
return row2;
|
|
1904
2213
|
}).sort((a, b) => BigInt(a.criterionId) < BigInt(b.criterionId) ? -1 : 1);
|
|
1905
2214
|
const snapshot = { account_id: account2, customer, campaign, budget, criteria };
|
|
1906
|
-
return { ...snapshot, snapshot_hash:
|
|
2215
|
+
return { ...snapshot, snapshot_hash: digest6(snapshot) };
|
|
1907
2216
|
}
|
|
1908
2217
|
async constants(account2, ids2, kind, required) {
|
|
1909
2218
|
const values = [...new Set(ids2)], found = /* @__PURE__ */ new Map(), resource = kind === "LOCATION" ? "geo_target_constant" : "language_constant", property = kind === "LOCATION" ? "geoTargetConstant" : "languageConstant";
|
|
@@ -1911,12 +2220,12 @@ var GoogleTargetingService = class {
|
|
|
1911
2220
|
const batch = values.slice(index, index + 100), selected2 = kind === "LOCATION" ? "geo_target_constant.resource_name, geo_target_constant.id, geo_target_constant.name, geo_target_constant.country_code, geo_target_constant.target_type, geo_target_constant.status" : "language_constant.resource_name, language_constant.id, language_constant.name, language_constant.code, language_constant.targetable";
|
|
1912
2221
|
const rows = await this.client.search(account2, `SELECT ${selected2} FROM ${resource} WHERE ${resource}.id IN (${batch.join(",")}) LIMIT ${batch.length + 1}`, { maxRows: batch.length + 1 });
|
|
1913
2222
|
for (const raw of rows) {
|
|
1914
|
-
const value =
|
|
1915
|
-
if (!batch.includes(
|
|
1916
|
-
found.set(
|
|
2223
|
+
const value = object5(raw[property]), id11 = String(value.id ?? "");
|
|
2224
|
+
if (!batch.includes(id11) || value.resourceName !== `${kind === "LOCATION" ? "geoTargetConstants" : "languageConstants"}/${id11}` || found.has(id11) || required && (kind === "LOCATION" ? value.status !== "ENABLED" : value.targetable !== true)) throw new AdportError10("INVALID_INPUT", "google: referenced targeting constant is unverified, duplicated or not currently targetable");
|
|
2225
|
+
found.set(id11, value);
|
|
1917
2226
|
}
|
|
1918
2227
|
}
|
|
1919
|
-
if (required && values.some((
|
|
2228
|
+
if (required && values.some((id11) => !found.has(id11))) throw new AdportError10("INVALID_INPUT", "google: not every requested targeting constant was returned");
|
|
1920
2229
|
return found;
|
|
1921
2230
|
}
|
|
1922
2231
|
async list(raw) {
|
|
@@ -1924,45 +2233,45 @@ var GoogleTargetingService = class {
|
|
|
1924
2233
|
let offset = 0;
|
|
1925
2234
|
if (input2.cursor) {
|
|
1926
2235
|
try {
|
|
1927
|
-
const parsed =
|
|
2236
|
+
const parsed = z10.object({ account: z10.string(), campaign: z10.string(), hash: z10.string(), offset: z10.number().int().positive(), size: z10.number().int().positive() }).strict().parse(JSON.parse(Buffer.from(input2.cursor, "base64url").toString("utf8")));
|
|
1928
2237
|
if (parsed.account !== context.account_id || parsed.campaign !== input2.campaign_id || parsed.hash !== context.snapshot_hash || parsed.size !== input2.page_size || parsed.offset >= context.criteria.length || parsed.offset % parsed.size) throw new Error("stale cursor");
|
|
1929
2238
|
offset = parsed.offset;
|
|
1930
2239
|
} catch {
|
|
1931
|
-
throw new
|
|
2240
|
+
throw new AdportError10("INVALID_INPUT", "google: targeting continuation changed or belongs to another selection; refresh the first page");
|
|
1932
2241
|
}
|
|
1933
2242
|
}
|
|
1934
2243
|
const page = context.criteria.slice(offset, offset + input2.page_size), warnings2 = [], labels = /* @__PURE__ */ new Map();
|
|
1935
2244
|
for (const kind of ["LOCATION", "LANGUAGE"]) {
|
|
1936
2245
|
const ids2 = page.filter((row2) => row2.type === kind).map((row2) => (kind === "LOCATION" ? row2.location.geoTargetConstant : row2.language.languageConstant).split("/").at(-1));
|
|
1937
2246
|
try {
|
|
1938
|
-
for (const [
|
|
2247
|
+
for (const [id11, value] of await this.constants(context.account_id, ids2, kind, false)) if (typeof value.name === "string") labels.set(`${kind}:${id11}`, value.name);
|
|
1939
2248
|
} catch {
|
|
1940
2249
|
warnings2.push(`${kind} names were not resolved; native IDs and configuration remain available.`);
|
|
1941
2250
|
}
|
|
1942
2251
|
}
|
|
1943
2252
|
const languageNote = context.campaign.advertisingChannelType === "SEARCH" ? "Search manual language targets are legacy and do not control serving. Only their removal is supported." : context.campaign.advertisingChannelType === "PERFORMANCE_MAX" ? "Performance Max language criteria apply outside Google Search; Search matching is automatic." : "Language criterion eligibility remains native campaign-specific.";
|
|
1944
2253
|
const records = page.map((row2) => {
|
|
1945
|
-
const
|
|
2254
|
+
const id11 = (row2.location?.geoTargetConstant ?? row2.language?.languageConstant)?.split("/").at(-1), name5 = id11 ? labels.get(`${row2.type}:${id11}`) ?? id11 : row2.device?.type ?? (row2.adSchedule ? scheduleText(row2.adSchedule) : `Retained ${row2.type}`);
|
|
1946
2255
|
return { id: row2.criterionId, name: name5, kind: row2.type, scope: row2.negative ? "Excluded" : "Targeted", status: row2.status, ...row2.type === "DEVICE" || row2.type === "AD_SCHEDULE" ? { bid_multiplier: multiplierText(row2.bidModifier) } : {}, ...row2.type === "LANGUAGE" && context.campaign.advertisingChannelType === "SEARCH" ? { serving: "Legacy \xB7 not used by Search" } : {} };
|
|
1947
2256
|
});
|
|
1948
2257
|
const end = offset + page.length;
|
|
1949
2258
|
return { account_id: context.account_id, campaign_id: input2.campaign_id, campaign: context.campaign, customer: context.customer, budget: context.budget, snapshot_hash: context.snapshot_hash, records, criteria: page, total_criteria: context.criteria.length, truncated: end < context.criteria.length, ...end < context.criteria.length ? { next_cursor: Buffer.from(JSON.stringify({ account: context.account_id, campaign: input2.campaign_id, hash: context.snapshot_hash, offset: end, size: input2.page_size })).toString("base64url") } : {}, notes: [languageNote, "LOCATION_GROUP and PROXIMITY references are retained and are not edited by this tool. A location-ID list is not the entire geographic targeting model.", ...notes], warnings: warnings2 };
|
|
1950
2259
|
}
|
|
1951
2260
|
async plan(op) {
|
|
1952
|
-
if (op.provider !== "google" || op.kind !== "update" || op.tool !== "google_update_targeting") throw new
|
|
2261
|
+
if (op.provider !== "google" || op.kind !== "update" || op.tool !== "google_update_targeting") throw new AdportError10("INVALID_INPUT", "google: targeting operation provider/kind mismatch");
|
|
1953
2262
|
const input2 = targetingUpdate.parse(op.payload), before = await this.context(op.accountId, input2.campaign_id);
|
|
1954
|
-
if (before.snapshot_hash !== input2.expected_snapshot_hash) throw new
|
|
2263
|
+
if (before.snapshot_hash !== input2.expected_snapshot_hash) throw new AdportError10("PENDING_MISMATCH", "google: targeting, parent or budget configuration changed; read and preview it again");
|
|
1955
2264
|
const campaign = String(before.campaign.resourceName), removals = /* @__PURE__ */ new Set(), updates = /* @__PURE__ */ new Map(), creates = [], reviewFields = [{ label: "Campaign", after: before.campaign.name }, { label: "Campaign status", after: before.campaign.status }, { label: "Account timezone", after: before.customer.timeZone }];
|
|
1956
2265
|
const patch = (row2, fields5) => updates.set(row2.resourceName, { ...updates.get(row2.resourceName), ...fields5 });
|
|
1957
2266
|
const changeIds = async (kind, negative, delta2) => {
|
|
1958
2267
|
if (!delta2) return;
|
|
1959
|
-
if (kind === "LANGUAGE" && before.campaign.advertisingChannelType === "SEARCH" && delta2.add_ids.length) throw new
|
|
2268
|
+
if (kind === "LANGUAGE" && before.campaign.advertisingChannelType === "SEARCH" && delta2.add_ids.length) throw new AdportError10("INVALID_INPUT", "google: Search manual language creation/update is no longer supported; only legacy criterion removal is available");
|
|
1960
2269
|
const current = before.criteria.filter((row2) => row2.type === kind && row2.negative === negative), idOf = (row2) => (kind === "LOCATION" ? row2.location.geoTargetConstant : row2.language.languageConstant).split("/").at(-1);
|
|
1961
|
-
if (delta2.add_ids.some((
|
|
2270
|
+
if (delta2.add_ids.some((id11) => current.some((row2) => idOf(row2) === id11)) || delta2.remove_ids.some((id11) => !current.some((row2) => idOf(row2) === id11))) throw new AdportError10("INVALID_INPUT", "google: targeting additions already exist or removals were not found; no mutation submitted");
|
|
1962
2271
|
const constants = await this.constants(before.account_id, delta2.add_ids, kind, true);
|
|
1963
|
-
for (const
|
|
1964
|
-
for (const
|
|
1965
|
-
if (delta2.add_ids.length) reviewFields.push({ label: `Add ${negative ? "excluded" : "targeted"} ${kind.toLowerCase()}`, after: delta2.add_ids.map((
|
|
2272
|
+
for (const id11 of delta2.remove_ids) removals.add(current.find((row2) => idOf(row2) === id11).resourceName);
|
|
2273
|
+
for (const id11 of delta2.add_ids) creates.push({ campaign, status: "ENABLED", negative, ...kind === "LOCATION" ? { location: { geoTargetConstant: `geoTargetConstants/${id11}` } } : { language: { languageConstant: `languageConstants/${id11}` } } });
|
|
2274
|
+
if (delta2.add_ids.length) reviewFields.push({ label: `Add ${negative ? "excluded" : "targeted"} ${kind.toLowerCase()}`, after: delta2.add_ids.map((id11) => `${constants.get(id11)?.name ?? id11} [${id11}]`) });
|
|
1966
2275
|
if (delta2.remove_ids.length) reviewFields.push({ label: `Remove ${negative ? "excluded" : "targeted"} ${kind.toLowerCase()}`, after: delta2.remove_ids });
|
|
1967
2276
|
};
|
|
1968
2277
|
await changeIds("LOCATION", false, input2.locations?.include);
|
|
@@ -1970,14 +2279,14 @@ var GoogleTargetingService = class {
|
|
|
1970
2279
|
await changeIds("LANGUAGE", false, input2.languages);
|
|
1971
2280
|
if (input2.locations) {
|
|
1972
2281
|
const retained = before.criteria.filter((row2) => row2.type === "LOCATION" && !removals.has(row2.resourceName));
|
|
1973
|
-
const included = /* @__PURE__ */ new Set([...retained.filter((row2) => !row2.negative).map((row2) => row2.location.geoTargetConstant), ...creates.filter((row2) => !row2.negative && row2.location).map((row2) => String(
|
|
1974
|
-
const excluded = /* @__PURE__ */ new Set([...retained.filter((row2) => row2.negative).map((row2) => row2.location.geoTargetConstant), ...creates.filter((row2) => row2.negative && row2.location).map((row2) => String(
|
|
1975
|
-
if ([...included].some((value) => excluded.has(value))) throw new
|
|
2282
|
+
const included = /* @__PURE__ */ new Set([...retained.filter((row2) => !row2.negative).map((row2) => row2.location.geoTargetConstant), ...creates.filter((row2) => !row2.negative && row2.location).map((row2) => String(object5(row2.location).geoTargetConstant))]);
|
|
2283
|
+
const excluded = /* @__PURE__ */ new Set([...retained.filter((row2) => row2.negative).map((row2) => row2.location.geoTargetConstant), ...creates.filter((row2) => row2.negative && row2.location).map((row2) => String(object5(row2.location).geoTargetConstant))]);
|
|
2284
|
+
if ([...included].some((value) => excluded.has(value))) throw new AdportError10("INVALID_INPUT", "google: the same location cannot be both explicitly included and excluded");
|
|
1976
2285
|
if (!included.size) reviewFields.push({ label: "Remaining included location IDs", after: "None. Other radius/group criteria and exclusions are retained; without other positive geography, reach is unrestricted by included locations." });
|
|
1977
2286
|
}
|
|
1978
2287
|
if (input2.ad_schedules !== void 0) {
|
|
1979
|
-
const current = before.criteria.filter((row2) => row2.type === "AD_SCHEDULE"), wanted = new Set(input2.ad_schedules.map((value) =>
|
|
1980
|
-
for (const row2 of current) if (!wanted.has(
|
|
2288
|
+
const current = before.criteria.filter((row2) => row2.type === "AD_SCHEDULE"), wanted = new Set(input2.ad_schedules.map((value) => digest6(scheduleWire(value))));
|
|
2289
|
+
for (const row2 of current) if (!wanted.has(digest6(row2.adSchedule))) removals.add(row2.resourceName);
|
|
1981
2290
|
for (const value of input2.ad_schedules) {
|
|
1982
2291
|
const wire3 = scheduleWire(value), existing = current.find((row2) => equal(row2.adSchedule, wire3));
|
|
1983
2292
|
if (!existing) creates.push({ campaign, status: "ENABLED", negative: false, adSchedule: wire3, ...value.bid_modifier !== void 0 ? { bidModifier: value.bid_modifier } : {} });
|
|
@@ -1987,15 +2296,15 @@ var GoogleTargetingService = class {
|
|
|
1987
2296
|
}
|
|
1988
2297
|
for (const value of input2.device_bid_modifiers ?? []) {
|
|
1989
2298
|
const current = before.criteria.filter((row3) => row3.type === "DEVICE" && row3.device?.type === value.device);
|
|
1990
|
-
if (current.length !== 1) throw new
|
|
2299
|
+
if (current.length !== 1) throw new AdportError10("INVALID_INPUT", "google: device bid changes require an existing exact device criterion; device types are not created or removed here");
|
|
1991
2300
|
const row2 = current[0];
|
|
1992
2301
|
if (float(row2.bidModifier) !== float(value.bid_modifier)) {
|
|
1993
2302
|
patch(row2, { bidModifier: value.bid_modifier });
|
|
1994
2303
|
reviewFields.push({ label: `${value.device} bid multiplier`, before: multiplierText(row2.bidModifier), after: value.bid_modifier === 0 ? "0\xD7 \xB7 device excluded" : multiplierText(value.bid_modifier) });
|
|
1995
2304
|
}
|
|
1996
2305
|
}
|
|
1997
|
-
const geo = {}, geoMask = [], existingGeo =
|
|
1998
|
-
if (before.campaign.advertisingChannelType === "SEARCH" && (input2.positive_geo_target_type === "SEARCH_INTEREST" || input2.negative_geo_target_type === "PRESENCE_OR_INTEREST")) throw new
|
|
2306
|
+
const geo = {}, geoMask = [], existingGeo = object5(before.campaign.geoTargetTypeSetting);
|
|
2307
|
+
if (before.campaign.advertisingChannelType === "SEARCH" && (input2.positive_geo_target_type === "SEARCH_INTEREST" || input2.negative_geo_target_type === "PRESENCE_OR_INTEREST")) throw new AdportError10("INVALID_INPUT", "google: Search supports PRESENCE/PRESENCE_OR_INTEREST positive intent and PRESENCE exclusion intent; native validation rejected the selected combination");
|
|
1999
2308
|
for (const [inputKey, nativeKey] of [["positive_geo_target_type", "positiveGeoTargetType"], ["negative_geo_target_type", "negativeGeoTargetType"]]) if (input2[inputKey] !== void 0 && input2[inputKey] !== existingGeo[nativeKey]) {
|
|
2000
2309
|
geo[nativeKey] = input2[inputKey];
|
|
2001
2310
|
geoMask.push(`geo_target_type_setting.${inputKey}`);
|
|
@@ -2004,14 +2313,14 @@ var GoogleTargetingService = class {
|
|
|
2004
2313
|
const operations = [...removals].map((resource) => ({ campaignCriterionOperation: { remove: resource } }));
|
|
2005
2314
|
for (const [resourceName, changes] of updates) {
|
|
2006
2315
|
const current = before.criteria.find((row2) => row2.resourceName === resourceName);
|
|
2007
|
-
if (removals.has(resourceName)) throw new
|
|
2316
|
+
if (removals.has(resourceName)) throw new AdportError10("INVALID_INPUT", "google: cannot edit and remove the same criterion");
|
|
2008
2317
|
const info = Object.fromEntries(["location", "language", "device", "adSchedule"].filter((key2) => current[key2] !== void 0).map((key2) => [key2, current[key2]]));
|
|
2009
2318
|
operations.push({ campaignCriterionOperation: { update: { resourceName, ...info, ...changes }, updateMask: Object.keys(changes).map((key2) => key2 === "bidModifier" ? "bid_modifier" : key2).join(",") } });
|
|
2010
2319
|
}
|
|
2011
2320
|
operations.push(...creates.map((create3) => ({ campaignCriterionOperation: { create: create3 } })));
|
|
2012
2321
|
if (geoMask.length) operations.push({ campaignOperation: { update: { resourceName: campaign, geoTargetTypeSetting: geo }, updateMask: geoMask.join(",") } });
|
|
2013
|
-
if (!operations.length) throw new
|
|
2014
|
-
if (operations.length > 5e3) throw new
|
|
2322
|
+
if (!operations.length) throw new AdportError10("INVALID_INPUT", "google: no targeting configuration change remains after comparing current values");
|
|
2323
|
+
if (operations.length > 5e3) throw new AdportError10("INVALID_INPUT", "google: targeting edits exceed the5,000-operation tool bound; use smaller changes");
|
|
2015
2324
|
const reviewNotes = [...notes, before.campaign.advertisingChannelType === "SEARCH" ? "Search legacy language criteria are not used in serving; removal is cleanup, not a new language restriction." : before.campaign.advertisingChannelType === "PERFORMANCE_MAX" ? "Performance Max language settings apply only outside Google Search." : "Google validates criterion/campaign compatibility before approval.", "Schedules use the account timezone, with exclusive end times. [] removes time restrictions. Location/language add/remove lists preserve every unmentioned criterion."];
|
|
2016
2325
|
let details;
|
|
2017
2326
|
return {
|
|
@@ -2026,23 +2335,23 @@ var GoogleTargetingService = class {
|
|
|
2026
2335
|
const known = /* @__PURE__ */ new Set([...removals, ...updates.keys(), ...geoMask.length ? [campaign] : []]);
|
|
2027
2336
|
try {
|
|
2028
2337
|
const result2 = await this.client.googleAdsMutate(before.account_id, operations, { validateOnly });
|
|
2029
|
-
if (!result2 || typeof result2 !== "object" || Array.isArray(result2)) throw new
|
|
2338
|
+
if (!result2 || typeof result2 !== "object" || Array.isArray(result2)) throw new AdportError10("PROVIDER_ERROR", "google: targeting mutate response envelope could not be verified");
|
|
2030
2339
|
const responses = result2.mutateOperationResponses;
|
|
2031
2340
|
if (Array.isArray(responses)) {
|
|
2032
|
-
for (const response of responses) for (const value of Object.values(
|
|
2341
|
+
for (const response of responses) for (const value of Object.values(object5(response))) if (typeof object5(value).resourceName === "string") known.add(String(object5(value).resourceName));
|
|
2033
2342
|
}
|
|
2034
2343
|
if ("partialFailureError" in result2) throw new Error("unexpected partial failure");
|
|
2035
2344
|
if (validateOnly) return [];
|
|
2036
2345
|
if (!Array.isArray(responses) || responses.length !== operations.length) throw new Error("mutation receipt count mismatch");
|
|
2037
2346
|
const created = [];
|
|
2038
2347
|
for (let index = 0; index < operations.length; index++) {
|
|
2039
|
-
const operation = operations[index], criterionOp =
|
|
2348
|
+
const operation = operations[index], criterionOp = object5(operation.campaignCriterionOperation), campaignOp = object5(operation.campaignOperation), expectedKey = operation.campaignCriterionOperation ? "campaignCriterionResult" : "campaignResult", response = responses[index];
|
|
2040
2349
|
if (Object.keys(response).length !== 1 || !response[expectedKey]) throw new Error("mutation receipt type mismatch");
|
|
2041
2350
|
const resource = response[expectedKey].resourceName;
|
|
2042
2351
|
if (criterionOp.create) {
|
|
2043
2352
|
if (typeof resource !== "string" || !new RegExp(`^customers/${before.account_id}/campaignCriteria/${input2.campaign_id}~[1-9]\\d*$`).test(resource) || before.criteria.some((row2) => row2.resourceName === resource) || created.some((row2) => row2.id === resource)) throw new Error("created criterion identity mismatch");
|
|
2044
|
-
created.push({ id: resource, value:
|
|
2045
|
-
} else if (resource !== (criterionOp.remove ??
|
|
2353
|
+
created.push({ id: resource, value: object5(criterionOp.create) });
|
|
2354
|
+
} else if (resource !== (criterionOp.remove ?? object5(criterionOp.update).resourceName ?? campaignOp.remove ?? object5(campaignOp.update).resourceName)) throw new Error("mutation receipt scope mismatch");
|
|
2046
2355
|
}
|
|
2047
2356
|
const after = await this.context(before.account_id, input2.campaign_id), expectedCampaign = { ...before.campaign, ...geoMask.length ? { geoTargetTypeSetting: { ...existingGeo, ...geo } } : {} };
|
|
2048
2357
|
if (!equal(after.customer, before.customer) || !equal(after.budget, before.budget) || !equal(after.campaign, expectedCampaign)) throw new Error("parent preservation mismatch");
|
|
@@ -2066,7 +2375,7 @@ var GoogleTargetingService = class {
|
|
|
2066
2375
|
return [...known];
|
|
2067
2376
|
} catch (error) {
|
|
2068
2377
|
if (validateOnly) throw error;
|
|
2069
|
-
throw new
|
|
2378
|
+
throw new AdportError10("PROVIDER_ERROR", "google: targeting mutation outcome was not confirmed. Reconcile acknowledged IDs and current targeting before another change; no write was retried.", { resourceIds: [...known] });
|
|
2070
2379
|
}
|
|
2071
2380
|
}
|
|
2072
2381
|
};
|
|
@@ -2075,8 +2384,493 @@ var GoogleTargetingService = class {
|
|
|
2075
2384
|
function googleTargetingTools(provider) {
|
|
2076
2385
|
const catalog = { category: "audiences", exposure: "specialist" };
|
|
2077
2386
|
return [
|
|
2078
|
-
|
|
2079
|
-
|
|
2387
|
+
defineTool9({ name: "google_campaign_targeting", namespace: "google", catalog, description: "Read scoped campaign location/language/device/schedule configuration and snapshot_hash. Native statuses, omitted bid multipliers and retained radius/group references remain explicit. Stable snapshot paging supports Load more. Search language criteria are legacy, not serving restrictions.", input: targetingList, presentation: "records", pagination: { cursorInput: "cursor" }, annotations: { readOnly: true }, handler: (input2) => provider.targeting.list(input2) }),
|
|
2388
|
+
guardedWriteTool9({ name: "google_update_targeting", namespace: "google", provider: "google", catalog, kind: "update", description: "Edit existing campaign targeting with snapshot_hash and delivery-effects acknowledgement. Location/language additions/removals preserve unmentioned criteria; schedules replace weekly intervals; device multipliers edit existing types. Exact native masks, atomic validateOnly and independent readback. Search languages can only be removed.", payload: targetingUpdate })
|
|
2389
|
+
];
|
|
2390
|
+
}
|
|
2391
|
+
|
|
2392
|
+
// src/negative-keywords.ts
|
|
2393
|
+
import { AdportError as AdportError11, defineTool as defineTool10, guardedWriteTool as guardedWriteTool10 } from "@adport/core";
|
|
2394
|
+
import { z as z11 } from "zod";
|
|
2395
|
+
var NEGATIVE_KEYWORD_MUTATE_BATCH = 1e3;
|
|
2396
|
+
var CAMPAIGN_MUTATE_BATCH = 1e4;
|
|
2397
|
+
var LIST_LIMIT = 5e3;
|
|
2398
|
+
var CAMPAIGN_LIMIT = 1e4;
|
|
2399
|
+
var OPERATION_BOUND = 2e4;
|
|
2400
|
+
var SAMPLE = 10;
|
|
2401
|
+
var id9 = z11.string().regex(/^[1-9]\d*$/);
|
|
2402
|
+
var keyword = z11.object({ text: z11.string().trim().min(1).max(80), match_type: z11.enum(["EXACT", "PHRASE", "BROAD"]) });
|
|
2403
|
+
var keywords = z11.array(keyword).min(1).max(LIST_LIMIT);
|
|
2404
|
+
var campaignIds2 = z11.array(id9).min(1).max(100);
|
|
2405
|
+
var createList = z11.object({ name: z11.string().trim().min(1).max(255), keywords, campaign_ids: campaignIds2.optional() });
|
|
2406
|
+
var updateList = z11.object({ shared_set_id: id9, add_keywords: keywords.optional(), remove_keywords: keywords.optional() }).refine((value) => value.add_keywords !== void 0 || value.remove_keywords !== void 0, "Supply add_keywords or remove_keywords");
|
|
2407
|
+
var linkList = z11.object({ shared_set_id: id9, action: z11.enum(["attach", "detach"]), campaign_ids: campaignIds2 });
|
|
2408
|
+
var campaignNegatives = z11.object({ campaign_ids: campaignIds2, keywords });
|
|
2409
|
+
var GOOGLE_NEGATIVE_KEYWORD_WRITES = /* @__PURE__ */ new Set(["google_create_negative_keyword_list", "google_update_negative_keyword_list", "google_link_negative_keyword_list", "google_add_campaign_negative_keywords"]);
|
|
2410
|
+
var kinds3 = { google_create_negative_keyword_list: "create", google_update_negative_keyword_list: "update", google_link_negative_keyword_list: "update", google_add_campaign_negative_keywords: "create" };
|
|
2411
|
+
var object6 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
2412
|
+
var normalized = (value) => value.trim().replace(/\s+/g, " ");
|
|
2413
|
+
var keyOf = (value) => `${value.match_type}:${normalized(value.text).toLowerCase()}`;
|
|
2414
|
+
var formatKeyword = (value) => value.match_type === "EXACT" ? `[${value.text}]` : value.match_type === "PHRASE" ? `"${value.text}"` : value.text;
|
|
2415
|
+
var sample = (values) => values.length <= SAMPLE ? values.map(formatKeyword) : [...values.slice(0, SAMPLE).map(formatKeyword), `\u2026 and ${values.length - SAMPLE} more`];
|
|
2416
|
+
var chunks2 = (values, size) => Array.from({ length: Math.ceil(values.length / size) }, (_, index) => values.slice(index * size, (index + 1) * size));
|
|
2417
|
+
var plural = (count2, word) => `${count2} ${word}${count2 === 1 ? "" : "s"}`;
|
|
2418
|
+
var INVENTORY_CONCURRENCY = 10;
|
|
2419
|
+
async function mapBounded(values, limit, map) {
|
|
2420
|
+
const results = new Array(values.length);
|
|
2421
|
+
let next = 0;
|
|
2422
|
+
await Promise.all(Array.from({ length: Math.min(limit, values.length) }, async () => {
|
|
2423
|
+
while (next < values.length) {
|
|
2424
|
+
const index = next++;
|
|
2425
|
+
results[index] = await map(values[index]);
|
|
2426
|
+
}
|
|
2427
|
+
}));
|
|
2428
|
+
return results;
|
|
2429
|
+
}
|
|
2430
|
+
var UnconfirmedBatch = class extends AdportError11 {
|
|
2431
|
+
constructor(unconfirmed, cause) {
|
|
2432
|
+
super("PROVIDER_ERROR", cause instanceof Error ? cause.message : "google: negative keyword mutation receipt mismatch");
|
|
2433
|
+
this.unconfirmed = unconfirmed;
|
|
2434
|
+
}
|
|
2435
|
+
unconfirmed;
|
|
2436
|
+
};
|
|
2437
|
+
async function confirmBatch(request, size) {
|
|
2438
|
+
try {
|
|
2439
|
+
return await request;
|
|
2440
|
+
} catch (error) {
|
|
2441
|
+
if (isGoogleAdsRejection(error)) throw error;
|
|
2442
|
+
throw new UnconfirmedBatch(size, error);
|
|
2443
|
+
}
|
|
2444
|
+
}
|
|
2445
|
+
function dedupeKeywords(values) {
|
|
2446
|
+
const seen = /* @__PURE__ */ new Set(), unique3 = [], duplicates = [];
|
|
2447
|
+
for (const value of values) {
|
|
2448
|
+
const item = { text: normalized(value.text), match_type: value.match_type }, key2 = keyOf(item);
|
|
2449
|
+
if (seen.has(key2)) duplicates.push(item);
|
|
2450
|
+
else {
|
|
2451
|
+
seen.add(key2);
|
|
2452
|
+
unique3.push(item);
|
|
2453
|
+
}
|
|
2454
|
+
}
|
|
2455
|
+
return { unique: unique3, duplicates };
|
|
2456
|
+
}
|
|
2457
|
+
var GoogleNegativeKeywordService = class {
|
|
2458
|
+
constructor(client) {
|
|
2459
|
+
this.client = client;
|
|
2460
|
+
}
|
|
2461
|
+
client;
|
|
2462
|
+
listResource(account2, listId) {
|
|
2463
|
+
return `customers/${account2}/sharedSets/${listId}`;
|
|
2464
|
+
}
|
|
2465
|
+
parseList(account2, value) {
|
|
2466
|
+
const row2 = object6(value);
|
|
2467
|
+
if (!id9.safeParse(row2.id).success || row2.resourceName !== this.listResource(account2, String(row2.id)) || row2.type !== "NEGATIVE_KEYWORDS" || row2.status !== "ENABLED" || typeof row2.name !== "string") throw new AdportError11("PROVIDER_ERROR", "google: negative keyword list response has an invalid identity, type or status");
|
|
2468
|
+
return { id: String(row2.id), name: row2.name, status: "ENABLED", member_count: Number(row2.memberCount ?? 0), reference_count: Number(row2.referenceCount ?? 0), resource_name: String(row2.resourceName) };
|
|
2469
|
+
}
|
|
2470
|
+
async readLists(account2, listId) {
|
|
2471
|
+
const rows = await this.client.search(account2, `SELECT shared_set.resource_name, shared_set.id, shared_set.name, shared_set.type, shared_set.status, shared_set.member_count, shared_set.reference_count FROM shared_set WHERE shared_set.type = 'NEGATIVE_KEYWORDS' AND shared_set.status = 'ENABLED'${listId ? ` AND shared_set.id = ${listId}` : ""} ORDER BY shared_set.id ASC LIMIT 1001`, { maxRows: 1001 });
|
|
2472
|
+
if (rows.length > 1e3) throw new AdportError11("PROVIDER_ERROR", "google: negative keyword list inventory exceeds the 1,000 list safety bound");
|
|
2473
|
+
return rows.map((row2) => this.parseList(account2, row2.sharedSet));
|
|
2474
|
+
}
|
|
2475
|
+
async list(account2, listId) {
|
|
2476
|
+
const lists = await this.readLists(account2, listId);
|
|
2477
|
+
if (lists.length !== 1 || lists[0].id !== listId) throw new AdportError11("INVALID_INPUT", "google: enabled negative keyword list was not found in the selected account");
|
|
2478
|
+
return lists[0];
|
|
2479
|
+
}
|
|
2480
|
+
async links(account2, listResources) {
|
|
2481
|
+
if (!listResources.length) return [];
|
|
2482
|
+
const rows = await this.client.search(account2, `SELECT campaign_shared_set.resource_name, campaign_shared_set.campaign, campaign_shared_set.shared_set, campaign_shared_set.status, campaign.id, campaign.name, campaign.status FROM campaign_shared_set WHERE campaign_shared_set.shared_set IN (${listResources.map((value) => `'${value}'`).join(", ")}) AND campaign_shared_set.status = 'ENABLED' AND campaign.status != 'REMOVED' LIMIT 10001`, { maxRows: 10001 });
|
|
2483
|
+
if (rows.length > 1e4) throw new AdportError11("PROVIDER_ERROR", "google: campaign list attachments exceed the 10,000 row safety bound");
|
|
2484
|
+
return rows.map((row2) => {
|
|
2485
|
+
const link = object6(row2.campaignSharedSet), campaign = object6(row2.campaign), listId = String(link.sharedSet ?? "").match(new RegExp(`^customers/${account2}/sharedSets/([1-9]\\d*)$`))?.[1];
|
|
2486
|
+
if (!listId || !listResources.includes(String(link.sharedSet)) || !id9.safeParse(campaign.id).success || link.campaign !== `customers/${account2}/campaigns/${campaign.id}` || link.resourceName !== `customers/${account2}/campaignSharedSets/${campaign.id}~${listId}`) throw new AdportError11("PROVIDER_ERROR", "google: campaign list attachment identity mismatch");
|
|
2487
|
+
return { list_id: listId, resource_name: String(link.resourceName), campaign: { id: String(campaign.id), name: String(campaign.name ?? ""), status: String(campaign.status ?? "") } };
|
|
2488
|
+
});
|
|
2489
|
+
}
|
|
2490
|
+
async criteria(account2, listId) {
|
|
2491
|
+
const rows = await this.client.search(account2, `SELECT shared_criterion.resource_name, shared_criterion.shared_set, shared_criterion.criterion_id, shared_criterion.type, shared_criterion.keyword.text, shared_criterion.keyword.match_type FROM shared_criterion WHERE shared_criterion.shared_set = '${this.listResource(account2, listId)}' AND shared_criterion.type = 'KEYWORD' ORDER BY shared_criterion.criterion_id ASC LIMIT ${LIST_LIMIT + 1}`, { maxRows: LIST_LIMIT + 1 });
|
|
2492
|
+
if (rows.length > LIST_LIMIT) throw new AdportError11("PROVIDER_ERROR", "google: negative keyword list exceeds the 5,000 keyword list limit");
|
|
2493
|
+
return rows.map((row2) => {
|
|
2494
|
+
const value = object6(row2.sharedCriterion), info = object6(value.keyword), parsed = keyword.safeParse({ text: info.text, match_type: info.matchType });
|
|
2495
|
+
if (!parsed.success || !id9.safeParse(value.criterionId).success || value.sharedSet !== this.listResource(account2, listId) || value.resourceName !== `customers/${account2}/sharedCriteria/${listId}~${value.criterionId}`) throw new AdportError11("PROVIDER_ERROR", "google: negative keyword list criterion identity or keyword mismatch");
|
|
2496
|
+
return { ...parsed.data, resourceName: String(value.resourceName), criterionId: String(value.criterionId) };
|
|
2497
|
+
});
|
|
2498
|
+
}
|
|
2499
|
+
async campaigns(account2, ids2) {
|
|
2500
|
+
const unique3 = [...new Set(ids2)];
|
|
2501
|
+
if (unique3.length !== ids2.length) throw new AdportError11("INVALID_INPUT", "google: campaign_ids contains duplicates");
|
|
2502
|
+
const rows = await this.client.search(account2, `SELECT campaign.resource_name, campaign.id, campaign.name, campaign.status, campaign.advertising_channel_type FROM campaign WHERE campaign.id IN (${unique3.join(", ")}) AND campaign.status != 'REMOVED' LIMIT ${unique3.length + 1}`, { maxRows: unique3.length + 1 });
|
|
2503
|
+
const found = /* @__PURE__ */ new Map();
|
|
2504
|
+
for (const row2 of rows) {
|
|
2505
|
+
const value = object6(row2.campaign);
|
|
2506
|
+
if (!unique3.includes(String(value.id)) || found.has(String(value.id)) || value.resourceName !== `customers/${account2}/campaigns/${value.id}` || !["ENABLED", "PAUSED"].includes(String(value.status))) throw new AdportError11("PROVIDER_ERROR", "google: campaign identity or status mismatch");
|
|
2507
|
+
found.set(String(value.id), { id: String(value.id), name: String(value.name ?? ""), status: String(value.status), resourceName: String(value.resourceName) });
|
|
2508
|
+
}
|
|
2509
|
+
const missing = unique3.filter((value) => !found.has(value));
|
|
2510
|
+
if (missing.length) throw new AdportError11("INVALID_INPUT", `google: campaigns not found or removed in the selected account: ${missing.join(", ")}`);
|
|
2511
|
+
return unique3.map((value) => found.get(value));
|
|
2512
|
+
}
|
|
2513
|
+
async campaignNegatives(account2, campaign) {
|
|
2514
|
+
const rows = await this.client.search(account2, `SELECT campaign.id, campaign_criterion.resource_name, campaign_criterion.campaign, campaign_criterion.criterion_id, campaign_criterion.negative, campaign_criterion.keyword.text, campaign_criterion.keyword.match_type FROM campaign_criterion WHERE campaign.id = ${campaign.id} AND campaign_criterion.type = 'KEYWORD' AND campaign_criterion.negative = TRUE AND campaign_criterion.status != 'REMOVED' LIMIT ${CAMPAIGN_LIMIT + 1}`, { maxRows: CAMPAIGN_LIMIT + 1 });
|
|
2515
|
+
if (rows.length > CAMPAIGN_LIMIT) throw new AdportError11("PROVIDER_ERROR", "google: campaign negative keywords exceed the 10,000 criterion safety bound");
|
|
2516
|
+
return rows.map((row2) => {
|
|
2517
|
+
const value = object6(row2.campaignCriterion), info = object6(value.keyword), parsed = keyword.safeParse({ text: info.text, match_type: info.matchType });
|
|
2518
|
+
if (!parsed.success || value.negative !== true || value.campaign !== campaign.resourceName || value.resourceName !== `customers/${account2}/campaignCriteria/${campaign.id}~${value.criterionId}`) throw new AdportError11("PROVIDER_ERROR", "google: campaign negative keyword identity mismatch");
|
|
2519
|
+
return { ...parsed.data, resourceName: String(value.resourceName), criterionId: String(value.criterionId) };
|
|
2520
|
+
});
|
|
2521
|
+
}
|
|
2522
|
+
/** Every enabled list, or one list (shared_set_id) with its keywords up to limit. */
|
|
2523
|
+
async listLists(input2) {
|
|
2524
|
+
const account2 = normalizeCustomerId(input2.account_id), lists = input2.shared_set_id ? [await this.list(account2, input2.shared_set_id)] : await this.readLists(account2);
|
|
2525
|
+
const links = await this.links(account2, lists.map((list2) => list2.resource_name)), limit = input2.limit ?? 1e3;
|
|
2526
|
+
const criteria = input2.shared_set_id ? await this.criteria(account2, input2.shared_set_id) : void 0;
|
|
2527
|
+
return { lists: lists.map(({ resource_name: _resource, status: _status, ...list2 }) => ({
|
|
2528
|
+
...list2,
|
|
2529
|
+
campaigns: links.filter((link) => link.list_id === list2.id).map((link) => link.campaign),
|
|
2530
|
+
...criteria ? { keywords: criteria.slice(0, limit).map((value) => ({ criterion_id: value.criterionId, text: value.text, match_type: value.match_type })), truncated: criteria.length > limit } : {}
|
|
2531
|
+
})) };
|
|
2532
|
+
}
|
|
2533
|
+
async plan(op) {
|
|
2534
|
+
if (op.provider !== "google" || !GOOGLE_NEGATIVE_KEYWORD_WRITES.has(op.tool) || op.kind !== kinds3[op.tool]) throw new AdportError11("INVALID_INPUT", "google: negative keyword operation kind mismatch");
|
|
2535
|
+
const account2 = normalizeCustomerId(op.accountId);
|
|
2536
|
+
if (op.tool === "google_create_negative_keyword_list") return this.planCreate(account2, createList.parse(op.payload));
|
|
2537
|
+
if (op.tool === "google_update_negative_keyword_list") return this.planUpdate(account2, updateList.parse(op.payload));
|
|
2538
|
+
if (op.tool === "google_add_campaign_negative_keywords") return this.planCampaignNegatives(account2, campaignNegatives.parse(op.payload));
|
|
2539
|
+
const link = linkList.parse(op.payload);
|
|
2540
|
+
return this.planLink(account2, link, link.action === "attach");
|
|
2541
|
+
}
|
|
2542
|
+
/** Runs service mutates in bounded batches; each request is atomic (partialFailure=false). */
|
|
2543
|
+
async batches(account2, service, operations, validateOnly, expected, acknowledged, batchSize = NEGATIVE_KEYWORD_MUTATE_BATCH) {
|
|
2544
|
+
for (const batch of chunks2(operations, batchSize)) {
|
|
2545
|
+
const request = this.client.mutate(account2, service, batch, { validateOnly });
|
|
2546
|
+
if (validateOnly) {
|
|
2547
|
+
await request;
|
|
2548
|
+
continue;
|
|
2549
|
+
}
|
|
2550
|
+
const result2 = await confirmBatch(request, batch.length);
|
|
2551
|
+
const resources = (result2.results ?? []).map((value) => value.resourceName ?? "");
|
|
2552
|
+
if (resources.length !== batch.length || resources.some((resource, index) => !expected(batch[index], resource))) throw new UnconfirmedBatch(batch.length);
|
|
2553
|
+
acknowledged.push(...resources);
|
|
2554
|
+
}
|
|
2555
|
+
}
|
|
2556
|
+
outcome(error, acknowledged, total, guidance, details = {}) {
|
|
2557
|
+
const unconfirmed = error instanceof UnconfirmedBatch ? error.unconfirmed : 0;
|
|
2558
|
+
if (!acknowledged.length && !unconfirmed && error instanceof AdportError11) return error;
|
|
2559
|
+
const pending = unconfirmed ? ` A request of ${plural(unconfirmed, "operation")} was sent but its receipt could not be confirmed; it may have been applied.` : "";
|
|
2560
|
+
return new AdportError11("PROVIDER_ERROR", `google: negative keyword change stopped after ${acknowledged.length} of ${total} confirmed operations.${pending} ${guidance} Each request is atomic; earlier batches remain applied.`, { resourceIds: acknowledged, ...unconfirmed ? { unconfirmed_operations: unconfirmed } : {}, ...details, cause: error instanceof Error ? error.message : String(error) });
|
|
2561
|
+
}
|
|
2562
|
+
review(account2, kind, title, subject, fields5, notices) {
|
|
2563
|
+
return { provider: "google", accountId: account2, kind, title, subject, fields: fields5, notices };
|
|
2564
|
+
}
|
|
2565
|
+
async planCreate(account2, input2) {
|
|
2566
|
+
const { unique: unique3, duplicates } = dedupeKeywords(input2.keywords);
|
|
2567
|
+
const lists = await this.readLists(account2), name5 = input2.name.toLowerCase();
|
|
2568
|
+
if (lists.some((list2) => list2.name.toLowerCase() === name5)) throw new AdportError11("INVALID_INPUT", `google: an enabled negative keyword list named "${input2.name}" already exists; use google_update_negative_keyword_list`);
|
|
2569
|
+
const campaigns = input2.campaign_ids ? await this.campaigns(account2, input2.campaign_ids) : [];
|
|
2570
|
+
const temp = `customers/${account2}/sharedSets/-1`, chunkSize = NEGATIVE_KEYWORD_MUTATE_BATCH - 1;
|
|
2571
|
+
const criterion = (sharedSet, value) => ({ sharedSet, keyword: { text: value.text, matchType: value.match_type } });
|
|
2572
|
+
const requestCount = Math.ceil(unique3.length / chunkSize) + (campaigns.length ? 1 : 0);
|
|
2573
|
+
const notices = ["A negative keyword list only blocks matching searches once attached; it has no pause state. Attaching it to an enabled campaign affects delivery immediately. Budgets, bids and statuses are unchanged.", `Keywords are deduplicated by text and match type, ignoring case. Applied in ${plural(requestCount, "atomic request")} of at most ${NEGATIVE_KEYWORD_MUTATE_BATCH} operations; campaigns are attached only after every keyword is added.`];
|
|
2574
|
+
const fields5 = [{ label: "List name", after: input2.name }, { label: `Negative keywords (${unique3.length})`, after: sample(unique3) }];
|
|
2575
|
+
if (duplicates.length) fields5.push({ label: `Skipped duplicates (${duplicates.length})`, after: sample(duplicates) });
|
|
2576
|
+
if (campaigns.length) fields5.push({ label: `Attach to campaigns (${campaigns.length})`, after: campaigns.map((value) => `${value.name} (${value.id}, ${value.status})`) });
|
|
2577
|
+
let details;
|
|
2578
|
+
return {
|
|
2579
|
+
summary: `Create Google negative keyword list \u201C${input2.name}\u201D with ${plural(unique3.length, "keyword")}${campaigns.length ? ` and attach it to ${plural(campaigns.length, "campaign")}` : ""}`,
|
|
2580
|
+
changes: [`+ shared_set NEGATIVE_KEYWORDS "${input2.name}"`, `+ ${plural(unique3.length, "negative keyword")}: ${sample(unique3).join(", ")}`, ...duplicates.length ? [`skipped ${plural(duplicates.length, "duplicate")}: ${sample(duplicates).join(", ")}`] : [], ...campaigns.map((value) => `+ attach to campaign "${value.name}" (${value.id})`)],
|
|
2581
|
+
fieldChanges: [{ field: "Negative keyword list", before: "(new)", after: input2.name }, { field: "Keywords", before: "0", after: String(unique3.length) }, ...campaigns.length ? [{ field: "Attached campaigns", before: "0", after: String(campaigns.length) }] : []],
|
|
2582
|
+
notes: notices,
|
|
2583
|
+
coercions: [],
|
|
2584
|
+
budgetDeltas: [],
|
|
2585
|
+
review: this.review(account2, "create", "Create negative keyword list", input2.name, fields5, notices),
|
|
2586
|
+
resultDetails: () => details,
|
|
2587
|
+
execute: async (validateOnly) => {
|
|
2588
|
+
const keywordChunks = chunks2(unique3, chunkSize), acknowledged = [];
|
|
2589
|
+
if (validateOnly) {
|
|
2590
|
+
const create3 = { sharedSetOperation: { create: { resourceName: temp, name: input2.name, type: "NEGATIVE_KEYWORDS" } } };
|
|
2591
|
+
for (const batch of keywordChunks) await this.client.googleAdsMutate(account2, [create3, ...batch.map((value) => ({ sharedCriterionOperation: { create: criterion(temp, value) } }))], { validateOnly: true });
|
|
2592
|
+
if (campaigns.length) await this.client.googleAdsMutate(account2, [create3, ...campaigns.map((value) => ({ campaignSharedSetOperation: { create: { campaign: value.resourceName, sharedSet: temp } } }))], { validateOnly: true });
|
|
2593
|
+
return [];
|
|
2594
|
+
}
|
|
2595
|
+
let list2, listId;
|
|
2596
|
+
try {
|
|
2597
|
+
const [first, ...rest] = keywordChunks;
|
|
2598
|
+
const result2 = await confirmBatch(this.client.googleAdsMutate(account2, [{ sharedSetOperation: { create: { resourceName: temp, name: input2.name, type: "NEGATIVE_KEYWORDS" } } }, ...first.map((value) => ({ sharedCriterionOperation: { create: criterion(temp, value) } }))], { validateOnly: false }), first.length + 1);
|
|
2599
|
+
const responses = result2.mutateOperationResponses ?? [];
|
|
2600
|
+
list2 = responses[0]?.sharedSetResult?.resourceName;
|
|
2601
|
+
listId = list2?.match(new RegExp(`^customers/${account2}/sharedSets/([1-9]\\d*)$`))?.[1];
|
|
2602
|
+
if (!listId) throw new UnconfirmedBatch(first.length + 1);
|
|
2603
|
+
acknowledged.push(list2);
|
|
2604
|
+
const criterionPattern = new RegExp(`^customers/${account2}/sharedCriteria/${listId}~[1-9]\\d*$`);
|
|
2605
|
+
if (responses.length !== first.length + 1 || responses.slice(1).some((value) => !criterionPattern.test(value.sharedCriterionResult?.resourceName ?? ""))) throw new UnconfirmedBatch(first.length);
|
|
2606
|
+
acknowledged.push(...responses.slice(1).map((value) => value.sharedCriterionResult.resourceName));
|
|
2607
|
+
await this.batches(account2, "sharedCriteria", rest.flat().map((value) => ({ create: criterion(list2, value) })), false, (_, resource) => criterionPattern.test(resource), acknowledged);
|
|
2608
|
+
await this.batches(account2, "campaignSharedSets", campaigns.map((value) => ({ create: { campaign: value.resourceName, sharedSet: list2 } })), false, (operation, resource) => resource === `${String(object6(operation.create).campaign).replace("/campaigns/", "/campaignSharedSets/")}~${listId}`, acknowledged);
|
|
2609
|
+
} catch (error) {
|
|
2610
|
+
throw this.outcome(error, acknowledged, 1 + unique3.length + campaigns.length, listId ? `List ${listId} exists; finish with google_update_negative_keyword_list (already present keywords are skipped) and google_link_negative_keyword_list (attach) instead of creating it again.` : "Reconcile with google_negative_keyword_lists before retrying.", listId ? { shared_set_id: listId } : {});
|
|
2611
|
+
}
|
|
2612
|
+
details = { shared_set_id: listId, keywords_added: unique3.length, skipped_duplicates: duplicates.length, campaigns_attached: campaigns.map((value) => value.id) };
|
|
2613
|
+
return acknowledged;
|
|
2614
|
+
}
|
|
2615
|
+
};
|
|
2616
|
+
}
|
|
2617
|
+
async planUpdate(account2, input2) {
|
|
2618
|
+
const list2 = await this.list(account2, input2.shared_set_id), existing = await this.criteria(account2, list2.id);
|
|
2619
|
+
const add = dedupeKeywords(input2.add_keywords ?? []), remove2 = dedupeKeywords(input2.remove_keywords ?? []);
|
|
2620
|
+
const removeKeys = new Set(remove2.unique.map(keyOf));
|
|
2621
|
+
if (add.unique.some((value) => removeKeys.has(keyOf(value)))) throw new AdportError11("INVALID_INPUT", "google: the same keyword cannot be both added and removed");
|
|
2622
|
+
const current = new Map(existing.map((value) => [keyOf(value), value]));
|
|
2623
|
+
const additions = add.unique.filter((value) => !current.has(keyOf(value))), alreadyPresent = add.unique.filter((value) => current.has(keyOf(value)));
|
|
2624
|
+
const removals = remove2.unique.flatMap((value) => current.has(keyOf(value)) ? [current.get(keyOf(value))] : []), notFound = remove2.unique.filter((value) => !current.has(keyOf(value)));
|
|
2625
|
+
if (!additions.length && !removals.length) throw new AdportError11("INVALID_INPUT", `google: nothing to change; ${alreadyPresent.length} keyword(s) already in the list and ${notFound.length} removal(s) not found`);
|
|
2626
|
+
if (existing.length + additions.length > LIST_LIMIT) throw new AdportError11("INVALID_INPUT", `google: a negative keyword list holds at most ${LIST_LIMIT} keywords (${existing.length} present, ${additions.length} new). Remove keywords in a separate call first.`);
|
|
2627
|
+
const operations = [...additions.map((value) => ({ create: { sharedSet: list2.resource_name, keyword: { text: value.text, matchType: value.match_type } } })), ...removals.map((value) => ({ remove: value.resourceName }))];
|
|
2628
|
+
const pattern = new RegExp(`^customers/${account2}/sharedCriteria/${list2.id}~[1-9]\\d*$`);
|
|
2629
|
+
const notices = [`Changes apply to every campaign using this list (${plural(list2.reference_count, "campaign")}) and affect their delivery immediately. Budgets, bids and statuses are unchanged.`, `Additions run before removals, in ${plural(Math.ceil(operations.length / NEGATIVE_KEYWORD_MUTATE_BATCH), "atomic request")} of at most ${NEGATIVE_KEYWORD_MUTATE_BATCH} operations. Matching ignores case.`];
|
|
2630
|
+
const fields5 = [{ label: "List", after: `${list2.name} (${list2.id})` }, { label: "Keywords", before: existing.length, after: existing.length + additions.length - removals.length }];
|
|
2631
|
+
if (additions.length) fields5.push({ label: `Add (${additions.length})`, after: sample(additions) });
|
|
2632
|
+
if (removals.length) fields5.push({ label: `Remove (${removals.length})`, after: sample(removals) });
|
|
2633
|
+
if (alreadyPresent.length) fields5.push({ label: `Skipped, already in list (${alreadyPresent.length})`, after: sample(alreadyPresent) });
|
|
2634
|
+
if (add.duplicates.length + remove2.duplicates.length) fields5.push({ label: `Skipped duplicates (${add.duplicates.length + remove2.duplicates.length})`, after: sample([...add.duplicates, ...remove2.duplicates]) });
|
|
2635
|
+
if (notFound.length) fields5.push({ label: `Skipped, not in list (${notFound.length})`, after: sample(notFound) });
|
|
2636
|
+
let details;
|
|
2637
|
+
return {
|
|
2638
|
+
summary: `Update Google negative keyword list \u201C${list2.name}\u201D: +${additions.length} / \u2212${removals.length} keywords`,
|
|
2639
|
+
changes: [...additions.length ? [`+ ${plural(additions.length, "negative keyword")}: ${sample(additions).join(", ")}`] : [], ...removals.length ? [`- ${plural(removals.length, "negative keyword")}: ${sample(removals).join(", ")}`] : [], ...alreadyPresent.length ? [`skipped ${alreadyPresent.length} already present: ${sample(alreadyPresent).join(", ")}`] : [], ...notFound.length ? [`skipped ${notFound.length} not found: ${sample(notFound).join(", ")}`] : []],
|
|
2640
|
+
fieldChanges: [{ field: "Keywords", before: String(existing.length), after: String(existing.length + additions.length - removals.length) }],
|
|
2641
|
+
notes: notices,
|
|
2642
|
+
coercions: [],
|
|
2643
|
+
budgetDeltas: [],
|
|
2644
|
+
review: this.review(account2, "update", "Update negative keyword list", list2.name, fields5, notices),
|
|
2645
|
+
resultDetails: () => details,
|
|
2646
|
+
execute: async (validateOnly) => {
|
|
2647
|
+
const acknowledged = [];
|
|
2648
|
+
try {
|
|
2649
|
+
await this.batches(account2, "sharedCriteria", operations, validateOnly, (operation, resource) => operation.remove ? resource === operation.remove : pattern.test(resource), acknowledged);
|
|
2650
|
+
} catch (error) {
|
|
2651
|
+
if (validateOnly) throw error;
|
|
2652
|
+
throw this.outcome(error, acknowledged, operations.length, "Read google_negative_keyword_lists with shared_set_id and re-run the same request; keywords already present are skipped.");
|
|
2653
|
+
}
|
|
2654
|
+
details = { shared_set_id: list2.id, added: additions.length, removed: removals.length, skipped_already_present: alreadyPresent.length, skipped_duplicates: add.duplicates.length + remove2.duplicates.length, skipped_not_found: notFound.length };
|
|
2655
|
+
return acknowledged;
|
|
2656
|
+
}
|
|
2657
|
+
};
|
|
2658
|
+
}
|
|
2659
|
+
async planLink(account2, input2, linking) {
|
|
2660
|
+
const list2 = await this.list(account2, input2.shared_set_id), campaigns = await this.campaigns(account2, input2.campaign_ids);
|
|
2661
|
+
const links = await this.links(account2, [list2.resource_name]), linked = new Map(links.map((link) => [link.campaign.id, link.resource_name]));
|
|
2662
|
+
const targets = campaigns.filter((value) => linking !== linked.has(value.id)), skipped = campaigns.filter((value) => linking === linked.has(value.id));
|
|
2663
|
+
if (!targets.length) throw new AdportError11("INVALID_INPUT", `google: every campaign is already ${linking ? "attached to" : "detached from"} this list`);
|
|
2664
|
+
const operations = targets.map((value) => linking ? { create: { campaign: value.resourceName, sharedSet: list2.resource_name } } : { remove: linked.get(value.id) });
|
|
2665
|
+
const verb = linking ? "Attach" : "Detach", describe = (value) => `${value.name} (${value.id}, ${value.status})`;
|
|
2666
|
+
const notices = [linking ? `The list's ${plural(list2.member_count, "keyword")} start blocking matching searches in these campaigns immediately when they are enabled.` : "Searches previously blocked by this list can start matching these campaigns immediately when they are enabled. The list and its keywords are preserved.", "Budgets, bids and statuses are unchanged."];
|
|
2667
|
+
const fields5 = [{ label: "List", after: `${list2.name} (${list2.id}, ${plural(list2.member_count, "keyword")})` }, { label: `${verb} campaigns (${targets.length})`, after: targets.map(describe) }];
|
|
2668
|
+
if (skipped.length) fields5.push({ label: `Skipped, already ${linking ? "attached" : "detached"} (${skipped.length})`, after: skipped.map(describe) });
|
|
2669
|
+
let details;
|
|
2670
|
+
return {
|
|
2671
|
+
summary: `${verb} Google negative keyword list \u201C${list2.name}\u201D ${linking ? "to" : "from"} ${plural(targets.length, "campaign")}`,
|
|
2672
|
+
changes: [...targets.map((value) => `${linking ? "+" : "-"} campaign "${value.name}" (${value.id}) ${linking ? "\u2190" : "\u219B"} list "${list2.name}"`), ...skipped.length ? [`skipped ${skipped.length} already ${linking ? "attached" : "detached"}`] : []],
|
|
2673
|
+
fieldChanges: [{ field: "Attached campaigns", before: String(links.length), after: String(links.length + (linking ? targets.length : -targets.length)) }],
|
|
2674
|
+
notes: notices,
|
|
2675
|
+
coercions: [],
|
|
2676
|
+
budgetDeltas: [],
|
|
2677
|
+
review: this.review(account2, linking ? "create" : "remove", `${verb} negative keyword list`, list2.name, fields5, notices),
|
|
2678
|
+
resultDetails: () => details,
|
|
2679
|
+
execute: async (validateOnly) => {
|
|
2680
|
+
const acknowledged = [];
|
|
2681
|
+
try {
|
|
2682
|
+
await this.batches(account2, "campaignSharedSets", operations, validateOnly, (operation, resource) => resource === (operation.remove ?? `${String(object6(operation.create).campaign).replace("/campaigns/", "/campaignSharedSets/")}~${list2.id}`), acknowledged);
|
|
2683
|
+
} catch (error) {
|
|
2684
|
+
if (validateOnly) throw error;
|
|
2685
|
+
throw this.outcome(error, acknowledged, operations.length, "Read google_negative_keyword_lists with shared_set_id and re-run the same request; finished campaigns are skipped.");
|
|
2686
|
+
}
|
|
2687
|
+
details = { shared_set_id: list2.id, campaigns: targets.map((value) => value.id), skipped: skipped.map((value) => value.id) };
|
|
2688
|
+
return acknowledged;
|
|
2689
|
+
}
|
|
2690
|
+
};
|
|
2691
|
+
}
|
|
2692
|
+
async planCampaignNegatives(account2, input2) {
|
|
2693
|
+
const { unique: unique3, duplicates } = dedupeKeywords(input2.keywords), campaigns = await this.campaigns(account2, input2.campaign_ids);
|
|
2694
|
+
const inventories = await mapBounded(campaigns, INVENTORY_CONCURRENCY, (campaign) => this.campaignNegatives(account2, campaign));
|
|
2695
|
+
const perCampaign = campaigns.map((campaign, index) => {
|
|
2696
|
+
const existing = new Set(inventories[index].map(keyOf));
|
|
2697
|
+
const additions = unique3.filter((value) => !existing.has(keyOf(value))), present = unique3.filter((value) => existing.has(keyOf(value)));
|
|
2698
|
+
if (existing.size + additions.length > CAMPAIGN_LIMIT) throw new AdportError11("INVALID_INPUT", `google: campaign ${campaign.id} would exceed ${CAMPAIGN_LIMIT} negative keywords; consider a negative keyword list`);
|
|
2699
|
+
return { campaign, additions, present };
|
|
2700
|
+
});
|
|
2701
|
+
const count2 = perCampaign.reduce((sum, campaign) => sum + campaign.additions.length, 0);
|
|
2702
|
+
if (!count2) throw new AdportError11("INVALID_INPUT", "google: every keyword is already a negative keyword in every selected campaign");
|
|
2703
|
+
if (count2 > OPERATION_BOUND) throw new AdportError11("INVALID_INPUT", `google: ${count2} operations exceed the ${OPERATION_BOUND} per-call bound; split campaigns across calls or use a negative keyword list`);
|
|
2704
|
+
const operations = perCampaign.flatMap(({ campaign, additions }) => additions.map((value) => ({ create: { campaign: campaign.resourceName, negative: true, keyword: { text: value.text, matchType: value.match_type } } })));
|
|
2705
|
+
const notices = ["Campaign-level negative keywords block matching searches immediately in enabled campaigns. Budgets, bids and statuses are unchanged. For keywords shared by many campaigns, a negative keyword list is easier to maintain.", `Keywords are deduplicated by text and match type, ignoring case. Applied in ${plural(Math.ceil(operations.length / CAMPAIGN_MUTATE_BATCH), "atomic request")} of at most ${CAMPAIGN_MUTATE_BATCH} operations.`];
|
|
2706
|
+
const fields5 = perCampaign.map(({ campaign, additions, present }) => ({ label: `${campaign.name} (${campaign.id}): +${additions.length}${present.length ? `, ${present.length} already present` : ""}`, after: additions.length ? sample(additions) : "No change" }));
|
|
2707
|
+
fields5.unshift({ label: "Negative keywords to add", after: `${operations.length} across ${plural(perCampaign.filter((value) => value.additions.length).length, "campaign")}` });
|
|
2708
|
+
if (duplicates.length) fields5.push({ label: `Skipped duplicates (${duplicates.length})`, after: sample(duplicates) });
|
|
2709
|
+
const pattern = new RegExp(`^customers/${account2}/campaignCriteria/([1-9]\\d*)~[1-9]\\d*$`);
|
|
2710
|
+
let details;
|
|
2711
|
+
return {
|
|
2712
|
+
summary: `Add ${plural(operations.length, "campaign negative keyword")} to ${plural(perCampaign.filter((value) => value.additions.length).length, "Google campaign")}`,
|
|
2713
|
+
changes: [...perCampaign.map(({ campaign, additions, present }) => `+ campaign "${campaign.name}" (${campaign.id}): ${additions.length ? sample(additions).join(", ") : "no change"}${present.length ? ` (skipped ${present.length} already present)` : ""}`), ...duplicates.length ? [`skipped ${plural(duplicates.length, "duplicate")}: ${sample(duplicates).join(", ")}`] : []],
|
|
2714
|
+
fieldChanges: perCampaign.map(({ campaign, additions, present }) => ({ field: `${campaign.name} negative keywords`, before: `${present.length} of ${unique3.length} present`, after: `+${additions.length}` })),
|
|
2715
|
+
notes: notices,
|
|
2716
|
+
coercions: [],
|
|
2717
|
+
budgetDeltas: [],
|
|
2718
|
+
review: this.review(account2, "create", "Add campaign negative keywords", `${plural(campaigns.length, "campaign")}`, fields5, notices),
|
|
2719
|
+
resultDetails: () => details,
|
|
2720
|
+
execute: async (validateOnly) => {
|
|
2721
|
+
const acknowledged = [];
|
|
2722
|
+
try {
|
|
2723
|
+
await this.batches(account2, "campaignCriteria", operations, validateOnly, (operation, resource) => resource.match(pattern)?.[1] === String(object6(operation.create).campaign).split("/").at(-1), acknowledged, CAMPAIGN_MUTATE_BATCH);
|
|
2724
|
+
} catch (error) {
|
|
2725
|
+
if (validateOnly) throw error;
|
|
2726
|
+
throw this.outcome(error, acknowledged, operations.length, "Re-run the same request; negative keywords already present are skipped.");
|
|
2727
|
+
}
|
|
2728
|
+
details = { added: operations.length, campaigns: perCampaign.map(({ campaign, additions, present }) => ({ campaign_id: campaign.id, added: additions.length, skipped_already_present: present.length })), skipped_duplicates: duplicates.length };
|
|
2729
|
+
return acknowledged;
|
|
2730
|
+
}
|
|
2731
|
+
};
|
|
2732
|
+
}
|
|
2733
|
+
};
|
|
2734
|
+
function googleNegativeKeywordTools(provider) {
|
|
2735
|
+
const write = (name5, description, payload, kind) => guardedWriteTool10({ name: name5, namespace: "google", provider: "google", description, payload, kind });
|
|
2736
|
+
const campaign = z11.object({ id: z11.string(), name: z11.string(), status: z11.string() });
|
|
2737
|
+
const listKeyword = z11.object({ criterion_id: z11.string(), text: z11.string(), match_type: z11.string() });
|
|
2738
|
+
const list2 = z11.object({ id: z11.string(), name: z11.string(), member_count: z11.number(), reference_count: z11.number(), campaigns: z11.array(campaign), keywords: z11.array(listKeyword).optional(), truncated: z11.boolean().optional() });
|
|
2739
|
+
return [
|
|
2740
|
+
defineTool10({ name: "google_negative_keyword_lists", namespace: "google", description: "Read enabled negative keyword lists with counts and attached campaigns. With shared_set_id, read that list only, including up to limit keywords.", input: z11.object({ account_id: z11.string(), shared_set_id: id9.optional(), limit: z11.number().int().positive().max(LIST_LIMIT).optional() }), output: z11.object({ lists: z11.array(list2) }), annotations: { readOnly: true }, handler: (input2) => provider.negativeKeywords.listLists(input2) }),
|
|
2741
|
+
write("google_create_negative_keyword_list", "Create a negative keyword list (up to 5,000 keywords), optionally attached to campaigns.", createList, "create"),
|
|
2742
|
+
write("google_update_negative_keyword_list", "Add or remove keywords in a negative keyword list. Affects every attached campaign.", updateList, "update"),
|
|
2743
|
+
// One tool for both directions, like other grant/revoke writes: kind is update.
|
|
2744
|
+
write("google_link_negative_keyword_list", "Attach or detach a negative keyword list for one or many campaigns. Detaching keeps the list.", linkList, "update"),
|
|
2745
|
+
write("google_add_campaign_negative_keywords", "Add the same campaign-level negative keywords to one or many campaigns.", campaignNegatives, "create")
|
|
2746
|
+
];
|
|
2747
|
+
}
|
|
2748
|
+
|
|
2749
|
+
// src/keywords.ts
|
|
2750
|
+
import { AdportError as AdportError12, guardedWriteTool as guardedWriteTool11 } from "@adport/core";
|
|
2751
|
+
import { z as z12 } from "zod";
|
|
2752
|
+
var id10 = z12.string().regex(/^[1-9]\d*$/);
|
|
2753
|
+
var landingUrl = z12.string().url().refine((value) => {
|
|
2754
|
+
try {
|
|
2755
|
+
const parsed = new URL(value);
|
|
2756
|
+
return ["https:", "http:"].includes(parsed.protocol) && !parsed.username && !parsed.password;
|
|
2757
|
+
} catch {
|
|
2758
|
+
return false;
|
|
2759
|
+
}
|
|
2760
|
+
}, "Use an http(s) URL without credentials");
|
|
2761
|
+
var urlList = z12.array(landingUrl);
|
|
2762
|
+
var keywordUrlFields = {
|
|
2763
|
+
final_urls: urlList.optional(),
|
|
2764
|
+
final_mobile_urls: urlList.optional(),
|
|
2765
|
+
tracking_url_template: z12.string().min(1).optional(),
|
|
2766
|
+
final_url_suffix: z12.string().min(1).optional()
|
|
2767
|
+
};
|
|
2768
|
+
var URL_KEYS = ["final_urls", "final_mobile_urls", "tracking_url_template", "final_url_suffix"];
|
|
2769
|
+
var WIRE = { final_urls: "finalUrls", final_mobile_urls: "finalMobileUrls", tracking_url_template: "trackingUrlTemplate", final_url_suffix: "finalUrlSuffix" };
|
|
2770
|
+
var MAX_UPDATES = 1e3;
|
|
2771
|
+
var LOOKUP_CHUNK = 200;
|
|
2772
|
+
var urlUpdate = z12.object({
|
|
2773
|
+
ad_group_id: id10,
|
|
2774
|
+
criterion_id: id10,
|
|
2775
|
+
final_urls: urlList.optional(),
|
|
2776
|
+
final_mobile_urls: urlList.optional(),
|
|
2777
|
+
tracking_url_template: z12.string().min(1).nullable().optional(),
|
|
2778
|
+
final_url_suffix: z12.string().min(1).nullable().optional()
|
|
2779
|
+
}).refine((value) => URL_KEYS.some((key2) => value[key2] !== void 0), "Supply at least one URL field per keyword");
|
|
2780
|
+
var updatePayload = z12.object({ keywords: z12.array(urlUpdate).min(1).max(MAX_UPDATES) }).refine((value) => new Set(value.keywords.map((k) => `${k.ad_group_id}~${k.criterion_id}`)).size === value.keywords.length, "Each keyword may appear once");
|
|
2781
|
+
var keywordFields = ["resource_name", "criterion_id", "type", "status", "negative", "keyword.text", "keyword.match_type", ...URL_KEYS].map((field3) => `ad_group_criterion.${field3}`);
|
|
2782
|
+
var record4 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
2783
|
+
var show = (value) => Array.isArray(value) ? value.length ? value.join(", ") : "(none)" : typeof value === "string" && value ? value : "(none)";
|
|
2784
|
+
var GOOGLE_KEYWORD_WRITES = /* @__PURE__ */ new Set(["google_update_keyword_urls"]);
|
|
2785
|
+
function fieldMissingFinalUrls(fields5) {
|
|
2786
|
+
const populated = (value) => (typeof value === "string" || Array.isArray(value)) && value.length > 0;
|
|
2787
|
+
if (populated(fields5.final_urls)) return void 0;
|
|
2788
|
+
return URL_KEYS.find((key2) => key2 !== "final_urls" && populated(fields5[key2]));
|
|
2789
|
+
}
|
|
2790
|
+
function keywordUrlCreateFields(keyword2) {
|
|
2791
|
+
const missing = fieldMissingFinalUrls(keyword2);
|
|
2792
|
+
if (missing) throw new AdportError12("INVALID_INPUT", "google: " + missing + " requires final_urls on the same keyword");
|
|
2793
|
+
return Object.fromEntries(URL_KEYS.flatMap((key2) => keyword2[key2] !== void 0 && keyword2[key2].length ? [[WIRE[key2], keyword2[key2]]] : []));
|
|
2794
|
+
}
|
|
2795
|
+
var GoogleKeywordService = class {
|
|
2796
|
+
constructor(client) {
|
|
2797
|
+
this.client = client;
|
|
2798
|
+
}
|
|
2799
|
+
client;
|
|
2800
|
+
async plan(op) {
|
|
2801
|
+
const account2 = normalizeCustomerId(op.accountId), input2 = updatePayload.parse(op.payload);
|
|
2802
|
+
const resource = (k) => `customers/${account2}/adGroupCriteria/${k.ad_group_id}~${k.criterion_id}`;
|
|
2803
|
+
const wanted = input2.keywords.map(resource);
|
|
2804
|
+
const rows = [];
|
|
2805
|
+
for (let start = 0; start < wanted.length; start += LOOKUP_CHUNK) {
|
|
2806
|
+
const chunk = wanted.slice(start, start + LOOKUP_CHUNK);
|
|
2807
|
+
rows.push(...await this.client.search(account2, `SELECT ad_group.id, ${keywordFields.join(", ")} FROM ad_group_criterion WHERE ad_group_criterion.resource_name IN (${chunk.map((name5) => `'${name5}'`).join(", ")})`, { maxRows: chunk.length + 1, includeDrafts: true }));
|
|
2808
|
+
}
|
|
2809
|
+
const current = new Map(rows.map((row2) => {
|
|
2810
|
+
const criterion = record4(row2.adGroupCriterion);
|
|
2811
|
+
return [String(criterion.resourceName), criterion];
|
|
2812
|
+
}));
|
|
2813
|
+
const problems = [];
|
|
2814
|
+
const operations = [], changes = [], fieldChanges = [];
|
|
2815
|
+
for (const [index, keyword2] of input2.keywords.entries()) {
|
|
2816
|
+
const name5 = wanted[index], before = current.get(name5);
|
|
2817
|
+
if (!before || before.status === "REMOVED") {
|
|
2818
|
+
problems.push(`${keyword2.ad_group_id}~${keyword2.criterion_id} was not found in the selected account`);
|
|
2819
|
+
continue;
|
|
2820
|
+
}
|
|
2821
|
+
if (before.type !== "KEYWORD") {
|
|
2822
|
+
problems.push(`${keyword2.ad_group_id}~${keyword2.criterion_id} is not a keyword criterion`);
|
|
2823
|
+
continue;
|
|
2824
|
+
}
|
|
2825
|
+
if (before.negative === true) {
|
|
2826
|
+
problems.push(`${keyword2.ad_group_id}~${keyword2.criterion_id} is a negative keyword; negative keywords have no landing pages`);
|
|
2827
|
+
continue;
|
|
2828
|
+
}
|
|
2829
|
+
const update3 = { resourceName: name5 }, mask = [], info = record4(before.keyword), label = `"${String(info.text ?? "")}" [${String(info.matchType ?? "")}] ${keyword2.ad_group_id}~${keyword2.criterion_id}`;
|
|
2830
|
+
for (const key2 of URL_KEYS) {
|
|
2831
|
+
const value = keyword2[key2];
|
|
2832
|
+
if (value === void 0) continue;
|
|
2833
|
+
mask.push(key2);
|
|
2834
|
+
if (value !== null && !(Array.isArray(value) && value.length === 0)) update3[WIRE[key2]] = value;
|
|
2835
|
+
const after = value === null || Array.isArray(value) && !value.length ? "(cleared)" : show(value);
|
|
2836
|
+
changes.push(`~ keyword ${label} ${key2} ${show(before[WIRE[key2]])} \u2192 ${after}`);
|
|
2837
|
+
if (fieldChanges.length < 100) fieldChanges.push({ field: `${label} ${key2}`, before: show(before[WIRE[key2]]), after });
|
|
2838
|
+
}
|
|
2839
|
+
const effective = Object.fromEntries(URL_KEYS.map((key2) => [
|
|
2840
|
+
key2,
|
|
2841
|
+
keyword2[key2] === void 0 ? before[WIRE[key2]] : keyword2[key2]
|
|
2842
|
+
]));
|
|
2843
|
+
const missing = fieldMissingFinalUrls(effective);
|
|
2844
|
+
if (missing) problems.push(`${keyword2.ad_group_id}~${keyword2.criterion_id} would keep ${missing} without final_urls; supply a keyword landing page or clear that field`);
|
|
2845
|
+
operations.push({ update: update3, updateMask: mask.join(",") });
|
|
2846
|
+
}
|
|
2847
|
+
if (problems.length) throw new AdportError12("INVALID_INPUT", `google: keyword URL update rejected: ${problems.join("; ")}`);
|
|
2848
|
+
return {
|
|
2849
|
+
summary: `Update landing-page URLs on ${operations.length} keyword${operations.length === 1 ? "" : "s"}`,
|
|
2850
|
+
changes,
|
|
2851
|
+
fieldChanges,
|
|
2852
|
+
notes: ["Only the listed URL fields change; keyword text, match type, status and bids are preserved. Keyword URLs override ad final URLs for clicks on that keyword."],
|
|
2853
|
+
coercions: [],
|
|
2854
|
+
budgetDeltas: [],
|
|
2855
|
+
execute: async (validateOnly) => {
|
|
2856
|
+
const result2 = await this.client.mutate(account2, "adGroupCriteria", operations, { validateOnly });
|
|
2857
|
+
const resources = (result2.results ?? []).map((item) => item.resourceName ?? "");
|
|
2858
|
+
if (!validateOnly && (resources.length !== wanted.length || resources.some((name5, index) => name5 !== wanted[index]))) throw new AdportError12("PROVIDER_ERROR", "google: keyword URL mutation receipt mismatch; reconcile before retrying", { resource_ids: resources });
|
|
2859
|
+
return resources;
|
|
2860
|
+
}
|
|
2861
|
+
};
|
|
2862
|
+
}
|
|
2863
|
+
};
|
|
2864
|
+
function googleKeywordTools() {
|
|
2865
|
+
return [
|
|
2866
|
+
guardedWriteTool11({
|
|
2867
|
+
name: "google_update_keyword_urls",
|
|
2868
|
+
namespace: "google",
|
|
2869
|
+
provider: "google",
|
|
2870
|
+
kind: "update",
|
|
2871
|
+
description: "Set or clear landing-page URLs on existing keywords across ad groups. Omitted fields stay; [] or null clears.",
|
|
2872
|
+
payload: updatePayload
|
|
2873
|
+
})
|
|
2080
2874
|
];
|
|
2081
2875
|
}
|
|
2082
2876
|
|
|
@@ -2101,10 +2895,13 @@ var GoogleAdsProvider = class {
|
|
|
2101
2895
|
this.assetLinks = new GoogleAssetLinks(client, this.assets);
|
|
2102
2896
|
this.labels = new GoogleLabelService(client);
|
|
2103
2897
|
this.conversions = new GoogleConversionService(client);
|
|
2898
|
+
this.conversionGoals = new GoogleConversionGoalService(client, this.conversions);
|
|
2104
2899
|
this.dataManager = new GoogleDataManagerService(client, this.conversions);
|
|
2105
2900
|
this.experiments = new GoogleExperimentService(client);
|
|
2106
2901
|
this.performanceMax = new GooglePerformanceMaxService(client);
|
|
2107
2902
|
this.targeting = new GoogleTargetingService(client);
|
|
2903
|
+
this.negativeKeywords = new GoogleNegativeKeywordService(client);
|
|
2904
|
+
this.keywords = new GoogleKeywordService(client);
|
|
2108
2905
|
}
|
|
2109
2906
|
client;
|
|
2110
2907
|
id = "google";
|
|
@@ -2113,10 +2910,13 @@ var GoogleAdsProvider = class {
|
|
|
2113
2910
|
assetLinks;
|
|
2114
2911
|
labels;
|
|
2115
2912
|
conversions;
|
|
2913
|
+
conversionGoals;
|
|
2116
2914
|
dataManager;
|
|
2117
2915
|
experiments;
|
|
2118
2916
|
performanceMax;
|
|
2119
2917
|
targeting;
|
|
2918
|
+
negativeKeywords;
|
|
2919
|
+
keywords;
|
|
2120
2920
|
keywordPlanning(customerId, method, body) {
|
|
2121
2921
|
return this.client.keywordPlanning(customerId, method, body);
|
|
2122
2922
|
}
|
|
@@ -2139,9 +2939,9 @@ var GoogleAdsProvider = class {
|
|
|
2139
2939
|
creatives: rows.slice(0, input2.limit).map((row2) => {
|
|
2140
2940
|
const groupAd = row2.adGroupAd;
|
|
2141
2941
|
const ad = groupAd.ad;
|
|
2142
|
-
if (!ad?.id) throw new
|
|
2942
|
+
if (!ad?.id) throw new AdportError13("PROVIDER_ERROR", "google: ad response is missing its identifier");
|
|
2143
2943
|
const adGroupId = String(row2.adGroup?.id ?? "");
|
|
2144
|
-
if (!/^\d+$/.test(adGroupId)) throw new
|
|
2944
|
+
if (!/^\d+$/.test(adGroupId)) throw new AdportError13("PROVIDER_ERROR", "google: ad response is missing its ad-group identifier");
|
|
2145
2945
|
const headlines = textAssets(ad.responsiveSearchAd?.headlines);
|
|
2146
2946
|
return {
|
|
2147
2947
|
id: ad.id,
|
|
@@ -2196,24 +2996,24 @@ var GoogleAdsProvider = class {
|
|
|
2196
2996
|
const directlyAccessible = new Set(ids2);
|
|
2197
2997
|
const accounts = /* @__PURE__ */ new Map();
|
|
2198
2998
|
const managers = [];
|
|
2199
|
-
for (const
|
|
2999
|
+
for (const id11 of ids2) {
|
|
2200
3000
|
try {
|
|
2201
3001
|
const rows = await this.client.search(
|
|
2202
|
-
|
|
3002
|
+
id11,
|
|
2203
3003
|
"SELECT customer.id, customer.descriptive_name, customer.currency_code, customer.status, customer.manager FROM customer LIMIT 1",
|
|
2204
|
-
{ maxRows: 1, loginCustomerId:
|
|
3004
|
+
{ maxRows: 1, loginCustomerId: id11 }
|
|
2205
3005
|
);
|
|
2206
3006
|
const customer = rows[0]?.customer ?? {};
|
|
2207
|
-
if (customer.manager) managers.push(
|
|
2208
|
-
else accounts.set(
|
|
3007
|
+
if (customer.manager) managers.push(id11);
|
|
3008
|
+
else accounts.set(id11, {
|
|
2209
3009
|
provider: this.id,
|
|
2210
|
-
id:
|
|
2211
|
-
name: customer.descriptiveName ?? `(account ${
|
|
3010
|
+
id: id11,
|
|
3011
|
+
name: customer.descriptiveName ?? `(account ${id11})`,
|
|
2212
3012
|
currency: customer.currencyCode,
|
|
2213
3013
|
status: customer.status
|
|
2214
3014
|
});
|
|
2215
3015
|
} catch {
|
|
2216
|
-
accounts.set(
|
|
3016
|
+
accounts.set(id11, { provider: this.id, id: id11, name: "(details unavailable)", status: "UNKNOWN" });
|
|
2217
3017
|
}
|
|
2218
3018
|
}
|
|
2219
3019
|
for (const rootManagerId of managers) {
|
|
@@ -2372,10 +3172,13 @@ var GoogleAdsProvider = class {
|
|
|
2372
3172
|
if (GOOGLE_ASSET_LINK_WRITES.has(op.tool)) return this.assetLinks.plan(op, guard);
|
|
2373
3173
|
if (GOOGLE_LABEL_WRITES.has(op.tool)) return this.labels.plan(op);
|
|
2374
3174
|
if (GOOGLE_CONVERSION_WRITES.has(op.tool)) return this.conversions.plan(op);
|
|
3175
|
+
if (GOOGLE_CONVERSION_GOAL_WRITES.has(op.tool)) return this.conversionGoals.plan(op);
|
|
2375
3176
|
if (op.tool === "google_ingest_conversion_events") return this.dataManager.plan(op);
|
|
2376
3177
|
if (GOOGLE_EXPERIMENT_WRITES.has(op.tool)) return this.experiments.plan(op, guard);
|
|
2377
3178
|
if (GOOGLE_PMAX_WRITES.has(op.tool)) return this.performanceMax.plan(op, guard);
|
|
2378
3179
|
if (op.tool === "google_update_targeting") return this.targeting.plan(op);
|
|
3180
|
+
if (GOOGLE_NEGATIVE_KEYWORD_WRITES.has(op.tool)) return this.negativeKeywords.plan(op);
|
|
3181
|
+
if (GOOGLE_KEYWORD_WRITES.has(op.tool)) return this.keywords.plan(op);
|
|
2379
3182
|
const cid = normalizeCustomerId(op.accountId);
|
|
2380
3183
|
const payload = op.payload;
|
|
2381
3184
|
switch (op.tool) {
|
|
@@ -2412,7 +3215,7 @@ var GoogleAdsProvider = class {
|
|
|
2412
3215
|
case "google_api_remove":
|
|
2413
3216
|
return this.planApiRemove(cid, payload);
|
|
2414
3217
|
default:
|
|
2415
|
-
throw new
|
|
3218
|
+
throw new AdportError13("PROVIDER_ERROR", `google: unsupported write tool ${op.tool}`);
|
|
2416
3219
|
}
|
|
2417
3220
|
}
|
|
2418
3221
|
async planApiCreate(cid, payload, guard) {
|
|
@@ -2444,7 +3247,7 @@ var GoogleAdsProvider = class {
|
|
|
2444
3247
|
async planApiUpdate(cid, payload) {
|
|
2445
3248
|
const service = validateGoogleService(payload.service);
|
|
2446
3249
|
if (service === "campaignBudgets" || payload.updates.some((item) => /budget/i.test(item.update_mask))) {
|
|
2447
|
-
throw new
|
|
3250
|
+
throw new AdportError13(
|
|
2448
3251
|
"INVALID_INPUT",
|
|
2449
3252
|
"google: budget updates require google_set_budget so the current and proposed values can be policy-checked"
|
|
2450
3253
|
);
|
|
@@ -2485,10 +3288,10 @@ var GoogleAdsProvider = class {
|
|
|
2485
3288
|
coercions.push("status coerced to PAUSED by policy (paused_creation)");
|
|
2486
3289
|
}
|
|
2487
3290
|
const channelType = payload.channel_type ?? "SEARCH";
|
|
2488
|
-
if (channelType === "SEARCH" && payload.language_ids?.length) throw new
|
|
2489
|
-
if (channelType === "PERFORMANCE_MAX") throw new
|
|
3291
|
+
if (channelType === "SEARCH" && payload.language_ids?.length) throw new AdportError13("INVALID_INPUT", "google: Search no longer supports manual language criteria. Omit language_ids; matching uses creative/landing-page language and user preferences. Existing legacy language criteria can only be removed.");
|
|
3292
|
+
if (channelType === "PERFORMANCE_MAX") throw new AdportError13("INVALID_INPUT", "google: use google_create_performance_max_campaign to create the complete campaign, brand assets and asset-group hierarchy atomically");
|
|
2490
3293
|
if (channelType !== "SEARCH" && (payload.search_partners !== void 0 || payload.display_expansion !== void 0)) {
|
|
2491
|
-
throw new
|
|
3294
|
+
throw new AdportError13("INVALID_INPUT", "search_partners and display_expansion require a SEARCH campaign");
|
|
2492
3295
|
}
|
|
2493
3296
|
const strategy = payload.bidding_strategy ?? "MANUAL_CPC";
|
|
2494
3297
|
const strategyField = { MANUAL_CPC: "manualCpc", MAXIMIZE_CLICKS: "targetSpend", MAXIMIZE_CONVERSIONS: "maximizeConversions", MAXIMIZE_CONVERSION_VALUE: "maximizeConversionValue" }[strategy];
|
|
@@ -2648,18 +3451,23 @@ var GoogleAdsProvider = class {
|
|
|
2648
3451
|
};
|
|
2649
3452
|
}
|
|
2650
3453
|
async planAddKeywords(cid, payload) {
|
|
2651
|
-
const
|
|
3454
|
+
const urls2 = payload.keywords.map(keywordUrlCreateFields);
|
|
3455
|
+
if (payload.negative && urls2.some((fields5) => Object.keys(fields5).length)) {
|
|
3456
|
+
throw new AdportError13("INVALID_INPUT", "google: negative keywords cannot have final URLs, tracking templates or URL suffixes");
|
|
3457
|
+
}
|
|
3458
|
+
const operations = payload.keywords.map((kw, index) => ({
|
|
2652
3459
|
create: {
|
|
2653
3460
|
adGroup: `customers/${cid}/adGroups/${payload.ad_group_id}`,
|
|
2654
3461
|
status: "ENABLED",
|
|
2655
3462
|
negative: payload.negative ?? false,
|
|
2656
|
-
keyword: { text: kw.text, matchType: kw.match_type }
|
|
3463
|
+
keyword: { text: kw.text, matchType: kw.match_type },
|
|
3464
|
+
...urls2[index]
|
|
2657
3465
|
}
|
|
2658
3466
|
}));
|
|
2659
3467
|
const kind = payload.negative ? "negative keywords" : "keywords";
|
|
2660
3468
|
return {
|
|
2661
3469
|
summary: `Add ${payload.keywords.length} ${kind} to ad group ${payload.ad_group_id}`,
|
|
2662
|
-
changes: payload.keywords.map((kw) => `+ ${payload.negative ? "negative " : ""}keyword [${kw.match_type}] "${kw.text}"`),
|
|
3470
|
+
changes: payload.keywords.map((kw) => `+ ${payload.negative ? "negative " : ""}keyword [${kw.match_type}] "${kw.text}"${kw.final_urls?.length ? ` \u2192 ${kw.final_urls.join(", ")}` : ""}${kw.final_mobile_urls?.length ? ` (mobile ${kw.final_mobile_urls.join(", ")})` : ""}${kw.tracking_url_template ? ` tracking ${kw.tracking_url_template}` : ""}${kw.final_url_suffix ? ` suffix ${kw.final_url_suffix}` : ""}`),
|
|
2663
3471
|
coercions: [],
|
|
2664
3472
|
budgetDeltas: [],
|
|
2665
3473
|
execute: async (validateOnly) => {
|
|
@@ -2688,7 +3496,7 @@ var GoogleAdsProvider = class {
|
|
|
2688
3496
|
}
|
|
2689
3497
|
async planRemoveKeywords(cid, payload) {
|
|
2690
3498
|
const resourceNames = payload.criterion_ids.map(
|
|
2691
|
-
(
|
|
3499
|
+
(id11) => `customers/${cid}/adGroupCriteria/${payload.ad_group_id}~${id11}`
|
|
2692
3500
|
);
|
|
2693
3501
|
return {
|
|
2694
3502
|
summary: `PERMANENTLY remove ${resourceNames.length} keyword criteria from ad group ${payload.ad_group_id}`,
|
|
@@ -2715,7 +3523,7 @@ var GoogleAdsProvider = class {
|
|
|
2715
3523
|
);
|
|
2716
3524
|
const current = rows[0]?.adGroupAd;
|
|
2717
3525
|
if (rows.length !== 1 || current?.resourceName !== resourceName || current.status === "REMOVED") {
|
|
2718
|
-
throw new
|
|
3526
|
+
throw new AdportError13("INVALID_INPUT", "google: ad was not found in the selected account and ad group, or has been removed");
|
|
2719
3527
|
}
|
|
2720
3528
|
return {
|
|
2721
3529
|
summary: `Set ad ${payload.ad_id} status ${current.status ?? "unknown"} \u2192 ${payload.status}`,
|
|
@@ -2738,7 +3546,7 @@ var GoogleAdsProvider = class {
|
|
|
2738
3546
|
);
|
|
2739
3547
|
const groupAd = rows[0]?.adGroupAd;
|
|
2740
3548
|
if (rows.length !== 1 || groupAd?.resourceName !== `customers/${cid}/adGroupAds/${payload.ad_group_id}~${payload.ad_id}` || groupAd.ad?.type !== "RESPONSIVE_SEARCH_AD") {
|
|
2741
|
-
throw new
|
|
3549
|
+
throw new AdportError13("INVALID_INPUT", "google: responsive search ad was not found in the selected account and ad group");
|
|
2742
3550
|
}
|
|
2743
3551
|
const current = groupAd.ad;
|
|
2744
3552
|
const update3 = { resourceName: `customers/${cid}/ads/${payload.ad_id}` };
|
|
@@ -2822,7 +3630,7 @@ var GoogleAdsProvider = class {
|
|
|
2822
3630
|
};
|
|
2823
3631
|
updateMask = "target_impression_share.cpc_bid_ceiling_micros";
|
|
2824
3632
|
} else {
|
|
2825
|
-
throw new
|
|
3633
|
+
throw new AdportError13(
|
|
2826
3634
|
"PROVIDER_ERROR",
|
|
2827
3635
|
`google: campaign "${current.name}" uses ${current.strategyType} bidding, which has no CPC bid ceiling. Use google_set_bidding_strategy to switch strategy (e.g. MAXIMIZE_CLICKS supports a ceiling).`
|
|
2828
3636
|
);
|
|
@@ -2842,13 +3650,13 @@ var GoogleAdsProvider = class {
|
|
|
2842
3650
|
}
|
|
2843
3651
|
async planSetBiddingStrategy(cid, payload) {
|
|
2844
3652
|
if (payload.target_cpa_micros && payload.strategy !== "MAXIMIZE_CONVERSIONS") {
|
|
2845
|
-
throw new
|
|
3653
|
+
throw new AdportError13("INVALID_INPUT", "target_cpa_micros only applies to MAXIMIZE_CONVERSIONS");
|
|
2846
3654
|
}
|
|
2847
3655
|
if (payload.target_roas && payload.strategy !== "MAXIMIZE_CONVERSION_VALUE") {
|
|
2848
|
-
throw new
|
|
3656
|
+
throw new AdportError13("INVALID_INPUT", "target_roas only applies to MAXIMIZE_CONVERSION_VALUE");
|
|
2849
3657
|
}
|
|
2850
3658
|
if (payload.cpc_bid_ceiling_micros && payload.strategy !== "MAXIMIZE_CLICKS") {
|
|
2851
|
-
throw new
|
|
3659
|
+
throw new AdportError13("INVALID_INPUT", "cpc_bid_ceiling_micros only applies to MAXIMIZE_CLICKS (target spend)");
|
|
2852
3660
|
}
|
|
2853
3661
|
const current = await this.lookupCampaignBidding(cid, payload.campaign_id);
|
|
2854
3662
|
const resourceName = `customers/${cid}/campaigns/${payload.campaign_id}`;
|
|
@@ -2899,7 +3707,7 @@ var GoogleAdsProvider = class {
|
|
|
2899
3707
|
};
|
|
2900
3708
|
}
|
|
2901
3709
|
async lookupCampaignBidding(cid, campaignId) {
|
|
2902
|
-
if (!/^\d+$/.test(campaignId)) throw new
|
|
3710
|
+
if (!/^\d+$/.test(campaignId)) throw new AdportError13("INVALID_INPUT", "google: invalid campaign ID");
|
|
2903
3711
|
const rows = await this.client.search(
|
|
2904
3712
|
cid,
|
|
2905
3713
|
`SELECT campaign.name, campaign.bidding_strategy_type, campaign.target_spend.cpc_bid_ceiling_micros, campaign.target_impression_share.cpc_bid_ceiling_micros FROM campaign WHERE campaign.id = ${campaignId} LIMIT 1`,
|
|
@@ -2907,7 +3715,7 @@ var GoogleAdsProvider = class {
|
|
|
2907
3715
|
);
|
|
2908
3716
|
const row2 = rows[0];
|
|
2909
3717
|
if (!row2) {
|
|
2910
|
-
throw new
|
|
3718
|
+
throw new AdportError13("PROVIDER_ERROR", `google: campaign ${campaignId} not found in account ${cid}`);
|
|
2911
3719
|
}
|
|
2912
3720
|
const campaign = row2.campaign;
|
|
2913
3721
|
const ceiling = campaign.targetSpend?.cpcBidCeilingMicros ?? campaign.targetImpressionShare?.cpcBidCeilingMicros;
|
|
@@ -2918,7 +3726,7 @@ var GoogleAdsProvider = class {
|
|
|
2918
3726
|
};
|
|
2919
3727
|
}
|
|
2920
3728
|
async lookupCampaign(cid, campaignId) {
|
|
2921
|
-
if (!/^\d+$/.test(campaignId)) throw new
|
|
3729
|
+
if (!/^\d+$/.test(campaignId)) throw new AdportError13("INVALID_INPUT", "google: invalid campaign ID");
|
|
2922
3730
|
const rows = await this.client.search(
|
|
2923
3731
|
cid,
|
|
2924
3732
|
`SELECT campaign.name, campaign.status, campaign.campaign_budget, campaign_budget.resource_name, campaign_budget.amount_micros, campaign_budget.explicitly_shared FROM campaign WHERE campaign.id = ${campaignId} LIMIT 1`,
|
|
@@ -2926,7 +3734,7 @@ var GoogleAdsProvider = class {
|
|
|
2926
3734
|
);
|
|
2927
3735
|
const row2 = rows[0];
|
|
2928
3736
|
if (!row2) {
|
|
2929
|
-
throw new
|
|
3737
|
+
throw new AdportError13("PROVIDER_ERROR", `google: campaign ${campaignId} not found in account ${cid}`);
|
|
2930
3738
|
}
|
|
2931
3739
|
const campaign = row2.campaign;
|
|
2932
3740
|
const budget = row2.campaignBudget ?? {};
|
|
@@ -2947,12 +3755,12 @@ function validateRsa(payload) {
|
|
|
2947
3755
|
for (const h of payload.headlines) if (h.length > 30) problems.push(`headline over 30 chars: "${h}"`);
|
|
2948
3756
|
for (const d of payload.descriptions) if (d.length > 90) problems.push(`description over 90 chars: "${d}"`);
|
|
2949
3757
|
if (problems.length > 0) {
|
|
2950
|
-
throw new
|
|
3758
|
+
throw new AdportError13("INVALID_INPUT", `Responsive search ad invalid: ${problems.join("; ")}`);
|
|
2951
3759
|
}
|
|
2952
3760
|
}
|
|
2953
3761
|
function validateGoogleService(service) {
|
|
2954
3762
|
if (!/^[a-z][A-Za-z0-9]{1,80}$/.test(service)) {
|
|
2955
|
-
throw new
|
|
3763
|
+
throw new AdportError13("INVALID_INPUT", `google: invalid mutate service "${service}"`);
|
|
2956
3764
|
}
|
|
2957
3765
|
return service;
|
|
2958
3766
|
}
|
|
@@ -2965,7 +3773,7 @@ function validateCustomerReferences(value, customerId) {
|
|
|
2965
3773
|
if (typeof value === "string") {
|
|
2966
3774
|
const match = /^customers\/(\d+)/.exec(value);
|
|
2967
3775
|
if (match && match[1] !== customerId) {
|
|
2968
|
-
throw new
|
|
3776
|
+
throw new AdportError13("INVALID_INPUT", `google: resource reference belongs to customer ${match[1]}, not ${customerId}`);
|
|
2969
3777
|
}
|
|
2970
3778
|
}
|
|
2971
3779
|
return;
|
|
@@ -2976,7 +3784,7 @@ function collectGoogleBudgetCreates(creates) {
|
|
|
2976
3784
|
return creates.map((create3, index) => {
|
|
2977
3785
|
const amount = Number(create3.amountMicros);
|
|
2978
3786
|
if (!Number.isSafeInteger(amount) || amount <= 0) {
|
|
2979
|
-
throw new
|
|
3787
|
+
throw new AdportError13(
|
|
2980
3788
|
"INVALID_INPUT",
|
|
2981
3789
|
`google: campaignBudgets create ${index} must include a positive integer amountMicros for policy checks`
|
|
2982
3790
|
);
|
|
@@ -2989,47 +3797,47 @@ function round2(n) {
|
|
|
2989
3797
|
}
|
|
2990
3798
|
|
|
2991
3799
|
// src/tools.ts
|
|
2992
|
-
import { creativesOutput as creativesOutput4, defineTool as
|
|
2993
|
-
import { z as
|
|
3800
|
+
import { creativesOutput as creativesOutput4, defineTool as defineTool13, guardedWriteTool as guardedWriteTool12 } from "@adport/core";
|
|
3801
|
+
import { z as z15 } from "zod";
|
|
2994
3802
|
|
|
2995
3803
|
// src/planning.ts
|
|
2996
|
-
import { AdportError as
|
|
2997
|
-
import { z as
|
|
2998
|
-
var identifier2 =
|
|
2999
|
-
var
|
|
3000
|
-
var url3 =
|
|
3804
|
+
import { AdportError as AdportError14, defineTool as defineTool11 } from "@adport/core";
|
|
3805
|
+
import { z as z13 } from "zod";
|
|
3806
|
+
var identifier2 = z13.string().regex(/^\d+$/);
|
|
3807
|
+
var keywords2 = z13.array(z13.string().trim().min(1).max(500));
|
|
3808
|
+
var url3 = z13.string().url().refine((value) => {
|
|
3001
3809
|
const parsed = new URL(value);
|
|
3002
3810
|
return ["https:", "http:"].includes(parsed.protocol) && !parsed.username && !parsed.password;
|
|
3003
3811
|
}, "Use an HTTP(S) URL without credentials");
|
|
3004
3812
|
var targeting = {
|
|
3005
|
-
account_id:
|
|
3813
|
+
account_id: z13.string(),
|
|
3006
3814
|
language_id: identifier2.optional(),
|
|
3007
|
-
location_ids:
|
|
3008
|
-
network:
|
|
3009
|
-
include_adult_keywords:
|
|
3010
|
-
include_average_cpc:
|
|
3815
|
+
location_ids: z13.array(identifier2).max(10).default([]),
|
|
3816
|
+
network: z13.enum(["GOOGLE_SEARCH", "GOOGLE_SEARCH_AND_PARTNERS"]).default("GOOGLE_SEARCH"),
|
|
3817
|
+
include_adult_keywords: z13.boolean().default(false),
|
|
3818
|
+
include_average_cpc: z13.boolean().default(false)
|
|
3011
3819
|
};
|
|
3012
|
-
var nativeResult =
|
|
3013
|
-
var output =
|
|
3014
|
-
results:
|
|
3820
|
+
var nativeResult = z13.record(z13.string(), z13.unknown());
|
|
3821
|
+
var output = z13.object({
|
|
3822
|
+
results: z13.array(nativeResult),
|
|
3015
3823
|
aggregate_metric_results: nativeResult.optional(),
|
|
3016
|
-
next_page_token:
|
|
3017
|
-
total_size:
|
|
3018
|
-
truncated:
|
|
3824
|
+
next_page_token: z13.string().optional(),
|
|
3825
|
+
total_size: z13.string().regex(/^\d+$/).optional(),
|
|
3826
|
+
truncated: z13.boolean()
|
|
3019
3827
|
});
|
|
3020
|
-
var ideasInput =
|
|
3828
|
+
var ideasInput = z13.object({
|
|
3021
3829
|
...targeting,
|
|
3022
|
-
seed:
|
|
3023
|
-
|
|
3024
|
-
|
|
3025
|
-
|
|
3026
|
-
|
|
3830
|
+
seed: z13.discriminatedUnion("type", [
|
|
3831
|
+
z13.object({ type: z13.literal("keywords"), keywords: keywords2.min(1).max(20) }),
|
|
3832
|
+
z13.object({ type: z13.literal("url"), url: url3 }),
|
|
3833
|
+
z13.object({ type: z13.literal("keywords_and_url"), keywords: keywords2.min(1).max(20), url: url3 }),
|
|
3834
|
+
z13.object({ type: z13.literal("site"), url: url3 })
|
|
3027
3835
|
]),
|
|
3028
|
-
page_size:
|
|
3029
|
-
page_token:
|
|
3836
|
+
page_size: z13.number().int().positive().max(1e4).default(100),
|
|
3837
|
+
page_token: z13.string().min(1).max(1e4).optional()
|
|
3030
3838
|
});
|
|
3031
|
-
var historicalInput =
|
|
3032
|
-
function
|
|
3839
|
+
var historicalInput = z13.object({ ...targeting, keywords: keywords2.min(1).max(1e4) });
|
|
3840
|
+
function target4(input2) {
|
|
3033
3841
|
return {
|
|
3034
3842
|
...input2.language_id ? { language: `languageConstants/${input2.language_id}` } : {},
|
|
3035
3843
|
geoTargetConstants: input2.location_ids.map((value) => `geoTargetConstants/${value}`),
|
|
@@ -3049,12 +3857,12 @@ function result(data) {
|
|
|
3049
3857
|
...total === void 0 ? {} : { total_size: total },
|
|
3050
3858
|
truncated: typeof token === "string" && token.length > 0
|
|
3051
3859
|
});
|
|
3052
|
-
if (!parsed.success) throw new
|
|
3860
|
+
if (!parsed.success) throw new AdportError14("PROVIDER_ERROR", "Google keyword planning returned an invalid response shape");
|
|
3053
3861
|
return parsed.data;
|
|
3054
3862
|
}
|
|
3055
3863
|
function googlePlanningTools(provider) {
|
|
3056
3864
|
return [
|
|
3057
|
-
|
|
3865
|
+
defineTool11({
|
|
3058
3866
|
name: "google_keyword_ideas",
|
|
3059
3867
|
namespace: "google",
|
|
3060
3868
|
description: "Discover keyword ideas from keywords, a URL, both, or a site. Reads one native page; pass next_page_token as page_token with identical targeting and seed. Metrics are historical estimates, not a forecast. No keyword plan or campaign is created.",
|
|
@@ -3065,7 +3873,7 @@ function googlePlanningTools(provider) {
|
|
|
3065
3873
|
async handler(input2) {
|
|
3066
3874
|
const seed = input2.seed;
|
|
3067
3875
|
const body = {
|
|
3068
|
-
...
|
|
3876
|
+
...target4(input2),
|
|
3069
3877
|
pageSize: input2.page_size,
|
|
3070
3878
|
...input2.page_token ? { pageToken: input2.page_token } : {},
|
|
3071
3879
|
...seed.type === "keywords" ? { keywordSeed: { keywords: seed.keywords } } : seed.type === "url" ? { urlSeed: { url: seed.url } } : seed.type === "keywords_and_url" ? { keywordAndUrlSeed: { keywords: seed.keywords, url: seed.url } } : { siteSeed: { site: seed.url } }
|
|
@@ -3073,48 +3881,48 @@ function googlePlanningTools(provider) {
|
|
|
3073
3881
|
return result(await provider.keywordPlanning(normalizeCustomerId(input2.account_id), "generateKeywordIdeas", body));
|
|
3074
3882
|
}
|
|
3075
3883
|
}),
|
|
3076
|
-
|
|
3884
|
+
defineTool11({
|
|
3077
3885
|
name: "google_keyword_historical_metrics",
|
|
3078
3886
|
namespace: "google",
|
|
3079
3887
|
description: "Read native historical search volume, competition and bid estimates for up to 10,000 keywords. Google merges close variants; missing values stay unavailable and monetary int64 values remain native micros strings. Does not create a keyword plan or campaign.",
|
|
3080
3888
|
input: historicalInput,
|
|
3081
3889
|
output,
|
|
3082
3890
|
annotations: { readOnly: true },
|
|
3083
|
-
handler: async (input2) => result(await provider.keywordPlanning(normalizeCustomerId(input2.account_id), "generateKeywordHistoricalMetrics", { ...
|
|
3891
|
+
handler: async (input2) => result(await provider.keywordPlanning(normalizeCustomerId(input2.account_id), "generateKeywordHistoricalMetrics", { ...target4(input2), keywords: input2.keywords }))
|
|
3084
3892
|
})
|
|
3085
3893
|
];
|
|
3086
3894
|
}
|
|
3087
3895
|
|
|
3088
3896
|
// src/field-metadata.ts
|
|
3089
|
-
import { AdportError as
|
|
3090
|
-
import { z as
|
|
3091
|
-
var fieldName =
|
|
3092
|
-
var input =
|
|
3093
|
-
account_id:
|
|
3094
|
-
field_names:
|
|
3095
|
-
include_compatibility:
|
|
3096
|
-
page_token:
|
|
3897
|
+
import { AdportError as AdportError15, defineTool as defineTool12 } from "@adport/core";
|
|
3898
|
+
import { z as z14 } from "zod";
|
|
3899
|
+
var fieldName = z14.string().regex(/^[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)*$/).max(200);
|
|
3900
|
+
var input = z14.object({
|
|
3901
|
+
account_id: z14.string(),
|
|
3902
|
+
field_names: z14.array(fieldName).min(1).max(20).refine((values) => new Set(values).size === values.length, "Field names must be unique"),
|
|
3903
|
+
include_compatibility: z14.boolean().default(false),
|
|
3904
|
+
page_token: z14.string().min(1).max(16384).optional()
|
|
3097
3905
|
});
|
|
3098
|
-
var field2 =
|
|
3906
|
+
var field2 = z14.object({
|
|
3099
3907
|
name: fieldName,
|
|
3100
|
-
resourceName:
|
|
3101
|
-
category:
|
|
3102
|
-
dataType:
|
|
3103
|
-
typeUrl:
|
|
3104
|
-
selectable:
|
|
3105
|
-
filterable:
|
|
3106
|
-
sortable:
|
|
3107
|
-
isRepeated:
|
|
3108
|
-
enumValues:
|
|
3109
|
-
selectableWith:
|
|
3110
|
-
attributeResources:
|
|
3111
|
-
metrics:
|
|
3112
|
-
segments:
|
|
3908
|
+
resourceName: z14.string().optional(),
|
|
3909
|
+
category: z14.string().min(1),
|
|
3910
|
+
dataType: z14.string().min(1).optional(),
|
|
3911
|
+
typeUrl: z14.string().optional(),
|
|
3912
|
+
selectable: z14.boolean().optional(),
|
|
3913
|
+
filterable: z14.boolean().optional(),
|
|
3914
|
+
sortable: z14.boolean().optional(),
|
|
3915
|
+
isRepeated: z14.boolean().optional(),
|
|
3916
|
+
enumValues: z14.array(z14.string()).optional(),
|
|
3917
|
+
selectableWith: z14.array(z14.string()).optional(),
|
|
3918
|
+
attributeResources: z14.array(z14.string()).optional(),
|
|
3919
|
+
metrics: z14.array(z14.string()).optional(),
|
|
3920
|
+
segments: z14.array(z14.string()).optional()
|
|
3113
3921
|
}).passthrough();
|
|
3114
|
-
var nativeOutput =
|
|
3115
|
-
var output2 =
|
|
3922
|
+
var nativeOutput = z14.object({ results: z14.array(field2).default([]), nextPageToken: z14.string().optional(), totalResultsCount: z14.string().regex(/^\d+$/).optional() });
|
|
3923
|
+
var output2 = z14.object({ api_version: z14.string(), results: z14.array(field2), truncated: z14.boolean(), next_page_token: z14.string().optional(), total_results_count: z14.string().optional() });
|
|
3116
3924
|
function googleFieldMetadataTools(provider) {
|
|
3117
|
-
return [
|
|
3925
|
+
return [defineTool12({
|
|
3118
3926
|
name: "google_field_metadata",
|
|
3119
3927
|
namespace: "google",
|
|
3120
3928
|
description: "Look up up to 20 exact GAQL resource or field names in the connected API version. Returns native types, enums and queryability; optional compatibility lists can be large. API-wide metadata, not account performance. Continue next_page_token with identical names/options.",
|
|
@@ -3127,17 +3935,17 @@ function googleFieldMetadataTools(provider) {
|
|
|
3127
3935
|
const fields5 = ["name", "category", "data_type", "type_url", "is_repeated", "selectable", "filterable", "sortable", "enum_values", ...raw.include_compatibility ? ["selectable_with", "attribute_resources", "metrics", "segments"] : []];
|
|
3128
3936
|
const query = `SELECT ${fields5.join(", ")} WHERE name IN (${raw.field_names.map((name5) => `'${name5}'`).join(", ")})`;
|
|
3129
3937
|
const { apiVersion, response } = await provider.fieldMetadata(query, raw.field_names.length, raw.page_token), parsed = nativeOutput.safeParse(response);
|
|
3130
|
-
if (!parsed.success) throw new
|
|
3938
|
+
if (!parsed.success) throw new AdportError15("PROVIDER_ERROR", "google: invalid field metadata response");
|
|
3131
3939
|
const result2 = parsed.data;
|
|
3132
|
-
if (result2.results.length > raw.field_names.length || new Set(result2.results.map((value) => value.name)).size !== result2.results.length || result2.results.some((value) => !raw.field_names.includes(value.name) || value.resourceName !== void 0 && value.resourceName !== `googleAdsFields/${value.name}`)) throw new
|
|
3940
|
+
if (result2.results.length > raw.field_names.length || new Set(result2.results.map((value) => value.name)).size !== result2.results.length || result2.results.some((value) => !raw.field_names.includes(value.name) || value.resourceName !== void 0 && value.resourceName !== `googleAdsFields/${value.name}`)) throw new AdportError15("PROVIDER_ERROR", "google: field metadata identity or requested selection mismatch");
|
|
3133
3941
|
return { api_version: apiVersion, results: result2.results, truncated: Boolean(result2.nextPageToken), ...result2.nextPageToken ? { next_page_token: result2.nextPageToken } : {}, ...result2.totalResultsCount !== void 0 ? { total_results_count: result2.totalResultsCount } : {} };
|
|
3134
3942
|
}
|
|
3135
3943
|
})];
|
|
3136
3944
|
}
|
|
3137
3945
|
|
|
3138
3946
|
// src/tools.ts
|
|
3139
|
-
var statusSchema =
|
|
3140
|
-
var matchTypeSchema =
|
|
3947
|
+
var statusSchema = z15.enum(["ENABLED", "PAUSED"]);
|
|
3948
|
+
var matchTypeSchema = z15.enum(["EXACT", "PHRASE", "BROAD"]);
|
|
3141
3949
|
function googleTools(provider) {
|
|
3142
3950
|
return [
|
|
3143
3951
|
...googlePlanningTools(provider),
|
|
@@ -3146,38 +3954,41 @@ function googleTools(provider) {
|
|
|
3146
3954
|
...googleLabelTools(provider),
|
|
3147
3955
|
...googleFieldMetadataTools(provider),
|
|
3148
3956
|
...googleConversionTools(provider),
|
|
3957
|
+
...googleConversionGoalTools(provider),
|
|
3149
3958
|
...googleDataManagerTools(provider),
|
|
3150
3959
|
...googleExperimentTools(provider),
|
|
3151
3960
|
...googlePerformanceMaxTools(provider),
|
|
3152
3961
|
...googleTargetingTools(provider),
|
|
3153
|
-
|
|
3962
|
+
...googleNegativeKeywordTools(provider),
|
|
3963
|
+
...googleKeywordTools(),
|
|
3964
|
+
defineTool13({
|
|
3154
3965
|
name: "google_ads",
|
|
3155
3966
|
namespace: "google",
|
|
3156
3967
|
description: "Browse Google Ads with their actual text, final URLs, serving status and creative actions. Filter by campaign or ad group. Changes requested from the creative viewer return a preview before approval.",
|
|
3157
|
-
input:
|
|
3158
|
-
account_id:
|
|
3159
|
-
campaign_id:
|
|
3160
|
-
ad_group_id:
|
|
3161
|
-
include_drafts:
|
|
3162
|
-
limit:
|
|
3968
|
+
input: z15.object({
|
|
3969
|
+
account_id: z15.string(),
|
|
3970
|
+
campaign_id: z15.string().regex(/^\d+$/).optional(),
|
|
3971
|
+
ad_group_id: z15.string().regex(/^\d+$/).optional(),
|
|
3972
|
+
include_drafts: z15.boolean().optional().describe("Include in-design experiment draft ads; off by default"),
|
|
3973
|
+
limit: z15.number().int().positive().max(200).default(50)
|
|
3163
3974
|
}),
|
|
3164
3975
|
output: creativesOutput4,
|
|
3165
3976
|
presentation: "creatives",
|
|
3166
3977
|
annotations: { readOnly: true },
|
|
3167
3978
|
handler: (input2) => provider.listAds(input2)
|
|
3168
3979
|
}),
|
|
3169
|
-
|
|
3980
|
+
defineTool13({
|
|
3170
3981
|
name: "google_gaql",
|
|
3171
3982
|
namespace: "google",
|
|
3172
|
-
description: `Run a structured Google Ads (GAQL) query: pick a resource (campaign, ad_group, keyword_view, change_event, ...), fields (e.g. campaign.name, metrics.clicks, segments.date), optional conditions and ordering. Conditions are raw GAQL predicates, e.g. "segments.date DURING LAST_7_DAYS" or "campaign.status = 'ENABLED'".`,
|
|
3173
|
-
input:
|
|
3174
|
-
customer_id:
|
|
3175
|
-
resource:
|
|
3176
|
-
fields:
|
|
3177
|
-
conditions:
|
|
3178
|
-
order_by:
|
|
3179
|
-
include_drafts:
|
|
3180
|
-
limit:
|
|
3983
|
+
description: `Run a structured Google Ads (GAQL) query: pick a resource (campaign, ad_group, keyword_view, ad_group_criterion, change_event, ...), fields (e.g. campaign.name, metrics.clicks, segments.date), optional conditions and ordering. Conditions are raw GAQL predicates, e.g. "segments.date DURING LAST_7_DAYS" or "campaign.status = 'ENABLED'".`,
|
|
3984
|
+
input: z15.object({
|
|
3985
|
+
customer_id: z15.string().describe("10-digit account id, dashes ok"),
|
|
3986
|
+
resource: z15.string().min(1),
|
|
3987
|
+
fields: z15.array(z15.string()).min(1),
|
|
3988
|
+
conditions: z15.array(z15.string()).optional(),
|
|
3989
|
+
order_by: z15.array(z15.string()).optional(),
|
|
3990
|
+
include_drafts: z15.boolean().optional().describe("Include in-design experiment draft campaigns and children; off by default"),
|
|
3991
|
+
limit: z15.number().int().positive().max(1e4).default(200)
|
|
3181
3992
|
}),
|
|
3182
3993
|
annotations: { readOnly: true },
|
|
3183
3994
|
async handler(input2) {
|
|
@@ -3185,193 +3996,193 @@ function googleTools(provider) {
|
|
|
3185
3996
|
return { rows, row_count: rows.length };
|
|
3186
3997
|
}
|
|
3187
3998
|
}),
|
|
3188
|
-
|
|
3999
|
+
guardedWriteTool12({
|
|
3189
4000
|
name: "google_create_campaign",
|
|
3190
4001
|
namespace: "google",
|
|
3191
4002
|
description: "Create a campaign and non-shared budget atomically, with bidding and optional location/language targeting. Search defaults to Google Search only (no partners or Display expansion). Use google_gaql to resolve geo_target_constant and language_constant IDs. Ad groups, keywords and responsive search ads have separate explicit tools. Creation remains subject to paused-creation policy.",
|
|
3192
4003
|
provider: "google",
|
|
3193
4004
|
kind: "create",
|
|
3194
|
-
payload:
|
|
3195
|
-
name:
|
|
3196
|
-
daily_budget_micros:
|
|
3197
|
-
channel_type:
|
|
4005
|
+
payload: z15.object({
|
|
4006
|
+
name: z15.string().min(1),
|
|
4007
|
+
daily_budget_micros: z15.number().int().positive().describe("1 currency unit = 1,000,000 micros"),
|
|
4008
|
+
channel_type: z15.enum(["SEARCH", "DISPLAY", "SHOPPING", "VIDEO", "PERFORMANCE_MAX"]).default("SEARCH"),
|
|
3198
4009
|
status: statusSchema.optional(),
|
|
3199
|
-
bidding_strategy:
|
|
3200
|
-
search_partners:
|
|
3201
|
-
display_expansion:
|
|
3202
|
-
location_ids:
|
|
3203
|
-
language_ids:
|
|
3204
|
-
location_presence_only:
|
|
4010
|
+
bidding_strategy: z15.enum(["MANUAL_CPC", "MAXIMIZE_CLICKS", "MAXIMIZE_CONVERSIONS", "MAXIMIZE_CONVERSION_VALUE"]).default("MANUAL_CPC"),
|
|
4011
|
+
search_partners: z15.boolean().optional().describe("SEARCH only; defaults false"),
|
|
4012
|
+
display_expansion: z15.boolean().optional().describe("SEARCH only; defaults false"),
|
|
4013
|
+
location_ids: z15.array(z15.string().regex(/^\d+$/)).min(1).max(100).optional().describe("Google geo target constant IDs; omitted means unrestricted locations"),
|
|
4014
|
+
language_ids: z15.array(z15.string().regex(/^\d+$/)).min(1).max(100).optional().describe("Eligible non-Search campaigns only. Search language matching is automatic; omit this field for Search."),
|
|
4015
|
+
location_presence_only: z15.boolean().optional().describe("Target people in locations rather than people interested in them; defaults true when locations are specified")
|
|
3205
4016
|
})
|
|
3206
4017
|
}),
|
|
3207
|
-
|
|
4018
|
+
guardedWriteTool12({
|
|
3208
4019
|
name: "google_set_campaign_status",
|
|
3209
4020
|
namespace: "google",
|
|
3210
4021
|
description: "Enable or pause a campaign.",
|
|
3211
4022
|
provider: "google",
|
|
3212
4023
|
kind: "update",
|
|
3213
|
-
payload:
|
|
4024
|
+
payload: z15.object({ campaign_id: z15.string(), status: statusSchema })
|
|
3214
4025
|
}),
|
|
3215
|
-
|
|
4026
|
+
guardedWriteTool12({
|
|
3216
4027
|
name: "google_set_budget",
|
|
3217
4028
|
namespace: "google",
|
|
3218
4029
|
description: "Change a campaign's daily budget. The preview warns when the budget is shared across campaigns.",
|
|
3219
4030
|
provider: "google",
|
|
3220
4031
|
kind: "update",
|
|
3221
|
-
payload:
|
|
4032
|
+
payload: z15.object({ campaign_id: z15.string(), daily_budget_micros: z15.number().int().positive() })
|
|
3222
4033
|
}),
|
|
3223
|
-
|
|
4034
|
+
guardedWriteTool12({
|
|
3224
4035
|
name: "google_set_bid_ceiling",
|
|
3225
4036
|
namespace: "google",
|
|
3226
4037
|
description: "Set a campaign's max CPC bid ceiling (micros). Works for MAXIMIZE_CLICKS (target spend) and TARGET_IMPRESSION_SHARE strategies; fails with guidance for others.",
|
|
3227
4038
|
provider: "google",
|
|
3228
4039
|
kind: "update",
|
|
3229
|
-
payload:
|
|
3230
|
-
campaign_id:
|
|
3231
|
-
cpc_bid_ceiling_micros:
|
|
4040
|
+
payload: z15.object({
|
|
4041
|
+
campaign_id: z15.string(),
|
|
4042
|
+
cpc_bid_ceiling_micros: z15.number().int().positive().describe("1 currency unit = 1,000,000 micros")
|
|
3232
4043
|
})
|
|
3233
4044
|
}),
|
|
3234
|
-
|
|
4045
|
+
guardedWriteTool12({
|
|
3235
4046
|
name: "google_set_bidding_strategy",
|
|
3236
4047
|
namespace: "google",
|
|
3237
4048
|
description: "Switch a campaign's bidding strategy: MANUAL_CPC, MAXIMIZE_CLICKS (optional cpc_bid_ceiling_micros), MAXIMIZE_CONVERSIONS (optional target_cpa_micros), MAXIMIZE_CONVERSION_VALUE (optional target_roas). Also updates the target of the current strategy when the strategy stays the same.",
|
|
3238
4049
|
provider: "google",
|
|
3239
4050
|
kind: "update",
|
|
3240
|
-
payload:
|
|
3241
|
-
campaign_id:
|
|
3242
|
-
strategy:
|
|
3243
|
-
target_cpa_micros:
|
|
3244
|
-
target_roas:
|
|
3245
|
-
cpc_bid_ceiling_micros:
|
|
4051
|
+
payload: z15.object({
|
|
4052
|
+
campaign_id: z15.string(),
|
|
4053
|
+
strategy: z15.enum(["MANUAL_CPC", "MAXIMIZE_CLICKS", "MAXIMIZE_CONVERSIONS", "MAXIMIZE_CONVERSION_VALUE"]),
|
|
4054
|
+
target_cpa_micros: z15.number().int().positive().optional(),
|
|
4055
|
+
target_roas: z15.number().positive().optional().describe("e.g. 3.5 = 350% return on ad spend"),
|
|
4056
|
+
cpc_bid_ceiling_micros: z15.number().int().positive().optional()
|
|
3246
4057
|
})
|
|
3247
4058
|
}),
|
|
3248
|
-
|
|
4059
|
+
guardedWriteTool12({
|
|
3249
4060
|
name: "google_create_ad_group",
|
|
3250
4061
|
namespace: "google",
|
|
3251
4062
|
description: "Create a SEARCH_STANDARD ad group in a campaign.",
|
|
3252
4063
|
provider: "google",
|
|
3253
4064
|
kind: "create",
|
|
3254
|
-
payload:
|
|
3255
|
-
campaign_id:
|
|
3256
|
-
name:
|
|
3257
|
-
cpc_bid_micros:
|
|
4065
|
+
payload: z15.object({
|
|
4066
|
+
campaign_id: z15.string(),
|
|
4067
|
+
name: z15.string().min(1),
|
|
4068
|
+
cpc_bid_micros: z15.number().int().positive().optional()
|
|
3258
4069
|
})
|
|
3259
4070
|
}),
|
|
3260
|
-
|
|
4071
|
+
guardedWriteTool12({
|
|
3261
4072
|
name: "google_set_ad_group_status",
|
|
3262
4073
|
namespace: "google",
|
|
3263
4074
|
description: "Enable or pause an ad group.",
|
|
3264
4075
|
provider: "google",
|
|
3265
4076
|
kind: "update",
|
|
3266
|
-
payload:
|
|
4077
|
+
payload: z15.object({ ad_group_id: z15.string(), status: statusSchema })
|
|
3267
4078
|
}),
|
|
3268
|
-
|
|
4079
|
+
guardedWriteTool12({
|
|
3269
4080
|
name: "google_add_keywords",
|
|
3270
4081
|
namespace: "google",
|
|
3271
|
-
description: "Add keywords (or negative keywords) to an ad group.",
|
|
4082
|
+
description: "Add keywords (or negative keywords) to an ad group. For campaign-level or shared negatives, use google_add_campaign_negative_keywords or negative keyword lists.",
|
|
3272
4083
|
provider: "google",
|
|
3273
4084
|
kind: "create",
|
|
3274
|
-
payload:
|
|
3275
|
-
ad_group_id:
|
|
3276
|
-
keywords:
|
|
3277
|
-
negative:
|
|
3278
|
-
})
|
|
4085
|
+
payload: z15.object({
|
|
4086
|
+
ad_group_id: z15.string(),
|
|
4087
|
+
keywords: z15.array(z15.object({ text: z15.string().min(1), match_type: matchTypeSchema, ...keywordUrlFields })).min(1),
|
|
4088
|
+
negative: z15.boolean().default(false)
|
|
4089
|
+
}).refine((input2) => !input2.negative || input2.keywords.every((kw) => !kw.final_urls?.length && !kw.final_mobile_urls?.length && !kw.tracking_url_template && !kw.final_url_suffix), "Negative keywords cannot have URL fields").refine((input2) => input2.keywords.every((kw) => !fieldMissingFinalUrls(kw)), "Keyword mobile URLs, tracking templates and suffixes require final_urls")
|
|
3279
4090
|
}),
|
|
3280
|
-
|
|
4091
|
+
guardedWriteTool12({
|
|
3281
4092
|
name: "google_set_keyword_status",
|
|
3282
4093
|
namespace: "google",
|
|
3283
4094
|
description: "Enable or pause a keyword criterion.",
|
|
3284
4095
|
provider: "google",
|
|
3285
4096
|
kind: "update",
|
|
3286
|
-
payload:
|
|
4097
|
+
payload: z15.object({ ad_group_id: z15.string(), criterion_id: z15.string(), status: statusSchema })
|
|
3287
4098
|
}),
|
|
3288
|
-
|
|
4099
|
+
guardedWriteTool12({
|
|
3289
4100
|
name: "google_remove_keywords",
|
|
3290
4101
|
namespace: "google",
|
|
3291
4102
|
description: "PERMANENTLY remove keyword criteria from an ad group. Prefer google_set_keyword_status to pause.",
|
|
3292
4103
|
provider: "google",
|
|
3293
4104
|
kind: "remove",
|
|
3294
4105
|
destructive: true,
|
|
3295
|
-
payload:
|
|
4106
|
+
payload: z15.object({ ad_group_id: z15.string(), criterion_ids: z15.array(z15.string()).min(1) })
|
|
3296
4107
|
}),
|
|
3297
|
-
|
|
4108
|
+
guardedWriteTool12({
|
|
3298
4109
|
name: "google_set_ad_status",
|
|
3299
4110
|
namespace: "google",
|
|
3300
4111
|
description: "Enable or pause an existing ad in its ad group. Enabling an ad does not change its campaign or ad-group status.",
|
|
3301
4112
|
provider: "google",
|
|
3302
4113
|
kind: "update",
|
|
3303
|
-
payload:
|
|
3304
|
-
ad_group_id:
|
|
3305
|
-
ad_id:
|
|
4114
|
+
payload: z15.object({
|
|
4115
|
+
ad_group_id: z15.string().regex(/^\d+$/),
|
|
4116
|
+
ad_id: z15.string().regex(/^\d+$/),
|
|
3306
4117
|
status: statusSchema
|
|
3307
4118
|
})
|
|
3308
4119
|
}),
|
|
3309
|
-
|
|
4120
|
+
guardedWriteTool12({
|
|
3310
4121
|
name: "google_update_responsive_search_ad",
|
|
3311
4122
|
namespace: "google",
|
|
3312
4123
|
description: "Edit an existing responsive search ad\u2019s headlines, descriptions, final URLs or display paths. Omitted fields remain unchanged. Existing headline and description pinning is retained by position. Serving status does not change.",
|
|
3313
4124
|
provider: "google",
|
|
3314
4125
|
kind: "update",
|
|
3315
|
-
payload:
|
|
3316
|
-
ad_group_id:
|
|
3317
|
-
ad_id:
|
|
3318
|
-
headlines:
|
|
3319
|
-
descriptions:
|
|
3320
|
-
final_urls:
|
|
3321
|
-
path1:
|
|
3322
|
-
path2:
|
|
4126
|
+
payload: z15.object({
|
|
4127
|
+
ad_group_id: z15.string().regex(/^\d+$/),
|
|
4128
|
+
ad_id: z15.string().regex(/^\d+$/),
|
|
4129
|
+
headlines: z15.array(z15.string().min(1).max(30)).min(3).max(15).optional(),
|
|
4130
|
+
descriptions: z15.array(z15.string().min(1).max(90)).min(2).max(4).optional(),
|
|
4131
|
+
final_urls: z15.array(z15.string().url()).min(1).max(10).optional(),
|
|
4132
|
+
path1: z15.string().max(15).optional(),
|
|
4133
|
+
path2: z15.string().max(15).optional()
|
|
3323
4134
|
}).refine((input2) => ["headlines", "descriptions", "final_urls", "path1", "path2"].some((key2) => input2[key2] !== void 0), "Provide at least one content field")
|
|
3324
4135
|
}),
|
|
3325
|
-
|
|
4136
|
+
guardedWriteTool12({
|
|
3326
4137
|
name: "google_create_responsive_search_ad",
|
|
3327
4138
|
namespace: "google",
|
|
3328
4139
|
description: "Create a responsive search ad (3\u201315 headlines \u226430 chars, 2\u20134 descriptions \u226490 chars).",
|
|
3329
4140
|
provider: "google",
|
|
3330
4141
|
kind: "create",
|
|
3331
|
-
payload:
|
|
3332
|
-
ad_group_id:
|
|
3333
|
-
headlines:
|
|
3334
|
-
descriptions:
|
|
3335
|
-
final_urls:
|
|
3336
|
-
path1:
|
|
3337
|
-
path2:
|
|
4142
|
+
payload: z15.object({
|
|
4143
|
+
ad_group_id: z15.string(),
|
|
4144
|
+
headlines: z15.array(z15.string()).min(3).max(15),
|
|
4145
|
+
descriptions: z15.array(z15.string()).min(2).max(4),
|
|
4146
|
+
final_urls: z15.array(z15.string().url()).min(1),
|
|
4147
|
+
path1: z15.string().max(15).optional(),
|
|
4148
|
+
path2: z15.string().max(15).optional()
|
|
3338
4149
|
})
|
|
3339
4150
|
}),
|
|
3340
|
-
|
|
4151
|
+
guardedWriteTool12({
|
|
3341
4152
|
name: "google_api_create",
|
|
3342
4153
|
namespace: "google",
|
|
3343
4154
|
description: "Create resources through any Google Ads v25 mutate service using API-shaped create objects. Campaign status is forced to PAUSED and campaign-budget amounts are policy-checked.",
|
|
3344
4155
|
provider: "google",
|
|
3345
4156
|
kind: "create",
|
|
3346
|
-
payload:
|
|
3347
|
-
service:
|
|
3348
|
-
creates:
|
|
4157
|
+
payload: z15.object({
|
|
4158
|
+
service: z15.string().min(2).describe("REST mutate service, e.g. adGroupAds, assets, campaignCriteria"),
|
|
4159
|
+
creates: z15.array(z15.record(z15.string(), z15.unknown())).min(1).max(100)
|
|
3349
4160
|
})
|
|
3350
4161
|
}),
|
|
3351
|
-
|
|
4162
|
+
guardedWriteTool12({
|
|
3352
4163
|
name: "google_api_update",
|
|
3353
4164
|
namespace: "google",
|
|
3354
4165
|
description: "Update non-budget resources through any Google Ads v25 mutate service. Budget updates must use google_set_budget.",
|
|
3355
4166
|
provider: "google",
|
|
3356
4167
|
kind: "update",
|
|
3357
|
-
payload:
|
|
3358
|
-
service:
|
|
3359
|
-
updates:
|
|
3360
|
-
update:
|
|
3361
|
-
update_mask:
|
|
4168
|
+
payload: z15.object({
|
|
4169
|
+
service: z15.string().min(2),
|
|
4170
|
+
updates: z15.array(z15.object({
|
|
4171
|
+
update: z15.record(z15.string(), z15.unknown()),
|
|
4172
|
+
update_mask: z15.string().min(1)
|
|
3362
4173
|
})).min(1).max(100)
|
|
3363
4174
|
})
|
|
3364
4175
|
}),
|
|
3365
|
-
|
|
4176
|
+
guardedWriteTool12({
|
|
3366
4177
|
name: "google_api_remove",
|
|
3367
4178
|
namespace: "google",
|
|
3368
4179
|
description: "Permanently remove resources through any Google Ads v25 mutate service.",
|
|
3369
4180
|
provider: "google",
|
|
3370
4181
|
kind: "remove",
|
|
3371
4182
|
destructive: true,
|
|
3372
|
-
payload:
|
|
3373
|
-
service:
|
|
3374
|
-
resource_names:
|
|
4183
|
+
payload: z15.object({
|
|
4184
|
+
service: z15.string().min(2),
|
|
4185
|
+
resource_names: z15.array(z15.string().min(1)).min(1).max(100)
|
|
3375
4186
|
})
|
|
3376
4187
|
})
|
|
3377
4188
|
];
|
|
@@ -3379,9 +4190,9 @@ function googleTools(provider) {
|
|
|
3379
4190
|
|
|
3380
4191
|
// src/index.ts
|
|
3381
4192
|
async function resolveGoogleCredentials(store) {
|
|
3382
|
-
const
|
|
3383
|
-
if (
|
|
3384
|
-
const { client_id, client_secret, refresh_token, login_customer_id } =
|
|
4193
|
+
const record5 = await store.get("google");
|
|
4194
|
+
if (record5) {
|
|
4195
|
+
const { client_id, client_secret, refresh_token, login_customer_id } = record5.data;
|
|
3385
4196
|
if (client_id && client_secret && refresh_token) {
|
|
3386
4197
|
return {
|
|
3387
4198
|
clientId: client_id,
|