@adport/provider-spotify 0.8.0 → 0.10.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 +689 -3
- package/dist/index.js +1468 -64
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
package/dist/index.js
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import { FileResourceSecretStore } from "@adport/core";
|
|
3
|
+
|
|
1
4
|
// src/client.ts
|
|
2
5
|
import { AdportError } from "@adport/core";
|
|
6
|
+
import { createHmac, timingSafeEqual } from "crypto";
|
|
3
7
|
import { z } from "zod";
|
|
4
8
|
var SPOTIFY_API_BASE = "https://api-partner.spotify.com/ads/v3/";
|
|
5
9
|
var SPOTIFY_TOKEN_URL = "https://accounts.spotify.com/api/token";
|
|
@@ -48,34 +52,68 @@ var SpotifyAdsClient = class {
|
|
|
48
52
|
token;
|
|
49
53
|
refreshToken;
|
|
50
54
|
refreshing;
|
|
51
|
-
|
|
52
|
-
|
|
55
|
+
measurementReceipt(value) {
|
|
56
|
+
const payload = Buffer.from(JSON.stringify(value)).toString("base64url");
|
|
57
|
+
return `${payload}.${createHmac("sha256", this.measurementReceiptKey()).update(payload).digest("base64url")}`;
|
|
58
|
+
}
|
|
59
|
+
verifyMeasurementReceipt(receipt) {
|
|
60
|
+
const invalid = () => new AdportError("INVALID_INPUT", "spotify: invalid measurement resource receipt");
|
|
61
|
+
if (receipt.length > 4096 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]{43}$/.test(receipt)) throw invalid();
|
|
62
|
+
const [payload, signature] = receipt.split("."), supplied = Buffer.from(signature, "base64url");
|
|
63
|
+
const expected = createHmac("sha256", this.measurementReceiptKey()).update(payload).digest();
|
|
64
|
+
if (Buffer.from(payload, "base64url").toString("base64url") !== payload || supplied.toString("base64url") !== signature || supplied.length !== expected.length || !timingSafeEqual(supplied, expected)) throw invalid();
|
|
65
|
+
try {
|
|
66
|
+
return JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
|
|
67
|
+
} catch {
|
|
68
|
+
throw invalid();
|
|
69
|
+
}
|
|
53
70
|
}
|
|
54
|
-
|
|
55
|
-
return
|
|
71
|
+
measurementReceiptKey() {
|
|
72
|
+
return createHmac("sha256", this.credentials.clientSecret).update(`adport:spotify:measurement:v1:${this.credentials.clientId}`).digest();
|
|
56
73
|
}
|
|
57
|
-
async
|
|
74
|
+
async get(path, schema, params2 = new URLSearchParams()) {
|
|
75
|
+
return this.request(path, "GET", schema, void 0, params2);
|
|
76
|
+
}
|
|
77
|
+
async mutate(path, method, body, schema, params2 = new URLSearchParams()) {
|
|
78
|
+
return this.request(path, method, schema, body, params2);
|
|
79
|
+
}
|
|
80
|
+
async upload(path, body, schema) {
|
|
81
|
+
return this.request(path, "POST", schema, body);
|
|
82
|
+
}
|
|
83
|
+
async request(path, method, schema, body, params2 = new URLSearchParams(), retry = true) {
|
|
58
84
|
if (!/^[a-z_]+(?:\/[a-zA-Z0-9_-]+)*$/.test(path)) throw new AdportError("INVALID_INPUT", "spotify: invalid API resource path");
|
|
59
|
-
const
|
|
60
|
-
|
|
85
|
+
const url2 = new URL(path, SPOTIFY_API_BASE);
|
|
86
|
+
url2.search = params2.toString();
|
|
61
87
|
const token = await this.accessToken();
|
|
62
|
-
const response = await this.fetchImpl(
|
|
88
|
+
const response = await this.fetchImpl(url2.href, {
|
|
63
89
|
method,
|
|
64
|
-
headers: { authorization: `Bearer ${token}`, ...body !== void 0 ? { "content-type": "application/json" } : {} },
|
|
65
|
-
...body !== void 0 ? { body: JSON.stringify(body) } : {},
|
|
90
|
+
headers: { authorization: `Bearer ${token}`, ...body !== void 0 && !(body instanceof FormData) ? { "content-type": "application/json" } : {} },
|
|
91
|
+
...body !== void 0 ? { body: body instanceof FormData ? body : JSON.stringify(body) } : {},
|
|
66
92
|
redirect: "error",
|
|
67
|
-
signal: AbortSignal.timeout(
|
|
93
|
+
signal: AbortSignal.timeout(6e4)
|
|
68
94
|
});
|
|
69
95
|
if (response.status === 401 && method === "GET" && retry) {
|
|
70
96
|
if (this.token?.value === token) this.token = void 0;
|
|
71
|
-
return this.request(path, method, schema, body,
|
|
97
|
+
return this.request(path, method, schema, body, params2, false);
|
|
72
98
|
}
|
|
73
99
|
if (!response.ok) {
|
|
74
100
|
const advice = response.status === 403 ? " Check Ads API terms/allowlisting and ad-account permissions; reauthorization alone may not help." : "";
|
|
75
|
-
|
|
101
|
+
const details = { http_status: response.status };
|
|
102
|
+
if ([400, 404, 409, 422].includes(response.status)) {
|
|
103
|
+
const errors = z.object({ messages: z.array(z.string().max(2e3)).max(30).optional(), sp_trace_id: z.uuid().optional(), error_codes: z.array(z.object({ code: z.string().max(200), definition: z.string().max(2e3).optional() })).max(30).optional() });
|
|
104
|
+
const parsed2 = errors.safeParse(await response.json().catch(() => void 0));
|
|
105
|
+
if (parsed2.success) {
|
|
106
|
+
const redact = (value) => [this.credentials.clientId, this.credentials.clientSecret, this.credentials.refreshToken, this.refreshToken, token].reduce((text, secret) => secret ? text.replaceAll(secret, "[redacted]") : text, value);
|
|
107
|
+
if (parsed2.data.messages) details.messages = parsed2.data.messages.map(redact);
|
|
108
|
+
if (parsed2.data.sp_trace_id) details.sp_trace_id = parsed2.data.sp_trace_id;
|
|
109
|
+
if (parsed2.data.error_codes) details.error_codes = parsed2.data.error_codes.map((error) => ({ code: redact(error.code), ...error.definition ? { definition: redact(error.definition) } : {} }));
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
const messages = Array.isArray(details.messages) ? ` ${details.messages.join("; ")}` : "";
|
|
113
|
+
throw new AdportError("PROVIDER_ERROR", `spotify: HTTP ${response.status}.${advice}${messages}`, details);
|
|
76
114
|
}
|
|
77
|
-
const parsed = schema.safeParse(await response.json());
|
|
78
|
-
if (!parsed.success) throw new AdportError("PROVIDER_ERROR", "spotify: malformed API response");
|
|
115
|
+
const parsed = schema.safeParse(response.status === 204 ? void 0 : await response.json());
|
|
116
|
+
if (!parsed.success) throw new AdportError("PROVIDER_ERROR", "spotify: malformed API response", { api_path: path, response_issues: parsed.error.issues.map((issue) => ({ path: issue.path, code: issue.code })) });
|
|
79
117
|
return parsed.data;
|
|
80
118
|
}
|
|
81
119
|
async accessToken() {
|
|
@@ -97,12 +135,21 @@ var SpotifyAdsClient = class {
|
|
|
97
135
|
};
|
|
98
136
|
|
|
99
137
|
// src/provider.ts
|
|
100
|
-
import { z as
|
|
138
|
+
import { z as z11 } from "zod";
|
|
101
139
|
import {
|
|
102
|
-
AdportError as
|
|
140
|
+
AdportError as AdportError6,
|
|
141
|
+
LocalMediaResolver,
|
|
103
142
|
resolveDateRange
|
|
104
143
|
} from "@adport/core";
|
|
105
144
|
|
|
145
|
+
// src/creatives.ts
|
|
146
|
+
import { AdportError as AdportError2 } from "@adport/core";
|
|
147
|
+
import { z as z4 } from "zod";
|
|
148
|
+
|
|
149
|
+
// src/creative-schemas.ts
|
|
150
|
+
import { mediaSourceFields } from "@adport/core";
|
|
151
|
+
import { z as z3 } from "zod";
|
|
152
|
+
|
|
106
153
|
// src/schemas.ts
|
|
107
154
|
import { z as z2 } from "zod";
|
|
108
155
|
var spotifyId = z2.uuid();
|
|
@@ -153,6 +200,1312 @@ var setStatusSchema = z2.object({ campaign_id: spotifyId, status: z2.enum(["PAUS
|
|
|
153
200
|
var setBudgetSchema = z2.object({ ad_set_id: spotifyId, budget_micros: z2.number().int().positive().safe() });
|
|
154
201
|
var setDeliverySchema = z2.object({ ad_set_id: spotifyId, delivery: z2.enum(["OFF", "ON"]) });
|
|
155
202
|
|
|
203
|
+
// src/creative-schemas.ts
|
|
204
|
+
var strings = z3.array(z3.string().min(1)).max(1e3);
|
|
205
|
+
var money = z3.number().int().nonnegative().safe();
|
|
206
|
+
var url = z3.string().url().refine((value) => {
|
|
207
|
+
const u = new URL(value);
|
|
208
|
+
return ["https:", "http:"].includes(u.protocol) && !u.username && !u.password;
|
|
209
|
+
}, "Use an HTTP(S) destination without embedded credentials");
|
|
210
|
+
var assetType = z3.enum(["AUDIO", "IMAGE", "VIDEO"]);
|
|
211
|
+
var assetFormat = z3.enum(["AUDIO", "IMAGE", "VIDEO", "MULTI", "CATALOG"]);
|
|
212
|
+
var adLanguage = z3.enum(["ARABIC", "ARABIC_EGYPT", "BULGARIAN", "CHINESE", "CHINESE_HK", "CHINESE_TAIWAN", "CROATIAN", "CZECH", "DANISH", "DUTCH", "ENGLISH", "FINNISH", "FRENCH", "FRENCH_CANADA", "GERMAN", "GREEK", "HEBREW", "HUNGARIAN", "INDONESIAN", "ITALIAN", "JAPANESE", "KOREAN", "NORWEGIAN", "POLISH", "PORTUGUESE", "PORTUGUESE_PORTUGAL", "ROMANIAN", "RUSSIAN", "SLOVAK", "SPANISH", "SPANISH_ARGENTINA", "SPANISH_LATAM_CARIBBEAN", "SPANISH_MEXICO", "SWEDISH", "THAI", "TURKISH", "UKRAINIAN", "VIETNAMESE"]);
|
|
213
|
+
var deliveryGoal = z3.enum(["UNSET", "IMPRESSIONS", "REACH", "VIDEO_VIEWS", "CLICKS", "PAGE_VIEWS", "APP_INSTALLS", "STREAMS", "LEADS"]);
|
|
214
|
+
var bidStrategy = z3.enum(["COST_PER_RESULT", "MAX_BID", "AUTOBID", "UNSET"]);
|
|
215
|
+
var frequencyCaps = z3.array(z3.object({ frequency_unit: z3.enum(["DAY", "WEEK", "MONTH"]), frequency_period: z3.number().int().positive(), max_impressions: z3.number().int().positive() }).strict()).max(6);
|
|
216
|
+
var targets = z3.object({
|
|
217
|
+
age_ranges: z3.array(z3.object({ min: z3.number().int().min(13).max(99), max: z3.number().int().min(13).max(99) }).refine((v) => v.max >= v.min)).optional(),
|
|
218
|
+
artist_ids: strings.optional(),
|
|
219
|
+
genre_ids: strings.optional(),
|
|
220
|
+
interest_ids: z3.array(spotifyId).optional(),
|
|
221
|
+
geo_targets: z3.object({ country_code: z3.string().regex(/^[A-Z]{2}$/).optional(), city_ids: strings.optional(), postal_code_ids: strings.optional(), region_ids: strings.optional() }).strict().optional(),
|
|
222
|
+
genders: z3.array(z3.enum(["MALE", "FEMALE", "NON_BINARY"])).optional(),
|
|
223
|
+
platforms: z3.array(z3.enum(["ANDROID", "DESKTOP", "IOS"])).optional(),
|
|
224
|
+
podcast_episode_topic_ids: strings.optional(),
|
|
225
|
+
language: z3.string().regex(/^[a-z]{2}$/).optional(),
|
|
226
|
+
playlist_ids: strings.optional(),
|
|
227
|
+
placements: z3.array(z3.enum(["MUSIC", "PODCAST", "PODCAST_SAI", "PODCAST_DAI"])).min(1).optional(),
|
|
228
|
+
audience_ids: z3.array(spotifyId).optional(),
|
|
229
|
+
audience_ids_exclusions: z3.array(spotifyId).optional(),
|
|
230
|
+
sensitive_topic_exclusions: z3.object({ topics: z3.array(z3.object({ id: z3.string().min(1), filter_option: z3.enum(["STANDARD", "LIMITED", "PARTIAL", "RESTRICTED"]) }).strict()).optional(), filter_option: z3.enum(["STANDARD", "LIMITED", "PARTIAL", "RESTRICTED"]).optional() }).strict().refine((v) => Boolean(v.topics) !== Boolean(v.filter_option), "Choose topics or a global filter").optional(),
|
|
231
|
+
user_day_parts: z3.array(z3.object({ day_of_week: z3.array(z3.enum(["SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY"])), hour_of_day: z3.array(z3.object({ min: z3.number().int().min(0).max(23), max: z3.number().int().min(0).max(23) }).refine((v) => v.max >= v.min)) }).strict()).optional()
|
|
232
|
+
}).strict();
|
|
233
|
+
var campaignPatch = z3.object({ name: z3.string().trim().min(2).max(200).optional(), purchase_order: z3.string().min(2).max(45).optional(), delivery_goal_group: z3.enum(["AWARENESS", "WEBSITE_TRAFFIC", "APP_PROMOTION", "ENGAGEMENT_ON_SPOTIFY", "LEAD_GEN", "VIDEO_VIEWS"]).optional(), status: z3.enum(["PAUSED", "ACTIVE", "ARCHIVED"]).optional() }).strict();
|
|
234
|
+
var groupPatch = z3.object({
|
|
235
|
+
name: z3.string().trim().min(2).max(200).optional(),
|
|
236
|
+
start_time: z3.iso.datetime().optional(),
|
|
237
|
+
end_time: z3.iso.datetime().optional(),
|
|
238
|
+
budget: budgetSchema.optional(),
|
|
239
|
+
bid_micro_amount: money.optional(),
|
|
240
|
+
bid_strategy: bidStrategy.optional(),
|
|
241
|
+
targets: targets.optional(),
|
|
242
|
+
category: z3.string().regex(/^ADV_\d+_\d+$/).optional(),
|
|
243
|
+
asset_format: assetFormat.optional(),
|
|
244
|
+
delivery_goal: deliveryGoal.optional(),
|
|
245
|
+
pacing: z3.enum(["PACING_ASAP", "PACING_EVEN"]).optional(),
|
|
246
|
+
frequency_caps: frequencyCaps.optional(),
|
|
247
|
+
dataset_id: spotifyId.optional(),
|
|
248
|
+
mobile_app_id: spotifyId.optional()
|
|
249
|
+
}).strict();
|
|
250
|
+
var adPatch = z3.object({
|
|
251
|
+
name: z3.string().trim().min(2).max(200).optional(),
|
|
252
|
+
advertiser_name: z3.string().min(1).max(200).optional(),
|
|
253
|
+
tagline: z3.string().min(1).max(200).optional(),
|
|
254
|
+
assets: z3.object({ asset_id: spotifyId.optional(), logo_asset_id: spotifyId.optional(), companion_asset_id: spotifyId.optional(), canvas_asset_id: spotifyId.optional() }).strict().optional(),
|
|
255
|
+
asset_format: assetFormat.optional(),
|
|
256
|
+
call_to_action: z3.object({ key: z3.enum(["APPLY_NOW", "BOOK_NOW", "BUY_NOW", "BUY_TICKETS", "CLICK_NOW", "DOWNLOAD", "FIND_STORES", "GET_COUPON", "GET_INFO", "INSTALL_NOW", "LEARN_MORE", "LISTEN_NOW", "MORE_INFO", "ORDER_NOW", "PRE_SAVE", "SAVE_NOW", "SHARE", "SHOP_NOW", "SIGN_UP", "VISIT_PROFILE", "VISIT_SITE", "WATCH_NOW"]).optional(), language: adLanguage.optional(), clickthrough_url: url.optional() }).strict().optional(),
|
|
257
|
+
third_party_tracking: z3.array(z3.object({ measurement_partner: z3.enum(["IAS", "DCM", "UNSET"]), url }).strict()).max(11).optional(),
|
|
258
|
+
weight: z3.number().int().min(1).max(100).optional()
|
|
259
|
+
}).strict();
|
|
260
|
+
var createGroup = groupPatch.extend({ campaign_id: spotifyId, name: z3.string().trim().min(2).max(200) });
|
|
261
|
+
var createAd = adPatch.extend({ ad_set_id: spotifyId, name: z3.string().trim().min(2).max(200) });
|
|
262
|
+
var draftEntity = z3.enum(["campaigns", "ad_sets", "ads"]);
|
|
263
|
+
var draftMutation = z3.object({ entity: draftEntity, draft_id: spotifyId });
|
|
264
|
+
var updateCampaign = campaignPatch.extend({ draft_id: spotifyId }).refine((v) => Object.keys(v).length > 1, "Provide a change");
|
|
265
|
+
var updateGroup = groupPatch.extend({ draft_id: spotifyId }).refine((v) => Object.keys(v).length > 1, "Provide a change");
|
|
266
|
+
var updateAd = adPatch.extend({ draft_id: spotifyId }).refine((v) => Object.keys(v).length > 1, "Provide a change");
|
|
267
|
+
var publishDraft = z3.object({ draft_campaign_id: spotifyId, draft_hierarchy_version: z3.number().int().positive(), acknowledge_active_publication: z3.literal(true).optional().describe("Required for publication when policy permits active creation. Spotify publishes ACTIVE even when the draft is PAUSED.") });
|
|
268
|
+
var createAsset = z3.object({ name: z3.string().trim().min(2).max(120), asset_type: assetType, asset_subtype: z3.enum(["BACKGROUND_MUSIC", "USER_UPLOADED_AUDIO"]).optional() }).refine((v) => !v.asset_subtype || v.asset_type === "AUDIO", "Asset subtype is audio-only");
|
|
269
|
+
var uploadAsset = z3.object({ asset_id: spotifyId, ...mediaSourceFields }).refine((v) => Number(Boolean(v.media_id)) + Number(Boolean(v.file_path)) === 1, "Choose media_id or file_path");
|
|
270
|
+
var assetResponse = z3.looseObject({ id: spotifyId, name: z3.string(), asset_type: assetType, status: z3.string(), url: z3.string().optional() });
|
|
271
|
+
var draftResponse = z3.looseObject({ id: spotifyId, name: z3.string().nullable().optional(), ad_account_id: spotifyId.nullable().optional(), campaign_id: spotifyId.optional(), ad_set_id: spotifyId.optional(), status: z3.string().nullable().optional(), draft_hierarchy_version: z3.number().int().positive().nullable().optional() });
|
|
272
|
+
|
|
273
|
+
// src/creatives.ts
|
|
274
|
+
var object = z4.record(z4.string(), z4.unknown());
|
|
275
|
+
var paging = z4.looseObject({ offset: z4.number().int().nonnegative(), total_results: z4.number().int().nonnegative() });
|
|
276
|
+
var keys = { campaigns: "campaign_drafts", ad_sets: "ad_set_drafts", ads: "ad_drafts" };
|
|
277
|
+
var SpotifyCreativeService = class {
|
|
278
|
+
constructor(client, media) {
|
|
279
|
+
this.client = client;
|
|
280
|
+
this.media = media;
|
|
281
|
+
}
|
|
282
|
+
client;
|
|
283
|
+
media;
|
|
284
|
+
base(account3) {
|
|
285
|
+
return `ad_accounts/${spotifyId.parse(account3)}`;
|
|
286
|
+
}
|
|
287
|
+
async page(input, path, key, params2 = {}) {
|
|
288
|
+
const data = await this.client.get(`${this.base(input.account_id)}/${path}`, z4.looseObject({ paging }), query({ limit: input.limit, offset: input.offset, ...params2 }));
|
|
289
|
+
if (data.paging.offset !== input.offset) throw new AdportError2("PROVIDER_ERROR", "spotify: pagination offset mismatch");
|
|
290
|
+
const rows = z4.array(draftResponse).parse(data[key]);
|
|
291
|
+
for (const row of rows) this.checkAccount(input.account_id, row);
|
|
292
|
+
const next = input.offset + rows.length, truncated = next < data.paging.total_results;
|
|
293
|
+
if (truncated && !rows.length) throw new AdportError2("PROVIDER_ERROR", "spotify: pagination stalled");
|
|
294
|
+
return { ...data, truncated, ...truncated ? { next_offset: next } : {} };
|
|
295
|
+
}
|
|
296
|
+
async drafts(input) {
|
|
297
|
+
return this.page(input, `drafts/${input.entity}`, keys[input.entity], { campaign_ids: input.campaign_ids, ad_set_ids: input.ad_set_ids });
|
|
298
|
+
}
|
|
299
|
+
async get(account3, entity, id, draft = true) {
|
|
300
|
+
const row = await this.getOwned(account3, entity, id, draft);
|
|
301
|
+
if (entity === "ad_sets") await this.get(account3, "campaigns", spotifyId.parse(row.campaign_id), draft);
|
|
302
|
+
else if (entity === "ads") await this.get(account3, "ad_sets", spotifyId.parse(row.ad_set_id), draft);
|
|
303
|
+
return row;
|
|
304
|
+
}
|
|
305
|
+
async getOwned(account3, entity, id, draft = true) {
|
|
306
|
+
const row = await this.client.get(`${this.base(account3)}/${draft ? "drafts/" : ""}${entity}/${spotifyId.parse(id)}`, draftResponse);
|
|
307
|
+
if (row.id !== id) throw new AdportError2("PROVIDER_ERROR", "spotify: response ID mismatch");
|
|
308
|
+
this.checkAccount(account3, row);
|
|
309
|
+
if (entity === "campaigns") {
|
|
310
|
+
if (draft && row.ad_account_id !== account3) throw new AdportError2("PROVIDER_ERROR", "spotify: campaign account mismatch");
|
|
311
|
+
if (!draft && row.ad_account_id == null) await this.verifyPublishedCampaign(account3, id);
|
|
312
|
+
}
|
|
313
|
+
return row;
|
|
314
|
+
}
|
|
315
|
+
checkAccount(account3, row) {
|
|
316
|
+
if (row.ad_account_id != null && row.ad_account_id !== account3) throw new AdportError2("PROVIDER_ERROR", "spotify: resource belongs to another account");
|
|
317
|
+
}
|
|
318
|
+
async verifyPublishedCampaign(account3, id) {
|
|
319
|
+
for (let page3 = 0, offset = 0; page3 < 1e3; page3++) {
|
|
320
|
+
const data = await this.page({ account_id: account3, limit: 50, offset }, "campaigns", "campaigns", { sort_field: "ID", sort_direction: "ASC" });
|
|
321
|
+
if (data.campaigns.some((campaign) => campaign.id === id)) return;
|
|
322
|
+
if (!data.truncated) break;
|
|
323
|
+
offset = data.next_offset;
|
|
324
|
+
}
|
|
325
|
+
throw new AdportError2("INVALID_INPUT", "spotify: campaign is not present in the selected account\u2019s published campaign list");
|
|
326
|
+
}
|
|
327
|
+
async assets(input) {
|
|
328
|
+
const data = await this.client.get(`${this.base(input.account_id)}/assets`, z4.looseObject({ paging, assets: z4.array(assetResponse) }), query({ limit: input.limit, offset: input.offset, asset_types: input.asset_types, asset_statuses: input.asset_statuses, name: input.name }));
|
|
329
|
+
if (data.paging.offset !== input.offset) throw new AdportError2("PROVIDER_ERROR", "spotify: asset pagination offset mismatch");
|
|
330
|
+
for (const asset of data.assets) this.checkAccount(input.account_id, asset);
|
|
331
|
+
const next = input.offset + data.assets.length, truncated = next < data.paging.total_results;
|
|
332
|
+
if (truncated && !data.assets.length) throw new AdportError2("PROVIDER_ERROR", "spotify: asset pagination stalled");
|
|
333
|
+
const creatives = data.assets.map((asset) => ({ id: asset.id, provider: "spotify", account_id: input.account_id, name: asset.name, type: asset.asset_type, status: asset.status, headlines: [], descriptions: [], landing_urls: [], media: mediaFor(asset), actions: [] }));
|
|
334
|
+
return { ...data, creatives, truncated, ...truncated ? { next_offset: next } : {} };
|
|
335
|
+
}
|
|
336
|
+
async asset(account3, id) {
|
|
337
|
+
const asset = await this.client.get(`${this.base(account3)}/assets/${spotifyId.parse(id)}`, assetResponse);
|
|
338
|
+
if (asset.id !== id) throw new AdportError2("PROVIDER_ERROR", "spotify: asset response ID mismatch");
|
|
339
|
+
this.checkAccount(account3, asset);
|
|
340
|
+
return asset;
|
|
341
|
+
}
|
|
342
|
+
async ads(input) {
|
|
343
|
+
const data = await this.page(input, `${input.draft ? "drafts/" : ""}ads`, input.draft ? "ad_drafts" : "ads", { ad_set_ids: input.ad_set_ids });
|
|
344
|
+
const rows = data[input.draft ? "ad_drafts" : "ads"];
|
|
345
|
+
const cache = /* @__PURE__ */ new Map();
|
|
346
|
+
const creatives = [];
|
|
347
|
+
for (const ad of rows) {
|
|
348
|
+
const assets = record(ad.assets), media = [];
|
|
349
|
+
for (const id of new Set(Object.values(assets).filter((value) => typeof value === "string" && spotifyId.safeParse(value).success))) {
|
|
350
|
+
if (!cache.has(id)) cache.set(id, await this.asset(input.account_id, id));
|
|
351
|
+
media.push(...mediaFor(cache.get(id)));
|
|
352
|
+
}
|
|
353
|
+
const args = { account_id: input.account_id, draft_id: ad.id };
|
|
354
|
+
creatives.push({
|
|
355
|
+
id: String(ad.id),
|
|
356
|
+
provider: "spotify",
|
|
357
|
+
account_id: input.account_id,
|
|
358
|
+
name: String(ad.name ?? ad.id),
|
|
359
|
+
type: input.draft ? "DRAFT_AD" : "AD",
|
|
360
|
+
...typeof ad.status === "string" ? { status: ad.status } : {},
|
|
361
|
+
...typeof ad.ad_set_id === "string" ? { ad_group_id: ad.ad_set_id } : {},
|
|
362
|
+
headlines: typeof ad.advertiser_name === "string" ? [ad.advertiser_name] : [],
|
|
363
|
+
descriptions: typeof ad.tagline === "string" ? [ad.tagline] : [],
|
|
364
|
+
landing_urls: safeUrl(record(ad.call_to_action).clickthrough_url),
|
|
365
|
+
media,
|
|
366
|
+
actions: input.draft ? [{ label: "Edit draft copy", tool: "spotify_update_draft_ad", arguments: args, fields: [{ key: "name", label: "Ad name", type: "text", value: String(ad.name ?? ""), max_length: 200 }, ...typeof ad.tagline === "string" ? [{ key: "tagline", label: "Tagline", type: "text", value: ad.tagline, max_length: 200 }] : []] }] : [{ label: "Stage a draft for editing", tool: "spotify_create_draft_from_published", arguments: { account_id: input.account_id, entity: "ads", draft_id: ad.id }, fields: [] }]
|
|
367
|
+
});
|
|
368
|
+
}
|
|
369
|
+
return { ...data, creatives };
|
|
370
|
+
}
|
|
371
|
+
async read(account3, path, params2 = {}) {
|
|
372
|
+
return this.client.get(`${this.base(account3)}/${path}`, object, query(params2));
|
|
373
|
+
}
|
|
374
|
+
async targeting(input) {
|
|
375
|
+
const { account_id, kind, ...params2 } = input;
|
|
376
|
+
return this.client.get(`targets/${kind}`, object, query({ ...params2, ...kind === "languages" ? { ad_account_id: account_id } : {} }));
|
|
377
|
+
}
|
|
378
|
+
async categories(q) {
|
|
379
|
+
return this.client.get("ad_categories", object, query({ q }));
|
|
380
|
+
}
|
|
381
|
+
async estimate(kind, input) {
|
|
382
|
+
const { account_id, ...body } = input;
|
|
383
|
+
return this.client.mutate(`estimates/${kind}`, "POST", { ...body, ...kind === "audience" ? { ad_account_id: account_id } : {} }, object);
|
|
384
|
+
}
|
|
385
|
+
async validate(account3, id, version) {
|
|
386
|
+
const campaign = await this.get(account3, "campaigns", id);
|
|
387
|
+
this.version(campaign, version);
|
|
388
|
+
return this.client.mutate(`${this.base(account3)}/drafts/campaigns/${id}`, "POST", { action: "VALIDATE", draft_hierarchy_version: version }, object);
|
|
389
|
+
}
|
|
390
|
+
version(campaign, version) {
|
|
391
|
+
if (campaign.draft_hierarchy_version !== version) throw new AdportError2("PENDING_MISMATCH", "spotify: draft hierarchy changed. Read its current version and prepare a new preview.");
|
|
392
|
+
}
|
|
393
|
+
async allDrafts(account3, entity, campaign) {
|
|
394
|
+
const rows = [], seen = /* @__PURE__ */ new Set();
|
|
395
|
+
for (let page3 = 0, offset = 0; page3 < 1e3; page3++) {
|
|
396
|
+
const data = await this.drafts({ account_id: account3, entity, campaign_ids: [campaign], limit: 50, offset });
|
|
397
|
+
const nextRows = data[keys[entity]];
|
|
398
|
+
for (const row of nextRows) {
|
|
399
|
+
if (seen.has(String(row.id))) throw new AdportError2("PROVIDER_ERROR", "spotify: repeated draft resource");
|
|
400
|
+
seen.add(String(row.id));
|
|
401
|
+
rows.push(row);
|
|
402
|
+
}
|
|
403
|
+
if (!data.truncated) return rows;
|
|
404
|
+
offset = data.next_offset;
|
|
405
|
+
}
|
|
406
|
+
throw new AdportError2("PROVIDER_ERROR", "spotify: draft hierarchy pagination did not terminate");
|
|
407
|
+
}
|
|
408
|
+
async plan(op, guard) {
|
|
409
|
+
const base = this.base(op.accountId), coercions = [], budgetDeltas = [];
|
|
410
|
+
let path, body, method = "PATCH", expectedId;
|
|
411
|
+
const payload = op.payload;
|
|
412
|
+
switch (op.tool) {
|
|
413
|
+
case "spotify_create_draft_ad_set": {
|
|
414
|
+
const input = createGroup.parse(payload);
|
|
415
|
+
await this.get(op.accountId, "campaigns", input.campaign_id);
|
|
416
|
+
body = input;
|
|
417
|
+
path = `${base}/drafts/ad_sets`;
|
|
418
|
+
method = "POST";
|
|
419
|
+
checkGroup(body);
|
|
420
|
+
monetaryDeltas(body, {}, `draft ad set ${input.name}`, budgetDeltas);
|
|
421
|
+
break;
|
|
422
|
+
}
|
|
423
|
+
case "spotify_create_draft_ad": {
|
|
424
|
+
const input = createAd.parse(payload);
|
|
425
|
+
await this.get(op.accountId, "ad_sets", input.ad_set_id);
|
|
426
|
+
await this.verifyAssets(op.accountId, input.assets);
|
|
427
|
+
body = input;
|
|
428
|
+
path = `${base}/drafts/ads`;
|
|
429
|
+
method = "POST";
|
|
430
|
+
break;
|
|
431
|
+
}
|
|
432
|
+
case "spotify_update_draft_campaign":
|
|
433
|
+
case "spotify_update_draft_ad_set":
|
|
434
|
+
case "spotify_update_draft_ad": {
|
|
435
|
+
const entity = op.tool === "spotify_update_draft_campaign" ? "campaigns" : op.tool === "spotify_update_draft_ad_set" ? "ad_sets" : "ads";
|
|
436
|
+
const input = (entity === "campaigns" ? updateCampaign : entity === "ad_sets" ? updateGroup : updateAd).parse(payload);
|
|
437
|
+
const { draft_id, ...fields } = input;
|
|
438
|
+
const current = await this.get(op.accountId, entity, draft_id);
|
|
439
|
+
body = { ...fields };
|
|
440
|
+
expectedId = draft_id;
|
|
441
|
+
if (body.targets !== void 0) body.targets = { ...record(current.targets), ...record(body.targets) };
|
|
442
|
+
for (const key of ["assets", "call_to_action"]) if (body[key] !== void 0) {
|
|
443
|
+
const writable = key === "assets" ? ["asset_id", "logo_asset_id", "companion_asset_id", "canvas_asset_id"] : ["key", "language", "clickthrough_url"];
|
|
444
|
+
body[key] = { ...Object.fromEntries(Object.entries(record(current[key])).filter(([field, value]) => writable.includes(field) && value !== null)), ...record(body[key]) };
|
|
445
|
+
}
|
|
446
|
+
if (entity === "ad_sets") {
|
|
447
|
+
checkGroup({ ...current, ...body });
|
|
448
|
+
monetaryDeltas(body, current, `draft ad set ${draft_id}`, budgetDeltas);
|
|
449
|
+
}
|
|
450
|
+
if (entity === "ads") await this.verifyAssets(op.accountId, body.assets);
|
|
451
|
+
path = `${base}/drafts/${entity}/${draft_id}`;
|
|
452
|
+
break;
|
|
453
|
+
}
|
|
454
|
+
case "spotify_create_draft_from_published": {
|
|
455
|
+
const input = draftMutation.parse(payload);
|
|
456
|
+
await this.get(op.accountId, input.entity, input.draft_id, false);
|
|
457
|
+
try {
|
|
458
|
+
await this.get(op.accountId, input.entity, input.draft_id);
|
|
459
|
+
throw new AdportError2("INVALID_INPUT", "spotify: a draft already exists. Read and edit it instead of overwriting pending changes.");
|
|
460
|
+
} catch (error) {
|
|
461
|
+
if (!isNotFound(error)) throw error;
|
|
462
|
+
}
|
|
463
|
+
path = `${base}/${input.entity}/${input.draft_id}/drafts`;
|
|
464
|
+
method = "POST";
|
|
465
|
+
expectedId = input.draft_id;
|
|
466
|
+
body = {};
|
|
467
|
+
break;
|
|
468
|
+
}
|
|
469
|
+
case "spotify_delete_draft": {
|
|
470
|
+
const input = draftMutation.parse(payload);
|
|
471
|
+
const current = await this.getOwned(op.accountId, input.entity, input.draft_id);
|
|
472
|
+
if (input.entity === "campaigns") {
|
|
473
|
+
const groups = await this.allDrafts(op.accountId, "ad_sets", input.draft_id);
|
|
474
|
+
for (const group of groups) await this.ensureNoAdDrafts(op.accountId, String(group.id));
|
|
475
|
+
} else if (input.entity === "ad_sets") await this.ensureNoAdDrafts(op.accountId, input.draft_id);
|
|
476
|
+
return { summary: `Delete Spotify draft ${input.entity}/${input.draft_id}`, changes: [`- ${current.name ?? current.id}; draft children may also be deleted. Published entities remain unchanged.`], coercions, budgetDeltas, execute: async () => {
|
|
477
|
+
await this.client.mutate(`${base}/drafts/${input.entity}/${input.draft_id}`, "DELETE", void 0, z4.undefined());
|
|
478
|
+
return [input.draft_id];
|
|
479
|
+
} };
|
|
480
|
+
}
|
|
481
|
+
case "spotify_delete_draft_ads":
|
|
482
|
+
case "spotify_delete_draft_ad_sets": {
|
|
483
|
+
const ads = op.tool === "spotify_delete_draft_ads", entity = ads ? "ads" : "ad_sets";
|
|
484
|
+
const input = z4.object({ draft_ids: z4.array(spotifyId).min(1).max(ads ? 100 : 40).refine((ids2) => new Set(ids2).size === ids2.length, "IDs must be unique") }).parse(payload);
|
|
485
|
+
for (const id of input.draft_ids) {
|
|
486
|
+
await this.getOwned(op.accountId, entity, id);
|
|
487
|
+
if (!ads) await this.ensureNoAdDrafts(op.accountId, id);
|
|
488
|
+
}
|
|
489
|
+
return { summary: `Delete ${input.draft_ids.length} Spotify ${entity} drafts`, changes: input.draft_ids.map((id) => `- draft ${id}${ads ? "" : " and child ad drafts"}; published entities remain unchanged`), coercions, budgetDeltas, execute: async () => {
|
|
490
|
+
await this.client.mutate(`${base}/drafts/${entity}`, "DELETE", void 0, z4.undefined(), query({ [ads ? "ad_draft_ids" : "ad_set_draft_ids"]: input.draft_ids }));
|
|
491
|
+
return input.draft_ids;
|
|
492
|
+
} };
|
|
493
|
+
}
|
|
494
|
+
case "spotify_publish_draft":
|
|
495
|
+
return this.publish(op, guard);
|
|
496
|
+
case "spotify_create_asset": {
|
|
497
|
+
const input = createAsset.parse(payload);
|
|
498
|
+
return { summary: `Create Spotify ${input.asset_type} asset metadata`, changes: [`+ ${JSON.stringify(input)}; file upload is a separate approved operation`], coercions, budgetDeltas, execute: async () => {
|
|
499
|
+
const asset = await this.client.mutate(`${base}/assets`, "POST", input, assetResponse);
|
|
500
|
+
this.checkAccount(op.accountId, asset);
|
|
501
|
+
if (asset.asset_type !== input.asset_type) throw new AdportError2("PROVIDER_ERROR", "spotify: created asset type mismatch; inspect before retrying");
|
|
502
|
+
return [asset.id];
|
|
503
|
+
} };
|
|
504
|
+
}
|
|
505
|
+
case "spotify_rename_asset": {
|
|
506
|
+
const input = z4.object({ asset_id: spotifyId, name: z4.string().trim().min(2).max(120) }).parse(payload);
|
|
507
|
+
const current = await this.asset(op.accountId, input.asset_id);
|
|
508
|
+
return { summary: "Rename Spotify asset", changes: [`~ ${current.id} name: ${current.name} \u2192 ${input.name}`], coercions, budgetDeltas, execute: async () => {
|
|
509
|
+
const result = await this.client.mutate(`${base}/assets/${current.id}`, "PATCH", { asset_type: current.asset_type, name: input.name }, assetResponse);
|
|
510
|
+
if (result.id !== current.id || result.name !== input.name) throw new AdportError2("PROVIDER_ERROR", "spotify: asset update response mismatch");
|
|
511
|
+
return [current.id];
|
|
512
|
+
} };
|
|
513
|
+
}
|
|
514
|
+
case "spotify_upload_asset":
|
|
515
|
+
return this.upload(op);
|
|
516
|
+
default:
|
|
517
|
+
throw new AdportError2("INVALID_INPUT", `spotify: unsupported write ${op.tool}`);
|
|
518
|
+
}
|
|
519
|
+
const parent = body.campaign_id ?? body.ad_set_id;
|
|
520
|
+
return { summary: `Spotify ${op.tool.replace(/^spotify_/, "").replaceAll("_", " ")}`, changes: [`${method} /${path} ${JSON.stringify(body)}`], coercions, budgetDeltas, execute: async () => {
|
|
521
|
+
const result = await this.client.mutate(path, method, op.tool === "spotify_create_draft_from_published" ? void 0 : body, draftResponse);
|
|
522
|
+
this.checkAccount(op.accountId, result);
|
|
523
|
+
if (expectedId && result.id !== expectedId || parent && parent !== (result.campaign_id ?? result.ad_set_id)) throw new AdportError2("PROVIDER_ERROR", "spotify: draft mutation response mismatch; inspect before retrying");
|
|
524
|
+
return [result.id];
|
|
525
|
+
} };
|
|
526
|
+
}
|
|
527
|
+
async verifyAssets(account3, assets) {
|
|
528
|
+
for (const value of Object.values(record(assets))) await this.asset(account3, spotifyId.parse(value));
|
|
529
|
+
}
|
|
530
|
+
async ensureNoAdDrafts(account3, group) {
|
|
531
|
+
const data = await this.drafts({ account_id: account3, entity: "ads", ad_set_ids: [group], limit: 1, offset: 0 });
|
|
532
|
+
if (data.ad_drafts.length || data.truncated) throw new AdportError2("INVALID_INPUT", "spotify: delete draft ads before deleting their parent. Spotify can otherwise leave undeletable orphan ad drafts.");
|
|
533
|
+
}
|
|
534
|
+
async publish(op, guard) {
|
|
535
|
+
if (guard.forcePausedCreation) throw new AdportError2("POLICY_VIOLATION", "spotify: publication is blocked by paused_creation. The live PUBLISH endpoint activates even a PAUSED draft; Spotify cannot guarantee paused publication. Keep this hierarchy as a draft.");
|
|
536
|
+
const input = publishDraft.parse(op.payload), account3 = op.accountId;
|
|
537
|
+
if (!input.acknowledge_active_publication) throw new AdportError2("INVALID_INPUT", "spotify: publishing activates the campaign. Explicit acknowledge_active_publication=true is required.");
|
|
538
|
+
const campaign = await this.get(account3, "campaigns", input.draft_campaign_id);
|
|
539
|
+
this.version(campaign, input.draft_hierarchy_version);
|
|
540
|
+
const groups = await this.allDrafts(account3, "ad_sets", campaign.id);
|
|
541
|
+
const budgetDeltas = [];
|
|
542
|
+
for (const group of groups) {
|
|
543
|
+
if (group.campaign_id !== campaign.id) throw new AdportError2("PROVIDER_ERROR", "spotify: draft ad set belongs to another campaign");
|
|
544
|
+
let current = {};
|
|
545
|
+
try {
|
|
546
|
+
current = await this.get(account3, "ad_sets", String(group.id), false);
|
|
547
|
+
} catch (error) {
|
|
548
|
+
if (!isNotFound(error)) throw error;
|
|
549
|
+
}
|
|
550
|
+
monetaryDeltas(group, current, `publish ad set ${group.id}`, budgetDeltas);
|
|
551
|
+
}
|
|
552
|
+
return { summary: `Publish Spotify campaign ${campaign.name ?? campaign.id} as ACTIVE`, changes: [`PUBLISH hierarchy version ${input.draft_hierarchy_version}; ${groups.length} draft ad sets. Spotify changes campaign status ${campaign.status} \u2192 ACTIVE, regardless of the draft's paused state.`], coercions: [], budgetDeltas, execute: async () => {
|
|
553
|
+
const validation = await this.validate(account3, campaign.id, input.draft_hierarchy_version);
|
|
554
|
+
assertValidation(validation);
|
|
555
|
+
const result = await this.client.mutate(`${this.base(account3)}/drafts/campaigns/${campaign.id}`, "POST", { action: "PUBLISH", draft_hierarchy_version: input.draft_hierarchy_version }, object);
|
|
556
|
+
assertValidation(result);
|
|
557
|
+
const published = record(result.campaign);
|
|
558
|
+
if (published.id !== campaign.id || published.ad_account_id != null && published.ad_account_id !== account3 || published.status !== "ACTIVE") throw new AdportError2("PROVIDER_ERROR", "spotify: publish receipt does not confirm the expected campaign/account/status. Inspect before retrying.", { resource_ids: spotifyId.safeParse(published.id).success ? [published.id] : [], observed_status: published.status });
|
|
559
|
+
if (published.ad_account_id == null) await this.verifyPublishedCampaign(account3, campaign.id);
|
|
560
|
+
return [campaign.id];
|
|
561
|
+
} };
|
|
562
|
+
}
|
|
563
|
+
async upload(op) {
|
|
564
|
+
const input = uploadAsset.parse(op.payload), current = await this.asset(op.accountId, input.asset_id);
|
|
565
|
+
if (current.status !== "WAITING_UPLOAD") throw new AdportError2("INVALID_INPUT", "spotify: upload only to a new WAITING_UPLOAD asset. Create a separate asset instead of replacing media used by ads.");
|
|
566
|
+
const types = { IMAGE: ["image/png", "image/jpeg"], AUDIO: ["audio/mpeg", "audio/wav", "audio/ogg"], VIDEO: ["video/mp4", "video/quicktime"] };
|
|
567
|
+
const file = await this.media.read(input, { maxBytes: 100 * 1024 * 1024, contentTypes: types[current.asset_type] });
|
|
568
|
+
const path = `${this.base(op.accountId)}/assets/${current.id}`;
|
|
569
|
+
return { summary: `Upload Spotify ${current.asset_type} asset ${current.name}`, changes: [`+ ${file.name}; ${file.bytes.byteLength} bytes; SHA-256 ${file.sha256}; existing ads are unchanged`], coercions: [], budgetDeltas: [], execute: async () => {
|
|
570
|
+
let result;
|
|
571
|
+
if (file.bytes.byteLength <= 2e7) {
|
|
572
|
+
result = await this.client.upload(`${path}/upload`, form(file.bytes, file.name, file.contentType, { asset_type: current.asset_type }), assetResponse);
|
|
573
|
+
} else {
|
|
574
|
+
const session = await this.client.mutate(`${path}/chunked_upload/start`, "POST", void 0, z4.object({ upload_session_id: spotifyId, max_chunk_size_mb: z4.number().int().positive().max(100) }));
|
|
575
|
+
const size = session.max_chunk_size_mb * 1e6, sections = Math.ceil(file.bytes.byteLength / size);
|
|
576
|
+
if (sections > 1e3) throw new AdportError2("PROVIDER_ERROR", "spotify: upload requires too many chunks");
|
|
577
|
+
for (let index = 0; index < sections; index++) {
|
|
578
|
+
const reply = await this.client.upload(`${path}/chunked_upload/transfer`, form(file.bytes.slice(index * size, (index + 1) * size), file.name, file.contentType, { asset_type: current.asset_type, upload_session_id: session.upload_session_id, upload_section: String(index + 1) }), z4.object({ success: z4.boolean() }));
|
|
579
|
+
if (!reply.success) throw new AdportError2("PROVIDER_ERROR", `spotify: upload section ${index + 1} failed. Inspect the asset before retrying.`);
|
|
580
|
+
}
|
|
581
|
+
result = await this.client.mutate(`${path}/chunked_upload/complete`, "POST", { asset_type: current.asset_type, upload_session_id: session.upload_session_id, number_of_sections: sections }, assetResponse);
|
|
582
|
+
}
|
|
583
|
+
if (result.id !== current.id || result.asset_type !== current.asset_type || result.status === "ERROR") throw new AdportError2("PROVIDER_ERROR", "spotify: uploaded asset response mismatch/error; inspect before retrying");
|
|
584
|
+
return [current.id];
|
|
585
|
+
} };
|
|
586
|
+
}
|
|
587
|
+
};
|
|
588
|
+
function record(value) {
|
|
589
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
590
|
+
}
|
|
591
|
+
function query(input) {
|
|
592
|
+
const params2 = new URLSearchParams();
|
|
593
|
+
for (const [key, value] of Object.entries(input)) if (value !== void 0) {
|
|
594
|
+
if (Array.isArray(value)) for (const item of value) params2.append(key, String(item));
|
|
595
|
+
else params2.set(key, String(value));
|
|
596
|
+
}
|
|
597
|
+
return params2;
|
|
598
|
+
}
|
|
599
|
+
function safeUrl(value) {
|
|
600
|
+
if (typeof value !== "string") return [];
|
|
601
|
+
try {
|
|
602
|
+
const url2 = new URL(value);
|
|
603
|
+
return ["https:", "http:"].includes(url2.protocol) && !url2.username && !url2.password ? [value] : [];
|
|
604
|
+
} catch {
|
|
605
|
+
return [];
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
function mediaFor(asset) {
|
|
609
|
+
return safeUrl(asset.url).filter((url2) => url2.startsWith("https:")).map((url2) => ({ type: asset.asset_type === "IMAGE" ? "image" : asset.asset_type === "VIDEO" ? "video" : "audio", url: url2 }));
|
|
610
|
+
}
|
|
611
|
+
function isNotFound(error) {
|
|
612
|
+
return error instanceof AdportError2 && record(error.details).http_status === 404;
|
|
613
|
+
}
|
|
614
|
+
function form(bytes, name2, type, fields) {
|
|
615
|
+
const data = new FormData();
|
|
616
|
+
for (const [key, value] of Object.entries(fields)) data.set(key, value);
|
|
617
|
+
data.set("media", new Blob([bytes], { type }), name2);
|
|
618
|
+
return data;
|
|
619
|
+
}
|
|
620
|
+
function checkGroup(row) {
|
|
621
|
+
const target = record(row.targets), budget = record(row.budget);
|
|
622
|
+
if (row.targets !== void 0 && (!Array.isArray(target.placements) || !target.placements.length)) throw new AdportError2("INVALID_INPUT", "spotify: supplied targeting must include placements");
|
|
623
|
+
if (budget.type === "LIFETIME" && !row.end_time) throw new AdportError2("INVALID_INPUT", "spotify: lifetime budget requires end_time");
|
|
624
|
+
if (row.start_time && row.end_time && String(row.end_time) <= String(row.start_time)) throw new AdportError2("INVALID_INPUT", "spotify: end_time must be after start_time");
|
|
625
|
+
}
|
|
626
|
+
function monetaryDeltas(next, current, target, deltas) {
|
|
627
|
+
if (next.budget !== void 0) {
|
|
628
|
+
const budget = budgetSchema.parse(next.budget), old = current.budget === void 0 ? void 0 : budgetSchema.parse(current.budget);
|
|
629
|
+
if (old && old.type !== budget.type) throw new AdportError2("INVALID_INPUT", "spotify: budget type changes require a separate ad set");
|
|
630
|
+
deltas.push({ target: `${target} ${budget.type} budget`, ...old ? { fromMicros: old.micro_amount } : {}, toMicros: budget.micro_amount });
|
|
631
|
+
}
|
|
632
|
+
if (next.bid_micro_amount !== void 0) {
|
|
633
|
+
const amount = z4.number().int().nonnegative().safe().parse(next.bid_micro_amount);
|
|
634
|
+
const old = current.bid_micro_amount === void 0 ? void 0 : z4.number().int().nonnegative().safe().parse(current.bid_micro_amount);
|
|
635
|
+
deltas.push({ target: `${target} bid`, ...old !== void 0 ? { fromMicros: old } : {}, toMicros: amount });
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
function assertValidation(result) {
|
|
639
|
+
if (result.validation_errors !== void 0 && result.validation_errors !== null && !Array.isArray(result.validation_errors)) throw new AdportError2("PROVIDER_ERROR", "spotify: malformed draft validation result");
|
|
640
|
+
if (Array.isArray(result.validation_errors) && result.validation_errors.length) throw new AdportError2("PROVIDER_ERROR", "spotify: draft hierarchy failed validation; nothing was published", { validation_errors: result.validation_errors });
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
// src/management.ts
|
|
644
|
+
import { AdportError as AdportError3 } from "@adport/core";
|
|
645
|
+
import { z as z6 } from "zod";
|
|
646
|
+
|
|
647
|
+
// src/management-tools.ts
|
|
648
|
+
import { defineTool, guardedWriteTool } from "@adport/core";
|
|
649
|
+
import { z as z5 } from "zod";
|
|
650
|
+
var account = { account_id: spotifyId };
|
|
651
|
+
var page = { limit: z5.number().int().positive().max(50).default(50), offset: z5.number().int().nonnegative().default(0) };
|
|
652
|
+
var ids = z5.array(spotifyId).min(1).max(100);
|
|
653
|
+
var nativeFields = z5.array(z5.string().regex(/^[A-Z][A-Z0-9_]*$/)).min(1).max(100);
|
|
654
|
+
var insightDimension = z5.enum(["ACT_AND_SET", "AGE", "AUDIENCE", "CITY", "COUNTRY", "DEVICE_TYPE", "FORMAT", "GENDER", "GENRE", "INTERESTS", "METRO", "PLACEMENT", "PLACEMENT_TYPE", "PLATFORM", "PODCAST_EPISODE_TOPIC", "REGION", "TONE"]);
|
|
655
|
+
var audienceName = z5.string().trim().min(2).max(80);
|
|
656
|
+
var description = z5.string().max(80).optional();
|
|
657
|
+
var reportName = z5.string().trim().min(2).max(120).refine((value) => /^[\p{L}\p{N} _-]+$/u.test(value), "Use letters, numbers, spaces, underscores or hyphens").describe("Unicode letters/numbers, spaces, underscores and hyphens.");
|
|
658
|
+
var createAudience = z5.object({ name: audienceName, description, subtype: z5.enum(["WEB_EVENT", "AD_ENGAGEMENT"]), dataset_ids: ids.optional(), campaign_ids: ids.optional(), ad_set_ids: ids.optional(), included_events: z5.array(z5.string().min(1)).min(1).max(100).optional(), excluded_events: z5.array(z5.string().min(1)).max(100).optional(), lookback_days: z5.union([z5.literal(30), z5.literal(60), z5.literal(90), z5.literal(180)]), exposure_type: z5.enum(["IMPRESSIONS", "CLICKS"]).optional() }).strict().superRefine((value, ctx) => {
|
|
659
|
+
if (value.subtype === "WEB_EVENT" && (!value.dataset_ids || !value.included_events || value.campaign_ids || value.ad_set_ids || value.exposure_type)) ctx.addIssue({ code: "custom", message: "Web-event audiences require datasets and included events, without engagement fields" });
|
|
660
|
+
if (value.subtype === "AD_ENGAGEMENT" && (Boolean(value.campaign_ids) === Boolean(value.ad_set_ids) || !value.exposure_type || value.dataset_ids || value.included_events || value.excluded_events)) ctx.addIssue({ code: "custom", message: "Engagement audiences require campaign_ids or ad_set_ids plus exposure_type, without web-event fields" });
|
|
661
|
+
});
|
|
662
|
+
var createLookalike = z5.object({ name: audienceName, description, seed_audience_id: spotifyId });
|
|
663
|
+
var updateAudience = z5.object({ audience_id: spotifyId, name: audienceName.optional(), description }).refine((v) => v.name !== void 0 || v.description !== void 0, "Provide an audience field");
|
|
664
|
+
var deleteAudience = z5.object({ audience_id: spotifyId });
|
|
665
|
+
var createReport = z5.object({ name: reportName, granularity: z5.enum(["LIFETIME", "DAY"]), dimensions: nativeFields, metrics: nativeFields, statuses: nativeFields.optional(), campaign_ids: ids.optional(), report_start: z5.iso.datetime().optional(), report_end: z5.iso.datetime().optional(), insight_dimension: insightDimension.optional(), attribution_window: z5.enum(["IMPRESSION_30_DAY", "IMPRESSION_7_DAY"]).optional() }).superRefine((value, ctx) => {
|
|
666
|
+
if (value.granularity === "DAY" && (!value.report_start || !value.report_end)) ctx.addIssue({ code: "custom", message: "Daily exports require report_start and report_end" });
|
|
667
|
+
if (value.insight_dimension && (value.granularity !== "LIFETIME" || value.report_start || value.report_end)) ctx.addIssue({ code: "custom", message: "Insight exports require LIFETIME without report dates" });
|
|
668
|
+
if (value.report_start && value.report_end && (Date.parse(value.report_end) < Date.parse(value.report_start) || Date.parse(value.report_end) - Date.parse(value.report_start) > 365 * 864e5)) ctx.addIssue({ code: "custom", message: "Report dates must be ordered and within365 days" });
|
|
669
|
+
if ([value.report_start, value.report_end].some((v) => v && !/T00:00:00Z$/.test(v))) ctx.addIssue({ code: "custom", message: "Use UTC midnight report dates" });
|
|
670
|
+
});
|
|
671
|
+
var managementWriteNames = /* @__PURE__ */ new Set(["spotify_create_audience", "spotify_create_lookalike_audience", "spotify_update_audience", "spotify_delete_audience", "spotify_create_report"]);
|
|
672
|
+
function spotifyManagementTools(provider) {
|
|
673
|
+
const read = (name2, description2, input, handler) => defineTool({ name: name2, namespace: "spotify", description: description2, input, annotations: { readOnly: true }, handler });
|
|
674
|
+
const write = (name2, description2, payload, kind) => guardedWriteTool({ name: name2, namespace: "spotify", provider: "spotify", description: description2, payload, kind });
|
|
675
|
+
return [
|
|
676
|
+
read("spotify_audiences", "Read existing account-owned custom/lookalike audiences with native filters and pagination. Does not upload customer records.", z5.object({ ...account, audience_ids: ids.optional(), audience_types: z5.array(z5.enum(["CUSTOM", "LOOKALIKE"])).optional(), q: z5.string().optional(), ...page }), (input) => provider.management.audiences(input)),
|
|
677
|
+
read("spotify_get_audience", "Read one account-owned custom/lookalike audience and its processing status.", z5.object({ ...account, audience_id: spotifyId }), (input) => provider.management.audience(input.account_id, input.audience_id)),
|
|
678
|
+
read("spotify_audience_datasets", "Read eligible account datasets and available web events for audience creation. Returns native pagination limits.", z5.object({ ...account, q: z5.string().optional(), limit: z5.number().int().positive().max(50).default(50) }), (input) => provider.management.eligibleDatasets(input)),
|
|
679
|
+
read("spotify_insight_report", "Read native lifetime insights for exactly one verified published ad set, as required by the live endpoint. Missing/suppressed conversion fields remain unavailable.", z5.object({ ...account, ad_set_id: spotifyId, insight_dimension: insightDimension, fields: nativeFields, statuses: nativeFields.optional() }), (input) => provider.management.insights(input)),
|
|
680
|
+
read("spotify_change_history", "Read account change history within Spotify\u2019s rolling180-day window. Actor details and billing rows depend on the caller\u2019s role.", z5.object({ ...account, entity_type: z5.enum(["CAMPAIGN", "AD_SET", "AD_ACCOUNT", "BUSINESS", "CREATIVE"]).optional(), entity_ids: ids.optional(), entity_name: z5.string().optional(), created_gte: z5.iso.datetime().optional(), created_lte: z5.iso.datetime().optional(), change_category: z5.enum(["STATUS", "BUDGET", "TARGETING", "CREATIVE", "SCHEDULING", "SETTINGS", "BILLING"]).optional(), sort_direction: z5.enum(["ASC", "DESC"]).default("DESC"), ...page }), (input) => provider.management.read(input, "change_history")),
|
|
681
|
+
read("spotify_report_status", "Read a previously submitted account export\u2019s status and native CSV URL. Does not fetch arbitrary URLs or create a public share.", z5.object({ ...account, report_id: spotifyId }), (input) => provider.management.read({ account_id: input.account_id }, `async_reports/${input.report_id}`)),
|
|
682
|
+
write("spotify_create_audience", "Create a web-event or ad-engagement audience from existing account-owned resources. Does not upload customer records or attach targeting to ads.", createAudience, "create"),
|
|
683
|
+
write("spotify_create_lookalike_audience", "Create a lookalike from an existing account-owned seed audience. Does not upload customer records or change ad targeting.", createLookalike, "create"),
|
|
684
|
+
write("spotify_update_audience", "Rename or edit the description of an account-owned audience, preserving its native type and source rules.", updateAudience, "update"),
|
|
685
|
+
write("spotify_delete_audience", "Delete an account-owned audience through the normal preview/apply gate. Review dependencies before applying.", deleteAudience, "remove"),
|
|
686
|
+
write("spotify_create_report", "Submit a native asynchronous CSV export job. No ad or delivery changes. Native field names are server-validated; use spotify_report_status for completion.", createReport, "create")
|
|
687
|
+
];
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
// src/management.ts
|
|
691
|
+
var object2 = z6.record(z6.string(), z6.unknown());
|
|
692
|
+
var audienceSchema = z6.looseObject({ id: spotifyId, type: z6.enum(["CUSTOM", "LOOKALIKE"]), name: z6.string() });
|
|
693
|
+
function query2(input) {
|
|
694
|
+
const params2 = new URLSearchParams();
|
|
695
|
+
for (const [key, value] of Object.entries(input)) if (value !== void 0) {
|
|
696
|
+
if (Array.isArray(value)) value.forEach((item) => params2.append(key, String(item)));
|
|
697
|
+
else params2.set(key, String(value));
|
|
698
|
+
}
|
|
699
|
+
return params2;
|
|
700
|
+
}
|
|
701
|
+
var SpotifyManagementService = class {
|
|
702
|
+
constructor(client, creatives) {
|
|
703
|
+
this.client = client;
|
|
704
|
+
this.creatives = creatives;
|
|
705
|
+
}
|
|
706
|
+
client;
|
|
707
|
+
creatives;
|
|
708
|
+
base(account3) {
|
|
709
|
+
return `ad_accounts/${spotifyId.parse(account3)}`;
|
|
710
|
+
}
|
|
711
|
+
async read(input, path) {
|
|
712
|
+
const { account_id, ...params2 } = input;
|
|
713
|
+
return this.client.get(`${this.base(account_id)}/${path}`, object2, query2(params2));
|
|
714
|
+
}
|
|
715
|
+
async audiences(input) {
|
|
716
|
+
const { account_id: _account, limit: _limit, offset: _offset, ...params2 } = input;
|
|
717
|
+
return this.creatives.page(input, "audiences", "audiences", params2);
|
|
718
|
+
}
|
|
719
|
+
async insights(input) {
|
|
720
|
+
const { ad_set_id, ...params2 } = input;
|
|
721
|
+
await this.creatives.get(input.account_id, "ad_sets", ad_set_id, false);
|
|
722
|
+
return this.read({ ...params2, entity_ids: [ad_set_id], entity_ids_type: "AD_SET" }, "insight_reports");
|
|
723
|
+
}
|
|
724
|
+
async audience(account3, id) {
|
|
725
|
+
const result = await this.client.get(`${this.base(account3)}/audiences/${spotifyId.parse(id)}`, audienceSchema);
|
|
726
|
+
if (result.id !== id || result.ad_account_id !== void 0 && result.ad_account_id !== account3) throw new AdportError3("PROVIDER_ERROR", "spotify: audience account/ID mismatch");
|
|
727
|
+
return result;
|
|
728
|
+
}
|
|
729
|
+
async eligibleDatasets(input) {
|
|
730
|
+
const result = await this.read(input, "audiences/datasets");
|
|
731
|
+
const data = z6.looseObject({ datasets: z6.array(z6.looseObject({ id: spotifyId })), paging: z6.looseObject({ total_results: z6.number().int().nonnegative(), offset: z6.number().int().nonnegative() }).optional() }).parse(result);
|
|
732
|
+
return { ...data, truncated: data.paging ? data.paging.offset + data.datasets.length < data.paging.total_results : data.datasets.length === input.limit };
|
|
733
|
+
}
|
|
734
|
+
async plan(op) {
|
|
735
|
+
const base = this.base(op.accountId);
|
|
736
|
+
let path, method = "POST", body, expected;
|
|
737
|
+
switch (op.tool) {
|
|
738
|
+
case "spotify_create_report": {
|
|
739
|
+
const input = createReport.parse(op.payload);
|
|
740
|
+
for (const id of input.campaign_ids ?? []) await this.creatives.get(op.accountId, "campaigns", id, false);
|
|
741
|
+
return { summary: `Submit Spotify CSV export ${input.name}`, changes: [`+ export job ${JSON.stringify(input)}; no ad delivery changes`], coercions: [], budgetDeltas: [], execute: async () => {
|
|
742
|
+
const result = await this.client.mutate(`${base}/async_reports`, "POST", input, z6.object({ id: spotifyId }));
|
|
743
|
+
return [result.id];
|
|
744
|
+
} };
|
|
745
|
+
}
|
|
746
|
+
case "spotify_create_audience": {
|
|
747
|
+
const input = createAudience.parse(op.payload);
|
|
748
|
+
if (input.subtype === "WEB_EVENT") {
|
|
749
|
+
const data = await this.eligibleDatasets({ account_id: op.accountId, limit: 50 });
|
|
750
|
+
if (input.dataset_ids.some((id) => !data.datasets.some((dataset) => dataset.id === id))) throw new AdportError3("INVALID_INPUT", "spotify: dataset is not present in the selected account\u2019s eligible audience datasets.");
|
|
751
|
+
}
|
|
752
|
+
for (const id of input.campaign_ids ?? []) await this.creatives.get(op.accountId, "campaigns", id, false);
|
|
753
|
+
for (const id of input.ad_set_ids ?? []) await this.creatives.get(op.accountId, "ad_sets", id, false);
|
|
754
|
+
body = { ...input, audience_type: "CUSTOM" };
|
|
755
|
+
path = `${base}/audiences`;
|
|
756
|
+
break;
|
|
757
|
+
}
|
|
758
|
+
case "spotify_create_lookalike_audience": {
|
|
759
|
+
const input = createLookalike.parse(op.payload);
|
|
760
|
+
await this.audience(op.accountId, input.seed_audience_id);
|
|
761
|
+
body = { ...input, audience_type: "LOOKALIKE" };
|
|
762
|
+
path = `${base}/audiences`;
|
|
763
|
+
break;
|
|
764
|
+
}
|
|
765
|
+
case "spotify_update_audience": {
|
|
766
|
+
const input = updateAudience.parse(op.payload), current = await this.audience(op.accountId, input.audience_id);
|
|
767
|
+
const { audience_id, ...patch } = input;
|
|
768
|
+
expected = audience_id;
|
|
769
|
+
body = { ...patch, audience_type: current.type };
|
|
770
|
+
path = `${base}/audiences/${audience_id}`;
|
|
771
|
+
method = "PATCH";
|
|
772
|
+
break;
|
|
773
|
+
}
|
|
774
|
+
case "spotify_delete_audience": {
|
|
775
|
+
const input = deleteAudience.parse(op.payload), current = await this.audience(op.accountId, input.audience_id);
|
|
776
|
+
return { summary: `Delete Spotify audience ${current.name}`, changes: [`- account-owned audience ${current.id}; targeting dependencies may be affected`], coercions: [], budgetDeltas: [], execute: async () => {
|
|
777
|
+
const result = await this.client.mutate(`${base}/audiences/${current.id}`, "DELETE", void 0, z6.object({ deletion_count: z6.number().int().nonnegative() }));
|
|
778
|
+
if (result.deletion_count !== 1) throw new AdportError3("PROVIDER_ERROR", "spotify: audience deletion did not confirm one removed record; inspect before retrying");
|
|
779
|
+
return [current.id];
|
|
780
|
+
} };
|
|
781
|
+
}
|
|
782
|
+
default:
|
|
783
|
+
throw new AdportError3("INVALID_INPUT", `spotify: unsupported write ${op.tool}`);
|
|
784
|
+
}
|
|
785
|
+
return { summary: `Spotify ${op.tool.replace(/^spotify_/, "").replaceAll("_", " ")}`, changes: [`${method} /${path} ${JSON.stringify(body)}`], coercions: [], budgetDeltas: [], execute: async () => {
|
|
786
|
+
const result = await this.client.mutate(path, method, body, audienceSchema);
|
|
787
|
+
if (expected && result.id !== expected || result.type !== body.audience_type || result.ad_account_id !== void 0 && result.ad_account_id !== op.accountId) throw new AdportError3("PROVIDER_ERROR", "spotify: audience mutation receipt mismatch; inspect before retrying");
|
|
788
|
+
return [result.id];
|
|
789
|
+
} };
|
|
790
|
+
}
|
|
791
|
+
};
|
|
792
|
+
|
|
793
|
+
// src/measurement.ts
|
|
794
|
+
import { createHash as createHash2 } from "crypto";
|
|
795
|
+
import { AdportError as AdportError5 } from "@adport/core";
|
|
796
|
+
import { z as z9 } from "zod";
|
|
797
|
+
|
|
798
|
+
// src/measurement-schemas.ts
|
|
799
|
+
import { z as z7 } from "zod";
|
|
800
|
+
var pixelId = z7.string().min(1).max(200).regex(/^[A-Za-z0-9_-]+$/);
|
|
801
|
+
var receiptInput = z7.string().min(1).max(4096);
|
|
802
|
+
var hash = z7.string().regex(/^[a-f0-9]{64}$/);
|
|
803
|
+
var name = z7.string().trim().min(1);
|
|
804
|
+
var domain = z7.string().url().refine((value) => {
|
|
805
|
+
const u = new URL(value);
|
|
806
|
+
return ["https:", "http:"].includes(u.protocol) && !u.username && !u.password;
|
|
807
|
+
}, "Use an HTTP(S) URL without credentials");
|
|
808
|
+
var aamField = z7.enum(["EMAIL", "PHONE", "FIRST_NAME", "LAST_NAME", "DATE_OF_BIRTH", "GENDER", "CITY", "STATE", "ZIP", "COUNTRY", "EXTERNAL_ID"]);
|
|
809
|
+
var datasetCreation = { dataset_id: spotifyId.optional(), expected_dataset_configuration_hash: hash.optional(), resource_receipt: receiptInput.optional() };
|
|
810
|
+
var datasetTarget = { dataset_id: spotifyId, resource_receipt: receiptInput.optional() };
|
|
811
|
+
var mobileTarget = { mobile_app_id: spotifyId, resource_receipt: receiptInput.optional() };
|
|
812
|
+
var pairing = (v) => Boolean(v.dataset_id) === Boolean(v.expected_dataset_configuration_hash);
|
|
813
|
+
var createPixel = z7.object({ ...datasetCreation, name, domain, aam_opt_in: z7.boolean().default(false), aam_fields: z7.array(aamField).max(11).default([]), acknowledge_advanced_matching: z7.boolean().optional() }).strict().refine(pairing, "An existing dataset requires its current configuration hash").refine((v) => new Set(v.aam_fields).size === v.aam_fields.length, "Matching fields must be unique").refine((v) => v.aam_opt_in ? v.acknowledge_advanced_matching === true && v.aam_fields.length > 0 : v.aam_fields.length === 0, "Advanced matching needs explicit acknowledgement and fields; disabled matching has no fields");
|
|
814
|
+
var updatePixel = z7.object({ ...datasetTarget, expected_configuration_hash: hash, name: name.optional(), domain: domain.optional() }).strict().refine((v) => v.name !== void 0 || v.domain !== void 0, "Provide a name or domain");
|
|
815
|
+
var createCapi = z7.object({ ...datasetCreation, name }).strict().refine(pairing, "An existing dataset requires its current configuration hash");
|
|
816
|
+
var updateCapi = z7.object({ ...datasetTarget, expected_configuration_hash: hash, name }).strict();
|
|
817
|
+
var createDataset = z7.object({ name, sources: z7.array(z7.object({ dataset_id: spotifyId, integration_id: spotifyId, expected_configuration_hash: hash, resource_receipt: receiptInput.optional() }).strict()).min(1).max(100), acknowledge_measurement_effects: z7.literal(true) }).strict().refine((v) => new Set(v.sources.map((s) => s.integration_id)).size === v.sources.length, "Integration IDs must be unique");
|
|
818
|
+
var updateDataset = z7.object({ ...datasetTarget, expected_configuration_hash: hash, name }).strict();
|
|
819
|
+
var removeIntegration = z7.object({ ...datasetTarget, expected_configuration_hash: hash, integration_id: spotifyId, acknowledge_measurement_effects: z7.literal(true) }).strict();
|
|
820
|
+
var datasetSharing = z7.object({ ...datasetTarget, expected_configuration_hash: hash, shared: z7.boolean(), acknowledge_measurement_effects: z7.boolean().optional() }).strict().refine((v) => v.shared || v.acknowledge_measurement_effects === true, "Unsharing requires acknowledgement of measurement effects");
|
|
821
|
+
var mobileFields = { name: z7.string().trim().min(2).max(50), platform: z7.enum(["IOS", "ANDROID"]).optional(), platform_app_id: z7.string().min(2).max(120).optional(), ad_type: z7.enum(["VIEW_THROUGH", "STORE_KIT"]).optional(), mobile_measurement_partner: z7.enum(["KOCHAVA", "APPS_FLYER", "ADJUST", "BRANCH", "SINGULAR"]).optional() };
|
|
822
|
+
var createMobile = z7.object(mobileFields).strict();
|
|
823
|
+
var updateMobile = z7.object({ ...mobileTarget, expected_configuration_hash: hash, ...mobileFields }).strict();
|
|
824
|
+
var mobileSharing = z7.object({ ...mobileTarget, expected_configuration_hash: hash, shared: z7.boolean(), acknowledge_measurement_effects: z7.boolean().optional() }).strict().refine((v) => v.shared || v.acknowledge_measurement_effects === true, "Unsharing requires acknowledgement of measurement effects");
|
|
825
|
+
var eventTime = z7.object({ event_type: z7.string().nullish(), first_event_time: z7.string().nullish() });
|
|
826
|
+
var pixelSchema = z7.object({ id: pixelId, name: z7.string().nullish(), domain: z7.string().nullish(), dataset_id: spotifyId.nullish(), integration_id: spotifyId.nullish(), aam_opt_in: z7.boolean().nullish(), aam_fields: z7.array(aamField).nullish(), cookie_opt_in: z7.boolean().nullish(), auto_capture_opt_in: z7.boolean().nullish(), auto_capture_fields: z7.array(z7.string()).nullish(), events_received: z7.array(eventTime).nullish() });
|
|
827
|
+
var capiSchema = z7.object({ capi_connection_id: spotifyId, name: z7.string().nullish(), dataset_id: spotifyId.nullish(), integration_id: spotifyId.nullish(), events_received: z7.array(eventTime).nullish() });
|
|
828
|
+
var shares = z7.array(z7.object({ id: spotifyId, name: z7.string().nullish() })).refine((v) => new Set(v.map((s) => s.id)).size === v.length, "Repeated account sharing IDs");
|
|
829
|
+
var datasetSchema = z7.object({ id: spotifyId, name: z7.string().nullish(), pixel: pixelSchema.nullish(), capi_integration: capiSchema.nullish(), shared_ad_accounts: shares.nullish(), ad_set_count: z7.number().int().nonnegative().nullish(), is_archived: z7.boolean().nullish(), is_receiving_events: z7.boolean().nullish(), is_receiving_lead_events: z7.boolean().nullish() });
|
|
830
|
+
var mobileSchema = z7.object({ id: spotifyId, name: z7.string().nullish(), platform: z7.string().nullish(), platform_app_id: z7.string().nullish(), ad_type: z7.string().nullish(), mobile_measurement_partner: z7.string().nullish(), dataset_id: spotifyId.nullish(), integration_id: spotifyId.nullish(), ad_set_count: z7.number().int().nonnegative().nullish(), is_skad_network: z7.boolean().nullish(), shared_ad_accounts: shares.nullish() });
|
|
831
|
+
var paging2 = z7.object({ offset: z7.number().int().nonnegative(), total_results: z7.number().int().nonnegative(), page_size: z7.number().int().nonnegative().nullish() });
|
|
832
|
+
var diagnosticSchema = z7.object({ dataset_id: spotifyId, datasources: z7.array(z7.object({ datasource_type: z7.enum(["PIXEL", "CAPI", "MOBILE_APP"]), datasource_id: z7.string(), granularity: z7.enum(["DAILY", "HOURLY"]), timeseries: z7.array(z7.object({ total: z7.number().nullish(), timestamp: z7.number().nullish(), event_counts: z7.array(z7.object({ name: z7.string(), event_count: z7.number(), last_activity_ms: z7.number().nullish() })).nullish() })) })) });
|
|
833
|
+
var createdReceipt = z7.object({ version: z7.literal(1), purpose: z7.enum(["creation", "sharing"]), account_id: spotifyId, business_id: spotifyId, kind: z7.enum(["pixel", "capi", "mobile_app", "dataset"]), id: pixelId, dataset_id: spotifyId.optional(), issued_at: z7.number().int().positive().safe(), expires_at: z7.number().int().positive().safe() }).strict().refine((v) => v.kind === "pixel" || spotifyId.safeParse(v.id).success, "Invalid resource ID");
|
|
834
|
+
|
|
835
|
+
// src/capi-credentials.ts
|
|
836
|
+
import { createHash } from "crypto";
|
|
837
|
+
import { AdportError as AdportError4 } from "@adport/core";
|
|
838
|
+
import { z as z8 } from "zod";
|
|
839
|
+
var hash2 = z8.string().regex(/^[a-f0-9]{64}$/);
|
|
840
|
+
var capiCredentialTarget = z8.object({ dataset_id: spotifyId }).strict();
|
|
841
|
+
var snapshot = { dataset_id: spotifyId, expected_configuration_hash: hash2, expected_dataset_configuration_hash: hash2, expected_token_inventory_hash: hash2 };
|
|
842
|
+
var createCapiCredential = z8.object({ ...snapshot, acknowledge_credential_access: z8.literal(true) }).strict();
|
|
843
|
+
var storeCapiCredential = createCapiCredential.extend({ capi_auth_token_id: spotifyId });
|
|
844
|
+
var revokeCapiCredential = z8.object({ ...snapshot, capi_auth_token_id: spotifyId, acknowledge_ingestion_effects: z8.literal(true) }).strict();
|
|
845
|
+
var capiCredentialWrites = /* @__PURE__ */ new Set(["spotify_create_capi_credential", "spotify_store_capi_credential", "spotify_revoke_capi_credential"]);
|
|
846
|
+
var nativeToken = z8.object({ capi_auth_token_id: spotifyId, created_at: z8.iso.datetime({ offset: true }).nullish(), capi_auth_token: z8.string().min(1).max(65536).optional() });
|
|
847
|
+
var tokenList = z8.object({ data: z8.array(nativeToken).max(1e3), paging: z8.unknown().optional() }).refine((v) => v.paging == null && new Set(v.data.map((t) => t.capi_auth_token_id)).size === v.data.length, "Invalid native credential inventory");
|
|
848
|
+
var createdToken = z8.object({ data: nativeToken.extend({ capi_auth_token: z8.string().min(1).max(65536) }) });
|
|
849
|
+
var notes = ["CAPI credentials grant ongoing event-ingestion access to this integration. The native endpoint provides no configurable expiry. No token value is returned to agents, widgets or audit logs.", "No conversion events, tracking installation, ad delivery or budget changes. Native failures are never replayed automatically."];
|
|
850
|
+
var previewNotes = ["Local preview only; Spotify has no native validation endpoint for credentials.", ...notes];
|
|
851
|
+
var SpotifyCapiCredentials = class {
|
|
852
|
+
constructor(client, authorize, secrets) {
|
|
853
|
+
this.client = client;
|
|
854
|
+
this.authorize = authorize;
|
|
855
|
+
this.secrets = secrets;
|
|
856
|
+
}
|
|
857
|
+
client;
|
|
858
|
+
authorize;
|
|
859
|
+
secrets;
|
|
860
|
+
path(scope) {
|
|
861
|
+
return `businesses/${scope.business_id}/capi/${scope.capi_connection_id}/tokens`;
|
|
862
|
+
}
|
|
863
|
+
key(scope, id) {
|
|
864
|
+
return { provider: "spotify", accountId: scope.account_id, businessId: scope.business_id, resourceId: scope.capi_connection_id, credentialId: id };
|
|
865
|
+
}
|
|
866
|
+
metadata(tokens) {
|
|
867
|
+
return tokens.map((t) => ({ capi_auth_token_id: t.capi_auth_token_id, created_at: t.created_at ?? null })).sort((a, b) => a.capi_auth_token_id.localeCompare(b.capi_auth_token_id));
|
|
868
|
+
}
|
|
869
|
+
inventoryHash(scope, tokens) {
|
|
870
|
+
return createHash("sha256").update(JSON.stringify({ ...scope, tokens: this.metadata(tokens) })).digest("hex");
|
|
871
|
+
}
|
|
872
|
+
async safe(call, operation) {
|
|
873
|
+
try {
|
|
874
|
+
return await call();
|
|
875
|
+
} catch (error) {
|
|
876
|
+
const status = error instanceof AdportError4 && error.details && typeof error.details === "object" && "http_status" in error.details ? error.details.http_status : void 0;
|
|
877
|
+
throw new AdportError4("PROVIDER_ERROR", `spotify: CAPI credential ${operation} failed; inspect credential metadata before any new mutation. No request was replayed.`, typeof status === "number" ? { http_status: status } : void 0);
|
|
878
|
+
}
|
|
879
|
+
}
|
|
880
|
+
async tokens(scope) {
|
|
881
|
+
return (await this.safe(() => this.client.get(this.path(scope), tokenList), "inventory read")).data;
|
|
882
|
+
}
|
|
883
|
+
vault() {
|
|
884
|
+
if (!this.secrets) throw new AdportError4("INVALID_INPUT", "spotify: a private resource credential store must be configured before managing CAPI credentials.");
|
|
885
|
+
return this.secrets;
|
|
886
|
+
}
|
|
887
|
+
async list(input) {
|
|
888
|
+
const scope = await this.authorize(input), tokens = await this.tokens(scope);
|
|
889
|
+
return {
|
|
890
|
+
...scope,
|
|
891
|
+
credential_inventory_hash: this.inventoryHash(scope, tokens),
|
|
892
|
+
vault_configured: !!this.secrets,
|
|
893
|
+
credentials: await Promise.all(this.metadata(tokens).map(async (token) => ({ ...token, stored_in_adport: this.secrets ? await this.safe(() => this.secrets.has(this.key(scope, token.capi_auth_token_id)), "storage metadata read") : null }))),
|
|
894
|
+
notes
|
|
895
|
+
};
|
|
896
|
+
}
|
|
897
|
+
uncertain(scope, id, before, operation) {
|
|
898
|
+
throw new AdportError4("PROVIDER_ERROR", `spotify: CAPI credential ${operation} is unconfirmed. Do not repeat it; read spotify_capi_credentials and reconcile the selected credential.`, { business_id: scope.business_id, dataset_id: scope.dataset_id, capi_connection_id: scope.capi_connection_id, ...id ? { capi_auth_token_id: id, resource_ids: [id] } : {}, previous_credential_ids: this.metadata(before).map((t) => t.capi_auth_token_id) });
|
|
899
|
+
}
|
|
900
|
+
async save(scope, token) {
|
|
901
|
+
const store = this.vault(), key = this.key(scope, token.capi_auth_token_id);
|
|
902
|
+
await store.putIfAbsent(key, token.capi_auth_token);
|
|
903
|
+
if (await store.get(key) !== token.capi_auth_token) throw new Error("Stored credential does not match native credential.");
|
|
904
|
+
}
|
|
905
|
+
async plan(op) {
|
|
906
|
+
const creating = op.tool === "spotify_create_capi_credential", storing = op.tool === "spotify_store_capi_credential";
|
|
907
|
+
if (!capiCredentialWrites.has(op.tool)) throw new AdportError4("UNKNOWN_TOOL", "spotify: unknown CAPI credential mutation");
|
|
908
|
+
const input = creating ? createCapiCredential.parse(op.payload) : storing ? storeCapiCredential.parse(op.payload) : revokeCapiCredential.parse(op.payload);
|
|
909
|
+
const vault = this.vault(), scope = await this.authorize({ account_id: op.accountId, dataset_id: input.dataset_id }), before = await this.tokens(scope);
|
|
910
|
+
if (scope.configuration_hash !== input.expected_configuration_hash || scope.dataset_configuration_hash !== input.expected_dataset_configuration_hash || this.inventoryHash(scope, before) !== input.expected_token_inventory_hash) throw new AdportError4("PENDING_MISMATCH", "spotify: CAPI configuration, sharing or credential inventory changed; read spotify_capi_credentials for a new preview.");
|
|
911
|
+
const id = "capi_auth_token_id" in input ? input.capi_auth_token_id : void 0;
|
|
912
|
+
const selected = before.find((t) => t.capi_auth_token_id === id);
|
|
913
|
+
const stored = id ? await this.safe(() => vault.has(this.key(scope, id)), "storage metadata read") : false;
|
|
914
|
+
if (storing && !selected?.capi_auth_token) throw new AdportError4("INVALID_INPUT", "spotify: the selected active credential has no available native secret to store.");
|
|
915
|
+
if (!creating && !selected && !stored) throw new AdportError4("INVALID_INPUT", "spotify: the selected credential is neither active in this integration nor stored in this Adport scope.");
|
|
916
|
+
const title = creating ? "Create CAPI credential" : storing ? "Store existing CAPI credential" : selected ? "Revoke CAPI credential" : "Remove inactive CAPI credential copy";
|
|
917
|
+
return {
|
|
918
|
+
summary: `${title} for Spotify integration ${scope.capi_connection_id}`,
|
|
919
|
+
changes: [creating ? "+ One native long-lived credential, saved privately in Adport." : storing ? `+ Store only the selected active credential ${id}; do not create a native token.` : selected ? `- Revoke native credential ${id} and remove its Adport copy after confirmed native revocation.` : `- Remove only the private Adport copy of inactive credential ${id}; no native deletion request.`, "No events are sent."],
|
|
920
|
+
coercions: [],
|
|
921
|
+
budgetDeltas: [],
|
|
922
|
+
notes: previewNotes,
|
|
923
|
+
review: { provider: "spotify", accountId: scope.account_id, kind: creating || storing ? "create" : "remove", title, fields: [{ label: "Dataset", after: scope.dataset_id }, { label: "CAPI integration", after: scope.capi_connection_id }, ...id ? [{ label: "Credential", after: id }, { label: "Stored in Adport", before: stored, after: storing }] : [], { label: "Active credentials", before: before.length, after: before.length + (creating ? 1 : !storing && selected ? -1 : 0) }], notices: previewNotes },
|
|
924
|
+
execute: async () => {
|
|
925
|
+
let createdId, nativeAcknowledged = false;
|
|
926
|
+
try {
|
|
927
|
+
if (creating) {
|
|
928
|
+
const token = (await this.safe(() => this.client.mutate(this.path(scope), "POST", void 0, createdToken), "creation")).data;
|
|
929
|
+
nativeAcknowledged = true;
|
|
930
|
+
createdId = token.capi_auth_token_id;
|
|
931
|
+
if (before.some((t) => t.capi_auth_token_id === createdId)) throw new Error("Creation returned an existing credential ID.");
|
|
932
|
+
await this.save(scope, token);
|
|
933
|
+
const after = await this.tokens(scope);
|
|
934
|
+
const actual = after.find((t) => t.capi_auth_token_id === createdId);
|
|
935
|
+
if (!actual || actual.capi_auth_token !== void 0 && actual.capi_auth_token !== token.capi_auth_token) throw new Error("Credential readback mismatch.");
|
|
936
|
+
return { applied: true, resourceIds: [createdId], details: { capi_auth_token_id: createdId, stored_in_adport: true, created_at: token.created_at ?? null, next_tool: "spotify_capi_credentials" } };
|
|
937
|
+
}
|
|
938
|
+
if (storing) {
|
|
939
|
+
await this.save(scope, selected);
|
|
940
|
+
return { applied: true, resourceIds: [id], details: { capi_auth_token_id: id, stored_in_adport: true, native_credential_created: false } };
|
|
941
|
+
}
|
|
942
|
+
if (selected) {
|
|
943
|
+
await this.safe(() => this.client.mutate(`${this.path(scope)}/${id}`, "DELETE", void 0, z8.undefined()), "revocation");
|
|
944
|
+
nativeAcknowledged = true;
|
|
945
|
+
}
|
|
946
|
+
if ((await this.tokens(scope)).some((t) => t.capi_auth_token_id === id)) throw new Error("Credential remains active.");
|
|
947
|
+
await vault.delete(this.key(scope, id));
|
|
948
|
+
return { applied: true, resourceIds: [id], details: { capi_auth_token_id: id, native_active: false, stored_in_adport: false } };
|
|
949
|
+
} catch (error) {
|
|
950
|
+
if (!nativeAcknowledged && error instanceof AdportError4 && error.details && typeof error.details === "object" && "http_status" in error.details && [400, 401, 403, 404, 409, 422].includes(Number(error.details.http_status))) throw error;
|
|
951
|
+
return this.uncertain(scope, createdId ?? id, before, creating ? "creation/storage" : storing ? "storage" : "revocation/cleanup");
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
};
|
|
955
|
+
}
|
|
956
|
+
};
|
|
957
|
+
|
|
958
|
+
// src/measurement.ts
|
|
959
|
+
var RECEIPT_TTL = 7 * 24 * 60 * 60;
|
|
960
|
+
var commonNotes = ["Local preview only. Measurement resource management does not install website code, send conversion events, issue CAPI credentials or change ad delivery or budgets.", "Native permissions and configuration remain authoritative. No automatic write retry; use the returned IDs and signed receipt to reconcile partial creation."];
|
|
961
|
+
var canonical = (value) => JSON.stringify(value, (key, item) => {
|
|
962
|
+
if (Array.isArray(item) && ["aam_fields", "auto_capture_fields", "shared_ad_accounts"].includes(key)) return item.map((v) => v && typeof v === "object" && "id" in v ? { id: v.id } : v).sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)));
|
|
963
|
+
return item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).filter(([k]) => !["events", "events_received", "historical_events", "created_at", "updated_at", "ad_set_count", "is_receiving_events", "is_receiving_lead_events"].includes(k)).sort(([a], [b]) => a.localeCompare(b))) : item;
|
|
964
|
+
});
|
|
965
|
+
var digest = (scope, kind, value) => createHash2("sha256").update(canonical({ ...scope, kind, configuration: value })).digest("hex");
|
|
966
|
+
var same = (a, b) => canonical(a) === canonical(b);
|
|
967
|
+
var members = (dataset) => [dataset.pixel, dataset.capi_integration].filter((v) => Boolean(v));
|
|
968
|
+
var contains = (dataset, integration) => members(dataset).some((v) => v.integration_id === integration);
|
|
969
|
+
function params(input) {
|
|
970
|
+
const p = new URLSearchParams();
|
|
971
|
+
for (const [k, v] of Object.entries(input)) if (v !== void 0) {
|
|
972
|
+
if (Array.isArray(v)) for (const value of v) p.append(k, String(value));
|
|
973
|
+
else p.set(k, String(v));
|
|
974
|
+
}
|
|
975
|
+
return p;
|
|
976
|
+
}
|
|
977
|
+
function ensure(value, message) {
|
|
978
|
+
if (!value) throw new AdportError5("PROVIDER_ERROR", `spotify: ${message}`);
|
|
979
|
+
}
|
|
980
|
+
var SpotifyMeasurementService = class {
|
|
981
|
+
constructor(client, secrets) {
|
|
982
|
+
this.client = client;
|
|
983
|
+
this.credentials = new SpotifyCapiCredentials(client, (input) => this.credentialScope(input), secrets);
|
|
984
|
+
}
|
|
985
|
+
client;
|
|
986
|
+
credentials;
|
|
987
|
+
async credentialScope(input) {
|
|
988
|
+
const scope = await this.scope(input.account_id), dataset = await this.dataset(scope, input.dataset_id);
|
|
989
|
+
this.exclusive(scope, dataset);
|
|
990
|
+
ensure(dataset.shared_ad_accounts?.some((account3) => account3.id === scope.account_id), "CAPI credentials require sharing with this selected account");
|
|
991
|
+
ensure(dataset.capi_integration, "dataset has no verified CAPI integration");
|
|
992
|
+
const integration = await this.rawCapi(scope, dataset.capi_integration.capi_connection_id);
|
|
993
|
+
this.verifyIntegrationBinding(dataset, "capi", integration.capi_connection_id, integration.dataset_id);
|
|
994
|
+
return { ...scope, dataset_id: dataset.id, capi_connection_id: integration.capi_connection_id, configuration_hash: digest(scope, "capi", integration), dataset_configuration_hash: digest(scope, "dataset", dataset) };
|
|
995
|
+
}
|
|
996
|
+
base(scope) {
|
|
997
|
+
return `businesses/${scope.business_id}`;
|
|
998
|
+
}
|
|
999
|
+
async scope(account3) {
|
|
1000
|
+
const id = spotifyId.parse(account3), data = await this.client.get(`ad_accounts/${id}`, z9.object({ id: spotifyId, business_id: spotifyId }));
|
|
1001
|
+
ensure(data.id === id, "measurement account identity mismatch");
|
|
1002
|
+
return { account_id: id, business_id: data.business_id };
|
|
1003
|
+
}
|
|
1004
|
+
proof(account3, value, purpose = "creation") {
|
|
1005
|
+
if (!value) return void 0;
|
|
1006
|
+
const parsed = createdReceipt.safeParse(this.client.verifyMeasurementReceipt(value)), now = Math.floor(Date.now() / 1e3);
|
|
1007
|
+
if (!parsed.success || parsed.data.purpose !== purpose || parsed.data.account_id !== account3 || parsed.data.issued_at > now + 60 || parsed.data.expires_at <= now || parsed.data.expires_at <= parsed.data.issued_at || parsed.data.expires_at - parsed.data.issued_at > RECEIPT_TTL) throw new AdportError5("INVALID_INPUT", "spotify: expired or mismatched measurement resource receipt");
|
|
1008
|
+
return parsed.data;
|
|
1009
|
+
}
|
|
1010
|
+
bind(scope, kind, id, datasetId, purpose = "creation") {
|
|
1011
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
1012
|
+
return this.client.measurementReceipt(createdReceipt.parse({ version: 1, purpose, ...scope, kind, id, ...datasetId ? { dataset_id: datasetId } : {}, issued_at: now, expires_at: now + RECEIPT_TTL }));
|
|
1013
|
+
}
|
|
1014
|
+
checkProof(scope, proof) {
|
|
1015
|
+
if (proof && proof.business_id !== scope.business_id) throw new AdportError5("INVALID_INPUT", "spotify: the account business changed; measurement receipt no longer matches");
|
|
1016
|
+
}
|
|
1017
|
+
async rawDataset(scope, id) {
|
|
1018
|
+
const data = await this.client.get(`${this.base(scope)}/datasets/${spotifyId.parse(id)}`, datasetSchema);
|
|
1019
|
+
ensure(data.id === id, "dataset identity mismatch");
|
|
1020
|
+
return data;
|
|
1021
|
+
}
|
|
1022
|
+
async rawMobile(scope, id) {
|
|
1023
|
+
const data = await this.client.get(`${this.base(scope)}/mobile_apps/${spotifyId.parse(id)}`, mobileSchema);
|
|
1024
|
+
ensure(data.id === id, "mobile-app identity mismatch");
|
|
1025
|
+
return data;
|
|
1026
|
+
}
|
|
1027
|
+
async rawPixel(scope, id) {
|
|
1028
|
+
const data = await this.client.get(`${this.base(scope)}/pixels/${id}`, pixelSchema);
|
|
1029
|
+
ensure(data.id === id, "Pixel identity mismatch");
|
|
1030
|
+
return data;
|
|
1031
|
+
}
|
|
1032
|
+
async rawCapi(scope, id) {
|
|
1033
|
+
const data = await this.client.get(`${this.base(scope)}/capi/${spotifyId.parse(id)}`, capiSchema);
|
|
1034
|
+
ensure(data.capi_connection_id === id, "CAPI integration identity mismatch");
|
|
1035
|
+
return data;
|
|
1036
|
+
}
|
|
1037
|
+
datasetContainsResource(dataset, kind, id) {
|
|
1038
|
+
return kind === "pixel" ? dataset.pixel?.id === id : kind === "capi" ? dataset.capi_integration?.capi_connection_id === id : false;
|
|
1039
|
+
}
|
|
1040
|
+
verifyIntegrationBinding(dataset, kind, id, observed) {
|
|
1041
|
+
ensure(this.datasetContainsResource(dataset, kind, id) && (observed == null || observed === dataset.id), `${kind === "pixel" ? "Pixel" : "CAPI"} dataset binding mismatch`);
|
|
1042
|
+
}
|
|
1043
|
+
async receiptNative(scope, proof) {
|
|
1044
|
+
this.checkProof(scope, proof);
|
|
1045
|
+
const resource = proof.kind === "pixel" ? await this.rawPixel(scope, proof.id) : proof.kind === "capi" ? await this.rawCapi(scope, proof.id) : proof.kind === "mobile_app" ? await this.rawMobile(scope, proof.id) : await this.rawDataset(scope, proof.id);
|
|
1046
|
+
const datasetId = proof.kind === "dataset" ? proof.id : "dataset_id" in resource && typeof resource.dataset_id === "string" ? resource.dataset_id : void 0;
|
|
1047
|
+
let expectedDataset, verifiedDatasetId = datasetId;
|
|
1048
|
+
let parentVerificationError;
|
|
1049
|
+
if (!datasetId && proof.dataset_id && ["pixel", "capi"].includes(proof.kind)) {
|
|
1050
|
+
try {
|
|
1051
|
+
expectedDataset = await this.rawDataset(scope, proof.dataset_id);
|
|
1052
|
+
if (this.datasetContainsResource(expectedDataset, proof.kind, proof.id)) verifiedDatasetId = expectedDataset.id;
|
|
1053
|
+
} catch (error) {
|
|
1054
|
+
if (!(error instanceof AdportError5)) throw error;
|
|
1055
|
+
const status = error.details && typeof error.details === "object" && "http_status" in error.details ? error.details.http_status : void 0;
|
|
1056
|
+
parentVerificationError = { code: error.code, ...typeof status === "number" ? { http_status: status } : {} };
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
return { resource, datasetId, verifiedDatasetId, expectedDataset, parentVerificationError };
|
|
1060
|
+
}
|
|
1061
|
+
async createdNative(scope, proof) {
|
|
1062
|
+
const { resource, verifiedDatasetId } = await this.receiptNative(scope, proof);
|
|
1063
|
+
ensure(!proof.dataset_id || verifiedDatasetId === proof.dataset_id, "created resource dataset binding changed; reconcile the original IDs");
|
|
1064
|
+
return { resource, datasetId: verifiedDatasetId };
|
|
1065
|
+
}
|
|
1066
|
+
sharing(scope, row) {
|
|
1067
|
+
return { shared_ad_accounts: row.shared_ad_accounts === null ? null : row.shared_ad_accounts?.filter((a) => a.id === scope.account_id), other_shared_account_count: row.shared_ad_accounts ? row.shared_ad_accounts.filter((a) => a.id !== scope.account_id).length : null };
|
|
1068
|
+
}
|
|
1069
|
+
publicDataset(scope, row, snapshot2 = true) {
|
|
1070
|
+
return { ...row, ...this.sharing(scope, row), ...snapshot2 ? { configuration_hash: digest(scope, "dataset", row) } : {} };
|
|
1071
|
+
}
|
|
1072
|
+
publicMobile(scope, row, snapshot2 = true) {
|
|
1073
|
+
return { ...row, ...this.sharing(scope, row), ...snapshot2 ? { configuration_hash: digest(scope, "mobile_app", row) } : {} };
|
|
1074
|
+
}
|
|
1075
|
+
async selectedDatasets(scope) {
|
|
1076
|
+
const data = await this.client.get(`${this.base(scope)}/ad_accounts/${scope.account_id}/datasets`, z9.object({ datasets: z9.array(datasetSchema), paging: paging2.nullish() }));
|
|
1077
|
+
ensure(new Set(data.datasets.map((d) => d.id)).size === data.datasets.length, "dataset inventory repeated an ID");
|
|
1078
|
+
ensure(!data.paging || data.paging.offset === 0 && data.paging.total_results >= data.datasets.length, "dataset inventory pagination is inconsistent");
|
|
1079
|
+
for (const row of data.datasets) ensure(!row.shared_ad_accounts || row.shared_ad_accounts.some((a) => a.id === scope.account_id), "dataset inventory contains an unshared account resource");
|
|
1080
|
+
return { ...data, complete: data.paging ? data.paging.total_results === data.datasets.length : null, truncated: !data.paging || data.paging.total_results !== data.datasets.length };
|
|
1081
|
+
}
|
|
1082
|
+
recoverableDataset(scope, row, proof, nativeDatasetId) {
|
|
1083
|
+
if (nativeDatasetId !== row.id) return false;
|
|
1084
|
+
if (proof.dataset_id === row.id || proof.kind === "dataset" && proof.id === row.id) return true;
|
|
1085
|
+
if (!row.shared_ad_accounts || row.shared_ad_accounts.some((a) => a.id !== scope.account_id)) return false;
|
|
1086
|
+
return proof.kind === "pixel" ? row.pixel?.id === proof.id && !row.capi_integration : proof.kind === "capi" ? row.capi_integration?.capi_connection_id === proof.id && !row.pixel : false;
|
|
1087
|
+
}
|
|
1088
|
+
async dataset(scope, id, proof) {
|
|
1089
|
+
this.checkProof(scope, proof);
|
|
1090
|
+
const row = await this.rawDataset(scope, id);
|
|
1091
|
+
if (row.shared_ad_accounts?.some((a) => a.id === scope.account_id)) return row;
|
|
1092
|
+
if (proof && this.recoverableDataset(scope, row, proof, (await this.createdNative(scope, proof)).datasetId)) return row;
|
|
1093
|
+
if (!row.shared_ad_accounts) {
|
|
1094
|
+
const selected = (await this.selectedDatasets(scope)).datasets.find((d) => d.id === id);
|
|
1095
|
+
if (selected) return { ...row, ...selected.shared_ad_accounts ? { shared_ad_accounts: selected.shared_ad_accounts } : {} };
|
|
1096
|
+
}
|
|
1097
|
+
throw new AdportError5("INVALID_INPUT", "spotify: dataset is not shared with the selected account; an unshared creation requires its signed resource receipt");
|
|
1098
|
+
}
|
|
1099
|
+
async mobile(scope, id, proof) {
|
|
1100
|
+
this.checkProof(scope, proof);
|
|
1101
|
+
const row = await this.rawMobile(scope, id);
|
|
1102
|
+
if (row.shared_ad_accounts?.some((a) => a.id === scope.account_id) || proof?.kind === "mobile_app" && proof.id === id) return row;
|
|
1103
|
+
if (!row.shared_ad_accounts) {
|
|
1104
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1105
|
+
for (let offset = 0, page3 = 0; page3 < 1e3; page3++) {
|
|
1106
|
+
const data = await this.mobilePage(scope, { limit: 50, offset });
|
|
1107
|
+
for (const item of data.mobile_apps) {
|
|
1108
|
+
ensure(!seen.has(item.id), "mobile-app inventory repeated a page");
|
|
1109
|
+
seen.add(item.id);
|
|
1110
|
+
}
|
|
1111
|
+
const selected = data.mobile_apps.find((a) => a.id === id);
|
|
1112
|
+
if (selected) return { ...row, ...selected.shared_ad_accounts ? { shared_ad_accounts: selected.shared_ad_accounts } : {} };
|
|
1113
|
+
if (!data.truncated) break;
|
|
1114
|
+
offset = data.next_offset;
|
|
1115
|
+
}
|
|
1116
|
+
}
|
|
1117
|
+
throw new AdportError5("INVALID_INPUT", "spotify: mobile app is not shared with the selected account or bound to its approved creation receipt");
|
|
1118
|
+
}
|
|
1119
|
+
exclusive(scope, row) {
|
|
1120
|
+
if (!row.shared_ad_accounts || row.shared_ad_accounts.some((a) => a.id !== scope.account_id)) throw new AdportError5("INVALID_INPUT", "spotify: business-wide configuration changes require verified sharing restricted to this selected account");
|
|
1121
|
+
}
|
|
1122
|
+
expected(scope, kind, value, hash3) {
|
|
1123
|
+
if (digest(scope, kind, value) !== hash3) throw new AdportError5("INVALID_INPUT", "spotify: measurement configuration changed; obtain a fresh snapshot before a new preview");
|
|
1124
|
+
}
|
|
1125
|
+
result(ids2, details = {}) {
|
|
1126
|
+
return { applied: true, resourceIds: [...new Set(ids2)], ...Object.keys(details).length ? { details } : {} };
|
|
1127
|
+
}
|
|
1128
|
+
uncertain(ids2, receipt) {
|
|
1129
|
+
throw new AdportError5("PROVIDER_ERROR", "spotify: measurement write/readback unconfirmed; reconcile the original IDs before another mutation. No write was replayed.", { resource_ids: ids2, ...receipt ? { resource_receipt: receipt } : {} });
|
|
1130
|
+
}
|
|
1131
|
+
review(scope, title, kind, body, current, notices = commonNotes) {
|
|
1132
|
+
const fields = Object.entries(body).map(([key, value]) => ({ label: key.replaceAll("_", " "), ...current?.[key] === void 0 ? {} : { before: current[key] }, after: value }));
|
|
1133
|
+
return { summary: title, changes: [`${kind}: ${JSON.stringify(body)}`], notes: notices, coercions: [], budgetDeltas: [], review: { provider: "spotify", accountId: scope.account_id, kind, title, fields, notices } };
|
|
1134
|
+
}
|
|
1135
|
+
async datasets(account3) {
|
|
1136
|
+
const scope = await this.scope(account3), data = await this.selectedDatasets(scope);
|
|
1137
|
+
return { ...scope, ...data, datasets: data.datasets.map((d) => this.publicDataset(scope, d, false)) };
|
|
1138
|
+
}
|
|
1139
|
+
async mobilePage(scope, input) {
|
|
1140
|
+
const data = await this.client.get(`${this.base(scope)}/ad_accounts/${scope.account_id}/mobile_apps`, z9.object({ mobile_apps: z9.array(mobileSchema), paging: paging2 }), params({ limit: input.limit, offset: input.offset }));
|
|
1141
|
+
ensure(data.paging.offset === input.offset && data.mobile_apps.length <= input.limit && (!data.mobile_apps.length || data.paging.total_results >= input.offset + data.mobile_apps.length), "mobile-app pagination is inconsistent");
|
|
1142
|
+
ensure(new Set(data.mobile_apps.map((a) => a.id)).size === data.mobile_apps.length, "mobile-app page repeated an ID");
|
|
1143
|
+
for (const row of data.mobile_apps) ensure(!row.shared_ad_accounts || row.shared_ad_accounts.some((a) => a.id === scope.account_id), "mobile-app inventory contains an unshared resource");
|
|
1144
|
+
const next = input.offset + data.mobile_apps.length, truncated = next < data.paging.total_results;
|
|
1145
|
+
ensure(!truncated || data.mobile_apps.length > 0, "mobile-app pagination stalled");
|
|
1146
|
+
return { ...data, truncated, ...truncated ? { next_offset: next } : {} };
|
|
1147
|
+
}
|
|
1148
|
+
async mobileApps(input) {
|
|
1149
|
+
const scope = await this.scope(input.account_id), data = await this.mobilePage(scope, input);
|
|
1150
|
+
return { ...scope, ...data, mobile_apps: data.mobile_apps.map((a) => this.publicMobile(scope, a, false)) };
|
|
1151
|
+
}
|
|
1152
|
+
async context(account3) {
|
|
1153
|
+
const scope = await this.scope(account3), data = await this.selectedDatasets(scope);
|
|
1154
|
+
return { ...scope, ...data, datasets: data.datasets.map((d) => this.publicDataset(scope, d, false)), notes: ["Only datasets shared with this selected account are inventoried. Business-wide resources and other account identities are excluded. Read an individual resource for its full mutation snapshot.", "Pixel creation may create a dataset; CAPI can join that dataset. No tracking code, tokens or events are created by these reads."] };
|
|
1155
|
+
}
|
|
1156
|
+
async getDataset(input) {
|
|
1157
|
+
const proof = this.proof(input.account_id, input.resource_receipt), scope = await this.scope(input.account_id);
|
|
1158
|
+
return { ...scope, dataset: this.publicDataset(scope, await this.dataset(scope, input.dataset_id, proof)) };
|
|
1159
|
+
}
|
|
1160
|
+
async getPixel(input) {
|
|
1161
|
+
const proof = this.proof(input.account_id, input.resource_receipt), scope = await this.scope(input.account_id), dataset = await this.dataset(scope, input.dataset_id, proof);
|
|
1162
|
+
ensure(dataset.pixel, "dataset has no verified Pixel");
|
|
1163
|
+
const pixel = await this.rawPixel(scope, dataset.pixel.id);
|
|
1164
|
+
this.verifyIntegrationBinding(dataset, "pixel", pixel.id, pixel.dataset_id);
|
|
1165
|
+
return { ...scope, pixel: { ...pixel, configuration_hash: digest(scope, "pixel", pixel) }, dataset_binding: { observed_dataset_id: pixel.dataset_id ?? null, verified_dataset_id: dataset.id, verification_source: pixel.dataset_id ? "resource" : "dataset" } };
|
|
1166
|
+
}
|
|
1167
|
+
async getCapi(input) {
|
|
1168
|
+
const proof = this.proof(input.account_id, input.resource_receipt), scope = await this.scope(input.account_id), dataset = await this.dataset(scope, input.dataset_id, proof);
|
|
1169
|
+
ensure(dataset.capi_integration, "dataset has no verified CAPI integration");
|
|
1170
|
+
const integration = await this.rawCapi(scope, dataset.capi_integration.capi_connection_id);
|
|
1171
|
+
this.verifyIntegrationBinding(dataset, "capi", integration.capi_connection_id, integration.dataset_id);
|
|
1172
|
+
return { ...scope, capi_integration: { ...integration, configuration_hash: digest(scope, "capi", integration) }, dataset_binding: { observed_dataset_id: integration.dataset_id ?? null, verified_dataset_id: dataset.id, verification_source: integration.dataset_id ? "resource" : "dataset" } };
|
|
1173
|
+
}
|
|
1174
|
+
async getMobile(input) {
|
|
1175
|
+
const proof = this.proof(input.account_id, input.resource_receipt), scope = await this.scope(input.account_id);
|
|
1176
|
+
return { ...scope, mobile_app: this.publicMobile(scope, await this.mobile(scope, input.mobile_app_id, proof)) };
|
|
1177
|
+
}
|
|
1178
|
+
async diagnostics(input) {
|
|
1179
|
+
const proof = this.proof(input.account_id, input.resource_receipt), scope = await this.scope(input.account_id);
|
|
1180
|
+
await this.dataset(scope, input.dataset_id, proof);
|
|
1181
|
+
const data = await this.client.get(`${this.base(scope)}/datasets/${input.dataset_id}/diagnostics`, diagnosticSchema, params({ granularities: input.granularities, datasource_ids: input.datasource_ids }));
|
|
1182
|
+
ensure(data.dataset_id === input.dataset_id && data.datasources.every((d) => input.granularities.includes(d.granularity) && (!input.datasource_ids || input.datasource_ids.includes(d.datasource_id))), "measurement diagnostic identity/filter mismatch");
|
|
1183
|
+
return { ...scope, ...data, notes: ["Diagnostics can lag implementation by at least 20 minutes. Received activity is not proof of campaign attribution, optimization or delivery. Missing or suppressed values remain native; this read sends no events."] };
|
|
1184
|
+
}
|
|
1185
|
+
async created(input) {
|
|
1186
|
+
const proof = this.proof(input.account_id, input.resource_receipt), scope = await this.scope(input.account_id), native = await this.receiptNative(scope, proof);
|
|
1187
|
+
const matches = proof.dataset_id ? native.datasetId === proof.dataset_id : null;
|
|
1188
|
+
const verified = !proof.dataset_id || native.verifiedDatasetId === proof.dataset_id;
|
|
1189
|
+
const candidate = verified && native.verifiedDatasetId ? native.expectedDataset ?? await this.rawDataset(scope, native.verifiedDatasetId) : void 0;
|
|
1190
|
+
const dataset = candidate && (candidate.shared_ad_accounts?.some((a) => a.id === scope.account_id) || this.recoverableDataset(scope, candidate, proof, native.verifiedDatasetId)) ? candidate : void 0;
|
|
1191
|
+
const key = proof.kind === "capi" ? "capi_integration" : proof.kind;
|
|
1192
|
+
const resource = proof.kind === "mobile_app" ? this.publicMobile(scope, native.resource) : proof.kind === "dataset" ? this.publicDataset(scope, native.resource) : { ...native.resource, configuration_hash: digest(scope, proof.kind, native.resource) };
|
|
1193
|
+
return {
|
|
1194
|
+
...scope,
|
|
1195
|
+
kind: proof.kind,
|
|
1196
|
+
[key]: resource,
|
|
1197
|
+
dataset: dataset ? this.publicDataset(scope, dataset) : null,
|
|
1198
|
+
dataset_binding: { expected_dataset_id: proof.dataset_id ?? null, observed_dataset_id: native.datasetId ?? null, matches_receipt: matches, verified_dataset_id: dataset?.id ?? null, verification_source: dataset ? native.datasetId ? "resource" : "dataset" : null, ...native.parentVerificationError ? { parent_verification_error: native.parentVerificationError } : {} },
|
|
1199
|
+
needs_dataset_sharing: dataset?.shared_ad_accounts ? !dataset.shared_ad_accounts.some((a) => a.id === scope.account_id) : null,
|
|
1200
|
+
resource_receipt: input.resource_receipt,
|
|
1201
|
+
notes: ["Read-only reconciliation of an approved creation. No creation, share, update or event request was replayed.", ...matches === false ? [dataset ? "The native child omits its dataset binding. The exact receipt-bound parent independently confirms the resource relationship; the native null value is preserved." : "The resource relationship is unverified. No unexpected dataset contents were followed. Sharing remains unverified and mutation checks remain strict."] : []]
|
|
1202
|
+
};
|
|
1203
|
+
}
|
|
1204
|
+
async sharingStatus(input) {
|
|
1205
|
+
const proof = this.proof(input.account_id, input.resource_receipt, "sharing"), scope = await this.scope(input.account_id);
|
|
1206
|
+
this.checkProof(scope, proof);
|
|
1207
|
+
if (!["dataset", "mobile_app"].includes(proof.kind)) throw new AdportError5("INVALID_INPUT", "spotify: receipt does not identify a sharing operation");
|
|
1208
|
+
const row = proof.kind === "dataset" ? await this.rawDataset(scope, proof.id) : await this.rawMobile(scope, proof.id);
|
|
1209
|
+
ensure(row.shared_ad_accounts, "native sharing state is unavailable");
|
|
1210
|
+
return { ...scope, kind: proof.kind, resource_id: proof.id, shared_with_selected_account: row.shared_ad_accounts.some((a) => a.id === scope.account_id), other_shared_account_count: row.shared_ad_accounts.filter((a) => a.id !== scope.account_id).length, notes: ["Read-only reconciliation of the selected account\u2019s sharing state. A sharing receipt does not grant resource-content access after unsharing."] };
|
|
1211
|
+
}
|
|
1212
|
+
async shareCreatedDataset(scope, id) {
|
|
1213
|
+
const current = await this.rawDataset(scope, id);
|
|
1214
|
+
this.exclusive(scope, current);
|
|
1215
|
+
if (!current.shared_ad_accounts.some((a) => a.id === scope.account_id)) await this.client.mutate(`${this.base(scope)}/datasets/${id}/ad_accounts/${scope.account_id}`, "POST", void 0, z9.undefined());
|
|
1216
|
+
const actual = await this.rawDataset(scope, id);
|
|
1217
|
+
this.exclusive(scope, actual);
|
|
1218
|
+
ensure(actual.shared_ad_accounts.some((a) => a.id === scope.account_id), "created dataset sharing readback unconfirmed");
|
|
1219
|
+
return actual;
|
|
1220
|
+
}
|
|
1221
|
+
async planCreate(op, scope, proof) {
|
|
1222
|
+
const kind = op.tool === "spotify_create_pixel" ? "pixel" : op.tool === "spotify_create_capi_integration" ? "capi" : "mobile_app";
|
|
1223
|
+
let body, requestedDataset;
|
|
1224
|
+
if (kind === "mobile_app") body = createMobile.parse(op.payload);
|
|
1225
|
+
else {
|
|
1226
|
+
const input = kind === "pixel" ? createPixel.parse(op.payload) : createCapi.parse(op.payload);
|
|
1227
|
+
const { expected_dataset_configuration_hash, resource_receipt: _receipt, ...native } = input;
|
|
1228
|
+
if (input.dataset_id) {
|
|
1229
|
+
const dataset = await this.dataset(scope, input.dataset_id, proof);
|
|
1230
|
+
this.exclusive(scope, dataset);
|
|
1231
|
+
this.expected(scope, "dataset", dataset, expected_dataset_configuration_hash);
|
|
1232
|
+
if (kind === "pixel" ? dataset.pixel : dataset.capi_integration) throw new AdportError5("INVALID_INPUT", `spotify: dataset already has a ${kind} integration; reuse it instead of duplicating the source`);
|
|
1233
|
+
}
|
|
1234
|
+
const { acknowledge_advanced_matching: _ack, ...fields } = native;
|
|
1235
|
+
body = fields;
|
|
1236
|
+
requestedDataset = input.dataset_id;
|
|
1237
|
+
}
|
|
1238
|
+
const path = `${this.base(scope)}/${kind === "pixel" ? "pixels" : kind === "capi" ? "capi" : "mobile_apps"}`;
|
|
1239
|
+
const notices = [...commonNotes, kind === "mobile_app" ? "The new mobile-app record will be shared only with this selected ad account. Registration does not install or configure an MMP SDK." : "The new integration will use its verified dataset, which will be shared only with this selected ad account. A new native dataset is created when dataset_id is omitted.", ...kind === "pixel" ? ["Advanced matching is disabled by default. Native cookie and automatic-capture settings are returned for review before any website installation."] : []];
|
|
1240
|
+
return { ...this.review(scope, `Create Spotify ${kind.replaceAll("_", " ")} "${body.name}"`, "create", body, void 0, notices), execute: async () => {
|
|
1241
|
+
let id, nativeDataset;
|
|
1242
|
+
try {
|
|
1243
|
+
if (kind === "pixel") {
|
|
1244
|
+
const row = await this.client.mutate(path, "POST", body, z9.object({ id: pixelId, dataset_id: z9.unknown().optional() }));
|
|
1245
|
+
id = row.id;
|
|
1246
|
+
const dataset = spotifyId.safeParse(row.dataset_id);
|
|
1247
|
+
nativeDataset = dataset.success ? dataset.data : void 0;
|
|
1248
|
+
} else if (kind === "capi") {
|
|
1249
|
+
const row = await this.client.mutate(path, "POST", body, z9.object({ capi_connection_id: spotifyId, dataset_id: z9.unknown().optional() }));
|
|
1250
|
+
id = row.capi_connection_id;
|
|
1251
|
+
const dataset = spotifyId.safeParse(row.dataset_id);
|
|
1252
|
+
nativeDataset = dataset.success ? dataset.data : void 0;
|
|
1253
|
+
} else {
|
|
1254
|
+
const row = await this.client.mutate(path, "POST", { mobile_app: body }, z9.object({ id: spotifyId, dataset_id: z9.unknown().optional() }));
|
|
1255
|
+
id = row.id;
|
|
1256
|
+
const dataset = spotifyId.safeParse(row.dataset_id);
|
|
1257
|
+
nativeDataset = dataset.success ? dataset.data : void 0;
|
|
1258
|
+
}
|
|
1259
|
+
} catch (error) {
|
|
1260
|
+
if (error instanceof AdportError5 && /HTTP (400|401|403|404|409|422)\b/.test(error.message)) throw error;
|
|
1261
|
+
return this.uncertain([]);
|
|
1262
|
+
}
|
|
1263
|
+
let receipt = this.bind(scope, kind, id, requestedDataset ?? nativeDataset), knownDataset = requestedDataset ?? nativeDataset;
|
|
1264
|
+
try {
|
|
1265
|
+
const bound = this.proof(scope.account_id, receipt), { resource, datasetId } = await this.createdNative(scope, bound);
|
|
1266
|
+
const observed = resource;
|
|
1267
|
+
ensure(Object.entries(body).every(([key, value]) => key === "dataset_id" && requestedDataset !== void 0 && datasetId === requestedDataset || kind === "pixel" && key === "aam_fields" && Array.isArray(value) && !value.length && observed.aam_opt_in === false && observed[key] == null || same({ [key]: observed[key] }, { [key]: value })), "created measurement fields differ from the request");
|
|
1268
|
+
ensure(!requestedDataset || datasetId === requestedDataset, "created integration has a different dataset");
|
|
1269
|
+
if (kind === "mobile_app") {
|
|
1270
|
+
const mobile = resource;
|
|
1271
|
+
this.exclusive(scope, mobile);
|
|
1272
|
+
if (!mobile.shared_ad_accounts.some((a) => a.id === scope.account_id)) await this.client.mutate(`${path}/${id}/ad_accounts/${scope.account_id}`, "POST", void 0, z9.undefined());
|
|
1273
|
+
const actual = await this.rawMobile(scope, id);
|
|
1274
|
+
this.exclusive(scope, actual);
|
|
1275
|
+
ensure(actual.shared_ad_accounts.some((a) => a.id === scope.account_id), "created mobile-app sharing readback unconfirmed");
|
|
1276
|
+
receipt = this.bind(scope, kind, id, datasetId);
|
|
1277
|
+
return this.result([id, ...datasetId ? [datasetId] : []], { resource_receipt: receipt, next_tool: "spotify_created_measurement", mobile_app_id: id, ...datasetId ? { dataset_id: datasetId } : {} });
|
|
1278
|
+
}
|
|
1279
|
+
ensure(datasetId, "created integration has no verified dataset ID");
|
|
1280
|
+
knownDataset = datasetId;
|
|
1281
|
+
receipt = this.bind(scope, kind, id, datasetId);
|
|
1282
|
+
const dataset = await this.rawDataset(scope, datasetId);
|
|
1283
|
+
ensure(kind === "pixel" ? dataset.pixel?.id === id : dataset.capi_integration?.capi_connection_id === id, "created dataset does not bind the returned integration");
|
|
1284
|
+
await this.shareCreatedDataset(scope, datasetId);
|
|
1285
|
+
return this.result([id, datasetId], { resource_receipt: receipt, next_tool: "spotify_created_measurement", dataset_id: datasetId });
|
|
1286
|
+
} catch {
|
|
1287
|
+
return this.uncertain([id, ...knownDataset ? [knownDataset] : []], receipt);
|
|
1288
|
+
}
|
|
1289
|
+
} };
|
|
1290
|
+
}
|
|
1291
|
+
async planUpdate(op, scope, proof) {
|
|
1292
|
+
let current, body, path, kind, id, readback;
|
|
1293
|
+
if (op.tool === "spotify_update_mobile_app") {
|
|
1294
|
+
const input = updateMobile.parse(op.payload), row = await this.mobile(scope, input.mobile_app_id, proof);
|
|
1295
|
+
this.exclusive(scope, row);
|
|
1296
|
+
this.expected(scope, "mobile_app", row, input.expected_configuration_hash);
|
|
1297
|
+
const { mobile_app_id: _id, resource_receipt: _receipt, expected_configuration_hash: _hash, ...fields } = input;
|
|
1298
|
+
current = row;
|
|
1299
|
+
body = fields;
|
|
1300
|
+
kind = "mobile_app";
|
|
1301
|
+
id = row.id;
|
|
1302
|
+
path = `${this.base(scope)}/mobile_apps/${id}`;
|
|
1303
|
+
readback = () => this.rawMobile(scope, id);
|
|
1304
|
+
} else {
|
|
1305
|
+
const input = op.tool === "spotify_update_pixel" ? updatePixel.parse(op.payload) : op.tool === "spotify_update_capi_integration" ? updateCapi.parse(op.payload) : op.tool === "spotify_update_dataset" ? updateDataset.parse(op.payload) : void 0;
|
|
1306
|
+
if (!input) throw new AdportError5("INVALID_INPUT", "spotify: unsupported measurement update");
|
|
1307
|
+
const dataset = await this.dataset(scope, input.dataset_id, proof);
|
|
1308
|
+
this.exclusive(scope, dataset);
|
|
1309
|
+
const { dataset_id: _id, resource_receipt: _receipt, expected_configuration_hash: _hash, ...fields } = input;
|
|
1310
|
+
body = fields;
|
|
1311
|
+
if (op.tool === "spotify_update_pixel") {
|
|
1312
|
+
ensure(dataset.pixel, "dataset has no verified Pixel");
|
|
1313
|
+
const pixel = await this.rawPixel(scope, dataset.pixel.id);
|
|
1314
|
+
this.verifyIntegrationBinding(dataset, "pixel", pixel.id, pixel.dataset_id);
|
|
1315
|
+
current = pixel;
|
|
1316
|
+
kind = "pixel";
|
|
1317
|
+
id = pixel.id;
|
|
1318
|
+
path = `${this.base(scope)}/pixels/${id}`;
|
|
1319
|
+
readback = () => this.rawPixel(scope, id);
|
|
1320
|
+
} else if (op.tool === "spotify_update_capi_integration") {
|
|
1321
|
+
ensure(dataset.capi_integration, "dataset has no verified CAPI integration");
|
|
1322
|
+
const capi = await this.rawCapi(scope, dataset.capi_integration.capi_connection_id);
|
|
1323
|
+
this.verifyIntegrationBinding(dataset, "capi", capi.capi_connection_id, capi.dataset_id);
|
|
1324
|
+
current = capi;
|
|
1325
|
+
kind = "capi";
|
|
1326
|
+
id = capi.capi_connection_id;
|
|
1327
|
+
path = `${this.base(scope)}/capi/${id}`;
|
|
1328
|
+
readback = () => this.rawCapi(scope, id);
|
|
1329
|
+
} else {
|
|
1330
|
+
current = dataset;
|
|
1331
|
+
kind = "dataset";
|
|
1332
|
+
id = dataset.id;
|
|
1333
|
+
path = `${this.base(scope)}/datasets/${id}`;
|
|
1334
|
+
readback = () => this.rawDataset(scope, id);
|
|
1335
|
+
}
|
|
1336
|
+
this.expected(scope, kind, current, input.expected_configuration_hash);
|
|
1337
|
+
}
|
|
1338
|
+
const expected = { ...current, ...body };
|
|
1339
|
+
return { ...this.review(scope, `Update Spotify ${kind.replaceAll("_", " ")} "${current.name}"`, "update", body, current), execute: async () => {
|
|
1340
|
+
let accepted = false;
|
|
1341
|
+
try {
|
|
1342
|
+
await this.client.mutate(path, "PATCH", body, z9.object({}));
|
|
1343
|
+
accepted = true;
|
|
1344
|
+
const actual = await readback();
|
|
1345
|
+
ensure(digest(scope, kind, actual) === digest(scope, kind, expected), "measurement update readback differs");
|
|
1346
|
+
} catch (error) {
|
|
1347
|
+
if (!accepted && error instanceof AdportError5 && /HTTP (400|401|403|404|409|422)\b/.test(error.message)) throw error;
|
|
1348
|
+
return this.uncertain([id]);
|
|
1349
|
+
}
|
|
1350
|
+
return this.result([id]);
|
|
1351
|
+
} };
|
|
1352
|
+
}
|
|
1353
|
+
async planSharing(op, scope, proof) {
|
|
1354
|
+
const mobile = op.tool === "spotify_set_mobile_app_sharing", input = mobile ? mobileSharing.parse(op.payload) : datasetSharing.parse(op.payload);
|
|
1355
|
+
const id = "mobile_app_id" in input ? input.mobile_app_id : input.dataset_id, kind = mobile ? "mobile_app" : "dataset";
|
|
1356
|
+
const current = mobile ? await this.mobile(scope, id, proof) : await this.dataset(scope, id, proof);
|
|
1357
|
+
ensure(current.shared_ad_accounts, "native sharing dependencies are unavailable");
|
|
1358
|
+
this.expected(scope, kind, current, input.expected_configuration_hash);
|
|
1359
|
+
const shared = current.shared_ad_accounts.some((a) => a.id === scope.account_id), path = `${this.base(scope)}/${mobile ? "mobile_apps" : "datasets"}/${id}/ad_accounts/${scope.account_id}`;
|
|
1360
|
+
const targetShares = [...current.shared_ad_accounts.filter((a) => a.id !== scope.account_id), ...input.shared ? [{ id: scope.account_id }] : []], expected = { ...current, shared_ad_accounts: targetShares };
|
|
1361
|
+
return { ...this.review(scope, `${input.shared ? "Share" : "Unshare"} Spotify ${kind.replaceAll("_", " ")} with the selected account`, "update", { shared: input.shared }, { shared }, [...commonNotes, `Only account ${scope.account_id} changes. Other account shares are preserved. Unsharing can stop this account using the measurement source.`]), execute: async () => {
|
|
1362
|
+
if (shared === input.shared) return this.result([id], { changed: false, shared_with_selected_account: shared });
|
|
1363
|
+
const receipt = this.bind(scope, kind, id, void 0, "sharing");
|
|
1364
|
+
let accepted = false;
|
|
1365
|
+
try {
|
|
1366
|
+
await this.client.mutate(path, input.shared ? "POST" : "DELETE", void 0, z9.undefined());
|
|
1367
|
+
accepted = true;
|
|
1368
|
+
const actual = mobile ? await this.rawMobile(scope, id) : await this.rawDataset(scope, id);
|
|
1369
|
+
ensure(digest(scope, kind, actual) === digest(scope, kind, expected), "native sharing readback differs");
|
|
1370
|
+
} catch (error) {
|
|
1371
|
+
if (!accepted && error instanceof AdportError5 && /HTTP (400|401|403|404|409|422)\b/.test(error.message)) throw error;
|
|
1372
|
+
return this.uncertain([id], receipt);
|
|
1373
|
+
}
|
|
1374
|
+
return this.result([id], { resource_receipt: receipt, next_tool: "spotify_measurement_sharing_status", shared_with_selected_account: input.shared });
|
|
1375
|
+
} };
|
|
1376
|
+
}
|
|
1377
|
+
async planDataset(op, scope) {
|
|
1378
|
+
const input = createDataset.parse(op.payload), selected = [];
|
|
1379
|
+
for (const source of input.sources) {
|
|
1380
|
+
const proof = this.proof(scope.account_id, source.resource_receipt), dataset = await this.dataset(scope, source.dataset_id, proof);
|
|
1381
|
+
this.exclusive(scope, dataset);
|
|
1382
|
+
this.expected(scope, "dataset", dataset, source.expected_configuration_hash);
|
|
1383
|
+
if (dataset.pixel?.integration_id === source.integration_id) {
|
|
1384
|
+
const pixel = await this.rawPixel(scope, dataset.pixel.id);
|
|
1385
|
+
this.verifyIntegrationBinding(dataset, "pixel", pixel.id, pixel.dataset_id);
|
|
1386
|
+
selected.push({ dataset, integration_id: source.integration_id, kind: "pixel", id: pixel.id });
|
|
1387
|
+
} else if (dataset.capi_integration?.integration_id === source.integration_id) {
|
|
1388
|
+
const capi = await this.rawCapi(scope, dataset.capi_integration.capi_connection_id);
|
|
1389
|
+
this.verifyIntegrationBinding(dataset, "capi", capi.capi_connection_id, capi.dataset_id);
|
|
1390
|
+
selected.push({ dataset, integration_id: source.integration_id, kind: "capi", id: capi.capi_connection_id });
|
|
1391
|
+
} else throw new AdportError5("INVALID_INPUT", "spotify: integration is not present in its approved source dataset");
|
|
1392
|
+
}
|
|
1393
|
+
const body = { name: input.name, integration_ids: selected.map((s) => s.integration_id) };
|
|
1394
|
+
return { ...this.review(scope, `Create Spotify dataset "${input.name}" from existing integrations`, "create", body, void 0, [...commonNotes, "This can reroute existing integrations and affect their measurement. Prefer creating Pixel first and adding CAPI with that dataset_id; native integration regrouping can leave inconsistent source routing, which readback must reject.", "The new dataset is shared only with the selected ad account."]), execute: async () => {
|
|
1395
|
+
let id;
|
|
1396
|
+
try {
|
|
1397
|
+
id = (await this.client.mutate(`${this.base(scope)}/datasets`, "POST", body, z9.object({ id: spotifyId }))).id;
|
|
1398
|
+
} catch (error) {
|
|
1399
|
+
if (error instanceof AdportError5 && /HTTP (400|401|403|404|409|422)\b/.test(error.message)) throw error;
|
|
1400
|
+
return this.uncertain([]);
|
|
1401
|
+
}
|
|
1402
|
+
const receipt = this.bind(scope, "dataset", id, id);
|
|
1403
|
+
try {
|
|
1404
|
+
ensure(!selected.some((s) => s.dataset.id === id), "dataset creation returned an existing source ID");
|
|
1405
|
+
const actual = await this.rawDataset(scope, id);
|
|
1406
|
+
ensure(actual.name === input.name && selected.every((s) => contains(actual, s.integration_id)), "created dataset membership mismatch");
|
|
1407
|
+
const previous = /* @__PURE__ */ new Map();
|
|
1408
|
+
for (const source of selected) {
|
|
1409
|
+
if (!previous.has(source.dataset.id)) previous.set(source.dataset.id, await this.rawDataset(scope, source.dataset.id));
|
|
1410
|
+
ensure(!contains(previous.get(source.dataset.id), source.integration_id), "native regrouping retained the integration in its source dataset");
|
|
1411
|
+
if (source.kind === "pixel") {
|
|
1412
|
+
const resource = await this.rawPixel(scope, source.id);
|
|
1413
|
+
this.verifyIntegrationBinding(actual, "pixel", resource.id, resource.dataset_id);
|
|
1414
|
+
} else {
|
|
1415
|
+
const resource = await this.rawCapi(scope, source.id);
|
|
1416
|
+
this.verifyIntegrationBinding(actual, "capi", resource.capi_connection_id, resource.dataset_id);
|
|
1417
|
+
}
|
|
1418
|
+
}
|
|
1419
|
+
await this.shareCreatedDataset(scope, id);
|
|
1420
|
+
} catch {
|
|
1421
|
+
return this.uncertain([id], receipt);
|
|
1422
|
+
}
|
|
1423
|
+
return this.result([id], { resource_receipt: receipt, next_tool: "spotify_created_measurement", dataset_id: id });
|
|
1424
|
+
} };
|
|
1425
|
+
}
|
|
1426
|
+
async planRemove(op, scope, proof) {
|
|
1427
|
+
const input = removeIntegration.parse(op.payload), current = await this.dataset(scope, input.dataset_id, proof);
|
|
1428
|
+
this.exclusive(scope, current);
|
|
1429
|
+
this.expected(scope, "dataset", current, input.expected_configuration_hash);
|
|
1430
|
+
ensure(contains(current, input.integration_id), "integration is not present in the selected dataset");
|
|
1431
|
+
return { ...this.review(scope, "Remove Spotify dataset integration into a new native dataset", "remove", { dataset_id: current.id, integration_id: input.integration_id }, void 0, [...commonNotes, "Native removal creates another dataset for the integration. It does not delete the integration or stop website code. Ads using the old dataset can lose measurement."]), execute: async () => {
|
|
1432
|
+
let created;
|
|
1433
|
+
try {
|
|
1434
|
+
created = await this.client.mutate(`${this.base(scope)}/datasets/${current.id}/integrations/${input.integration_id}`, "DELETE", void 0, z9.object({ id: spotifyId }));
|
|
1435
|
+
} catch (error) {
|
|
1436
|
+
if (error instanceof AdportError5 && /HTTP (400|401|403|404|409|422)\b/.test(error.message)) throw error;
|
|
1437
|
+
return this.uncertain([current.id]);
|
|
1438
|
+
}
|
|
1439
|
+
if (created.id === current.id) return this.uncertain([current.id]);
|
|
1440
|
+
const receipt = this.bind(scope, "dataset", created.id, created.id);
|
|
1441
|
+
try {
|
|
1442
|
+
const next = await this.rawDataset(scope, created.id), previous = await this.rawDataset(scope, current.id);
|
|
1443
|
+
ensure(contains(next, input.integration_id) && !contains(previous, input.integration_id), "integration removal readback is inconsistent");
|
|
1444
|
+
if (next.pixel?.integration_id === input.integration_id) {
|
|
1445
|
+
const resource = await this.rawPixel(scope, next.pixel.id);
|
|
1446
|
+
this.verifyIntegrationBinding(next, "pixel", resource.id, resource.dataset_id);
|
|
1447
|
+
}
|
|
1448
|
+
if (next.capi_integration?.integration_id === input.integration_id) {
|
|
1449
|
+
const resource = await this.rawCapi(scope, next.capi_integration.capi_connection_id);
|
|
1450
|
+
this.verifyIntegrationBinding(next, "capi", resource.capi_connection_id, resource.dataset_id);
|
|
1451
|
+
}
|
|
1452
|
+
} catch {
|
|
1453
|
+
return this.uncertain([current.id, created.id], receipt);
|
|
1454
|
+
}
|
|
1455
|
+
return this.result([current.id, created.id], { resource_receipt: receipt, next_tool: "spotify_created_measurement", dataset_id: created.id });
|
|
1456
|
+
} };
|
|
1457
|
+
}
|
|
1458
|
+
async plan(op) {
|
|
1459
|
+
if (capiCredentialWrites.has(op.tool)) return this.credentials.plan(op);
|
|
1460
|
+
if (op.tool === "spotify_create_dataset") for (const source of createDataset.parse(op.payload).sources) this.proof(op.accountId, source.resource_receipt);
|
|
1461
|
+
const proof = this.proof(op.accountId, typeof op.payload.resource_receipt === "string" ? op.payload.resource_receipt : void 0), scope = await this.scope(op.accountId);
|
|
1462
|
+
this.checkProof(scope, proof);
|
|
1463
|
+
if (op.tool === "spotify_create_pixel" || op.tool === "spotify_create_capi_integration" || op.tool === "spotify_create_mobile_app") return this.planCreate(op, scope, proof);
|
|
1464
|
+
if (op.tool === "spotify_create_dataset") return this.planDataset(op, scope);
|
|
1465
|
+
if (op.tool === "spotify_remove_dataset_integration") return this.planRemove(op, scope, proof);
|
|
1466
|
+
if (op.tool === "spotify_set_dataset_sharing" || op.tool === "spotify_set_mobile_app_sharing") return this.planSharing(op, scope, proof);
|
|
1467
|
+
return this.planUpdate(op, scope, proof);
|
|
1468
|
+
}
|
|
1469
|
+
};
|
|
1470
|
+
|
|
1471
|
+
// src/measurement-tools.ts
|
|
1472
|
+
import { defineTool as defineTool2, guardedWriteTool as guardedWriteTool2 } from "@adport/core";
|
|
1473
|
+
import { z as z10 } from "zod";
|
|
1474
|
+
var measurementWriteNames = /* @__PURE__ */ new Set([...capiCredentialWrites, "spotify_create_pixel", "spotify_update_pixel", "spotify_create_capi_integration", "spotify_update_capi_integration", "spotify_create_dataset", "spotify_update_dataset", "spotify_remove_dataset_integration", "spotify_set_dataset_sharing", "spotify_create_mobile_app", "spotify_update_mobile_app", "spotify_set_mobile_app_sharing"]);
|
|
1475
|
+
function spotifyMeasurementTools(provider) {
|
|
1476
|
+
const catalog = { category: "measurement", exposure: "specialist" };
|
|
1477
|
+
const read = (name2, description2, input, handler) => defineTool2({ name: name2, namespace: "spotify", description: description2, input, catalog, presentation: "records", annotations: { readOnly: true }, handler });
|
|
1478
|
+
const write = (name2, description2, payload, kind, destructive = false) => guardedWriteTool2({ name: name2, namespace: "spotify", provider: "spotify", description: description2, payload, catalog, kind, destructive });
|
|
1479
|
+
const account3 = { account_id: spotifyId }, dataset = z10.object({ ...account3, ...datasetTarget });
|
|
1480
|
+
return [
|
|
1481
|
+
read("spotify_capi_credentials", "List active CAPI credential IDs, creation times and private storage status for an integration shared only with this selected account. Returns snapshot hashes for mutations; never returns token values or sends events.", capiCredentialTarget.extend(account3), (v) => provider.measurement.credentials.list(v)),
|
|
1482
|
+
write("spotify_create_capi_credential", "Create one long-lived CAPI credential and store it privately in Adport. Requires current hashes from spotify_capi_credentials and explicit access acknowledgement. No secret is returned; no events are sent. Never repeat an unconfirmed creation.", createCapiCredential, "create"),
|
|
1483
|
+
write("spotify_store_capi_credential", "Store one selected active native CAPI credential privately in Adport without creating another token. Requires fresh credential/context hashes and explicit access acknowledgement. The token is fetched server-side and never returned.", storeCapiCredential, "create"),
|
|
1484
|
+
write("spotify_revoke_capi_credential", "Revoke one selected CAPI credential and remove its Adport copy after native confirmation. May stop existing event publishers. Fresh hashes and explicit acknowledgement required. Also reconciles a stored copy when native revocation already completed. No automatic native retries.", revokeCapiCredential, "remove", true),
|
|
1485
|
+
read("spotify_measurement_context", "Read the selected account\u2019s verified business and shared dataset topology. Read an individual resource before a mutation to obtain its full configuration_hash. Other account identities and business-wide inventory are excluded; no tracking or credentials are created.", z10.object(account3), (v) => provider.measurement.context(v.account_id)),
|
|
1486
|
+
read("spotify_datasets", "List only datasets shared with this account. The native endpoint has no limit/offset query; returns explicit completeness rather than inventing pagination.", z10.object(account3), (v) => provider.measurement.datasets(v.account_id)),
|
|
1487
|
+
read("spotify_get_dataset", "Read one shared dataset and its configuration_hash. An unshared approved creation requires its signed resource_receipt. Other account identities are omitted.", dataset, (v) => provider.measurement.getDataset(v)),
|
|
1488
|
+
read("spotify_get_pixel", "Read the Pixel bound to an authorized dataset, including matching settings and configuration_hash. Native Pixel IDs alone do not authorize business-wide reads.", dataset, (v) => provider.measurement.getPixel(v)),
|
|
1489
|
+
read("spotify_get_capi_integration", "Read a CAPI connection bound to an authorized dataset. Returns configuration_hash and metadata only, never active credentials.", dataset, (v) => provider.measurement.getCapi(v)),
|
|
1490
|
+
read("spotify_mobile_apps", "Read mobile measurement apps shared with this account using native pagination. Link tokens and other account identities are omitted.", z10.object({ ...account3, limit: z10.number().int().positive().max(50).default(50), offset: z10.number().int().nonnegative().default(0) }), (v) => provider.measurement.mobileApps(v)),
|
|
1491
|
+
read("spotify_get_mobile_app", "Read one account-shared or approved-created mobile app with its configuration_hash. Native MMP link tokens are omitted.", z10.object({ ...account3, ...mobileTarget }), (v) => provider.measurement.getMobile(v)),
|
|
1492
|
+
read("spotify_dataset_diagnostics", "Read native DAILY/HOURLY source activity for an authorized dataset. Diagnostics can lag 20 minutes; activity does not prove campaign attribution. Sends no conversion events.", z10.object({ ...account3, ...datasetTarget, granularities: z10.array(z10.enum(["DAILY", "HOURLY"])).min(1).max(2).refine((v) => new Set(v).size === v.length, "Granularities must be unique").default(["DAILY"]), datasource_ids: z10.array(z10.string().min(1)).min(1).max(100).optional() }), (v) => provider.measurement.diagnostics(v)),
|
|
1493
|
+
read("spotify_created_measurement", "Reconcile the exact created resource and receipt-bound parent with current account/business access. A missing child binding requires the locked parent to independently name this exact resource. Explicit conflicts never follow another parent. Read-only; never replays a write.", z10.object({ ...account3, resource_receipt: receiptInput }), (v) => provider.measurement.created(v)),
|
|
1494
|
+
read("spotify_measurement_sharing_status", "Reconcile sharing with the signed receipt from an approved share/unshare operation. Returns only selected-account sharing state; a status receipt does not grant content access after unsharing.", z10.object({ ...account3, resource_receipt: receiptInput }), (v) => provider.measurement.sharingStatus(v)),
|
|
1495
|
+
write("spotify_create_pixel", "Create a Pixel and verify its native dataset, then share only with the selected account. AAM defaults off; opt-in requires explicit acknowledgement. Supports existing dataset_id with its current hash. No website install or event sending.", createPixel, "create"),
|
|
1496
|
+
write("spotify_update_pixel", "Replace the supplied name or domain on an account-owned Pixel using its current configuration_hash. Preserves matching, routing and other settings. Rejects stale or shared configuration and verifies the result by readback.", updatePixel, "update", true),
|
|
1497
|
+
write("spotify_create_capi_integration", "Create a CAPI connection in a new or verified existing dataset, then verify sharing with the selected account. Does not issue tokens or send events. Returns a signed receipt for partial creation recovery; never retries automatically.", createCapi, "create"),
|
|
1498
|
+
write("spotify_update_capi_integration", "Replace the name of an authorized CAPI connection using its current configuration_hash. Preserves dataset routing, credentials and events. Verifies the result by readback.", updateCapi, "update", true),
|
|
1499
|
+
write("spotify_create_dataset", "Create a dataset from explicit account-owned integrations and source snapshots, acknowledging measurement rerouting. Independently checks each native integration\u2019s new dataset binding and selected-account sharing. Prefer Pixel-first plus CAPI dataset_id for a shared topology.", createDataset, "create", true),
|
|
1500
|
+
write("spotify_update_dataset", "Replace the name of an authorized dataset using its current configuration_hash. Preserves sources and sharing. Rejects edits when another account shares the dataset or dependencies are unknown.", updateDataset, "update", true),
|
|
1501
|
+
write("spotify_remove_dataset_integration", "Remove one verified integration from a dataset. Spotify moves it to a newly created dataset; this does not delete the source or remove website code. Requires current snapshot and explicit acknowledgement; returns signed recovery context.", removeIntegration, "remove", true),
|
|
1502
|
+
write("spotify_set_dataset_sharing", "Share/unshare a verified dataset only with the selected account, preserving all other shares. Requires current configuration_hash; unsharing needs measurement-effect acknowledgement. An unshared creation requires its receipt. Native readback and signed status reconciliation prevent unsafe replay.", datasetSharing, "update", true),
|
|
1503
|
+
write("spotify_create_mobile_app", "Register native mobile measurement metadata and share the new app only with this account. Supports current MMP enums including SINGULAR. Does not install a partner SDK; link tokens are not returned.", createMobile, "create"),
|
|
1504
|
+
write("spotify_update_mobile_app", "Replace the name and supplied attribution settings of an account-owned mobile app using its current configuration_hash. Preserves omitted fields and verifies the result by readback. Link tokens stay private and unchanged.", updateMobile, "update", true),
|
|
1505
|
+
write("spotify_set_mobile_app_sharing", "Share/unshare only this account\u2019s mobile-app association using the current hash. Unsharing needs explicit measurement-effect acknowledgement; other shares are preserved and the result is independently verified.", mobileSharing, "update", true)
|
|
1506
|
+
];
|
|
1507
|
+
}
|
|
1508
|
+
|
|
156
1509
|
// src/provider.ts
|
|
157
1510
|
var LEVEL = { account: "AD_ACCOUNT", campaign: "CAMPAIGN", ad_group: "AD_SET", ad: "AD" };
|
|
158
1511
|
var FIELDS = { spend: "SPEND", impressions: "IMPRESSIONS", clicks: "CLICKS", conversions: "PURCHASES", conversion_value: "REVENUE" };
|
|
@@ -164,11 +1517,17 @@ var DERIVED = {
|
|
|
164
1517
|
roas: ["conversion_value", "spend", 1]
|
|
165
1518
|
};
|
|
166
1519
|
var SpotifyAdsProvider = class {
|
|
167
|
-
constructor(client) {
|
|
1520
|
+
constructor(client, media = new LocalMediaResolver(), options = {}) {
|
|
168
1521
|
this.client = client;
|
|
1522
|
+
this.creatives = new SpotifyCreativeService(client, media);
|
|
1523
|
+
this.management = new SpotifyManagementService(client, this.creatives);
|
|
1524
|
+
this.measurement = new SpotifyMeasurementService(client, options.resourceSecrets);
|
|
169
1525
|
}
|
|
170
1526
|
client;
|
|
171
1527
|
id = "spotify";
|
|
1528
|
+
creatives;
|
|
1529
|
+
management;
|
|
1530
|
+
measurement;
|
|
172
1531
|
capabilities() {
|
|
173
1532
|
return { serverDryRun: false };
|
|
174
1533
|
}
|
|
@@ -176,24 +1535,24 @@ var SpotifyAdsProvider = class {
|
|
|
176
1535
|
return { pauseCampaign: (accountId, campaignId) => ({ tool: "spotify_set_campaign_status", input: { account_id: accountId, campaign_id: campaignId, status: "PAUSED" } }) };
|
|
177
1536
|
}
|
|
178
1537
|
async listAccounts() {
|
|
179
|
-
const { businesses } = await this.client.get("businesses",
|
|
1538
|
+
const { businesses } = await this.client.get("businesses", z11.object({ businesses: z11.array(businessSchema) }));
|
|
180
1539
|
const accounts = /* @__PURE__ */ new Map();
|
|
181
1540
|
for (const business of businesses) {
|
|
182
|
-
const { ad_accounts } = await this.client.get(`businesses/${business.id}/ad_accounts`,
|
|
183
|
-
for (const
|
|
1541
|
+
const { ad_accounts } = await this.client.get(`businesses/${business.id}/ad_accounts`, z11.object({ ad_accounts: z11.array(accountSchema) }));
|
|
1542
|
+
for (const account3 of ad_accounts) accounts.set(account3.id, { provider: this.id, id: account3.id, name: account3.name, currency: account3.currency_code, status: account3.status });
|
|
184
1543
|
}
|
|
185
1544
|
return [...accounts.values()];
|
|
186
1545
|
}
|
|
187
1546
|
async listCampaigns(accountId) {
|
|
188
1547
|
const path = `ad_accounts/${spotifyId.parse(accountId)}/campaigns`;
|
|
189
|
-
const schema =
|
|
1548
|
+
const schema = z11.object({ paging: pagingSchema, campaigns: z11.array(campaignSchema) });
|
|
190
1549
|
const rows = [];
|
|
191
1550
|
const seen = /* @__PURE__ */ new Set();
|
|
192
|
-
for (let
|
|
1551
|
+
for (let page3 = 0, offset = 0; page3 < 1e3; page3++) {
|
|
193
1552
|
const data = await this.client.get(path, schema, new URLSearchParams({ limit: "50", offset: String(offset), sort_field: "ID", sort_direction: "ASC" }));
|
|
194
|
-
if (data.paging.offset !== offset) throw new
|
|
1553
|
+
if (data.paging.offset !== offset) throw new AdportError6("PROVIDER_ERROR", "spotify: campaign pagination changed offset");
|
|
195
1554
|
for (const campaign of data.campaigns) {
|
|
196
|
-
if (seen.has(campaign.id)) throw new
|
|
1555
|
+
if (seen.has(campaign.id)) throw new AdportError6("PROVIDER_ERROR", "spotify: campaign pagination repeated an entity");
|
|
197
1556
|
seen.add(campaign.id);
|
|
198
1557
|
rows.push(campaign);
|
|
199
1558
|
}
|
|
@@ -201,49 +1560,49 @@ var SpotifyAdsProvider = class {
|
|
|
201
1560
|
if (offset >= data.paging.total_results) return rows;
|
|
202
1561
|
if (!data.campaigns.length) break;
|
|
203
1562
|
}
|
|
204
|
-
throw new
|
|
1563
|
+
throw new AdportError6("PROVIDER_ERROR", "spotify: campaign pagination did not terminate; refusing incomplete results");
|
|
205
1564
|
}
|
|
206
1565
|
async getAdSet(accountId, adSetId) {
|
|
207
1566
|
const data = await this.client.get(`ad_accounts/${spotifyId.parse(accountId)}/ad_sets/${spotifyId.parse(adSetId)}`, adSetSchema);
|
|
208
|
-
if (data.id !== adSetId) throw new
|
|
1567
|
+
if (data.id !== adSetId) throw new AdportError6("PROVIDER_ERROR", "spotify: ad set response ID mismatch");
|
|
209
1568
|
return data;
|
|
210
1569
|
}
|
|
211
|
-
async report(
|
|
212
|
-
const range = resolveDateRange(
|
|
213
|
-
const start =
|
|
1570
|
+
async report(query3) {
|
|
1571
|
+
const range = resolveDateRange(query3.dateRange);
|
|
1572
|
+
const start = z11.iso.date().parse(range.start), end = z11.iso.date().parse(range.end);
|
|
214
1573
|
const days = (Date.parse(end) - Date.parse(start)) / 864e5;
|
|
215
|
-
if (days < 0 || days > 90) throw new
|
|
216
|
-
const limit =
|
|
217
|
-
if (!Number.isSafeInteger(limit) || limit < 1) throw new
|
|
1574
|
+
if (days < 0 || days > 90) throw new AdportError6("INVALID_INPUT", "spotify: report end must be on/after start and within 90 days");
|
|
1575
|
+
const limit = query3.limit ?? 1e3;
|
|
1576
|
+
if (!Number.isSafeInteger(limit) || limit < 1) throw new AdportError6("INVALID_INPUT", "spotify: report limit must be a positive integer");
|
|
218
1577
|
const fields = /* @__PURE__ */ new Set();
|
|
219
|
-
for (const metric of
|
|
1578
|
+
for (const metric of query3.metrics) {
|
|
220
1579
|
if (metric in FIELDS) fields.add(FIELDS[metric]);
|
|
221
1580
|
else if (metric in DERIVED) for (const dependency of DERIVED[metric].slice(0, 2)) fields.add(FIELDS[dependency]);
|
|
222
1581
|
}
|
|
223
|
-
if (!fields.size) throw new
|
|
224
|
-
const accountIds = [...new Set(
|
|
1582
|
+
if (!fields.size) throw new AdportError6("INVALID_INPUT", "spotify: report requires at least one supported metric");
|
|
1583
|
+
const accountIds = [...new Set(query3.accountIds ?? (await this.listAccounts()).map((a) => a.id))];
|
|
225
1584
|
const rows = [];
|
|
226
1585
|
for (const id of accountIds) {
|
|
227
1586
|
const accountId = spotifyId.parse(id);
|
|
228
|
-
let
|
|
229
|
-
for (const field of fields)
|
|
1587
|
+
let params2 = new URLSearchParams({ entity_type: LEVEL[query3.level], report_start: `${start}T00:00:00Z`, report_end: `${end}T00:00:00Z`, granularity: "LIFETIME", limit: "50" });
|
|
1588
|
+
for (const field of fields) params2.append("fields", field);
|
|
230
1589
|
const tokens = /* @__PURE__ */ new Set();
|
|
231
1590
|
const entities = /* @__PURE__ */ new Set();
|
|
232
1591
|
while (true) {
|
|
233
|
-
const data = await this.client.get(`ad_accounts/${accountId}/aggregate_reports`, reportSchema,
|
|
234
|
-
if (data.granularity !== "LIFETIME") throw new
|
|
1592
|
+
const data = await this.client.get(`ad_accounts/${accountId}/aggregate_reports`, reportSchema, params2);
|
|
1593
|
+
if (data.granularity !== "LIFETIME") throw new AdportError6("PROVIDER_ERROR", "spotify: unexpected report granularity");
|
|
235
1594
|
for (const row of data.rows) {
|
|
236
|
-
if (row.entity_type !== LEVEL[
|
|
237
|
-
throw new
|
|
1595
|
+
if (row.entity_type !== LEVEL[query3.level] || query3.level === "account" && row.entity_id !== accountId || entities.has(row.entity_id)) {
|
|
1596
|
+
throw new AdportError6("PROVIDER_ERROR", "spotify: incorrectly scoped or duplicate report row");
|
|
238
1597
|
}
|
|
239
1598
|
entities.add(row.entity_id);
|
|
240
|
-
rows.push({ provider: this.id, accountId, entity: { level:
|
|
1599
|
+
rows.push({ provider: this.id, accountId, entity: { level: query3.level, id: row.entity_id, name: row.entity_name, status: row.entity_status }, metrics: normalize(row.stats, query3.metrics) });
|
|
241
1600
|
if (rows.length > limit) return { rows: rows.slice(0, limit), truncated: true };
|
|
242
1601
|
}
|
|
243
1602
|
if (!data.continuation_token) break;
|
|
244
|
-
if (tokens.has(data.continuation_token) || tokens.size >= 1e3) throw new
|
|
1603
|
+
if (tokens.has(data.continuation_token) || tokens.size >= 1e3) throw new AdportError6("PROVIDER_ERROR", "spotify: report pagination did not terminate");
|
|
245
1604
|
tokens.add(data.continuation_token);
|
|
246
|
-
|
|
1605
|
+
params2 = new URLSearchParams({ continuation_token: data.continuation_token });
|
|
247
1606
|
}
|
|
248
1607
|
}
|
|
249
1608
|
return { rows };
|
|
@@ -253,12 +1612,14 @@ var SpotifyAdsProvider = class {
|
|
|
253
1612
|
return { ...preview, serverValidated: false };
|
|
254
1613
|
}
|
|
255
1614
|
async applyWrite(op, guard) {
|
|
256
|
-
|
|
1615
|
+
const result = await (await this.plan(op, guard)).execute();
|
|
1616
|
+
return Array.isArray(result) ? { applied: true, resourceIds: result } : result;
|
|
257
1617
|
}
|
|
258
1618
|
async plan(op, guard) {
|
|
259
1619
|
const accountId = spotifyId.parse(op.accountId);
|
|
260
1620
|
const base = `ad_accounts/${accountId}`;
|
|
261
|
-
if (op.provider !== this.id) throw new
|
|
1621
|
+
if (op.provider !== this.id) throw new AdportError6("INVALID_INPUT", "spotify: provider mismatch");
|
|
1622
|
+
if (measurementWriteNames.has(op.tool)) return this.measurement.plan(op);
|
|
262
1623
|
if (op.tool === "spotify_create_campaign_draft" && op.kind === "create") {
|
|
263
1624
|
const input = createDraftSchema.parse(op.payload);
|
|
264
1625
|
const status = guard.forcePausedCreation ? "PAUSED" : input.status;
|
|
@@ -270,7 +1631,7 @@ var SpotifyAdsProvider = class {
|
|
|
270
1631
|
budgetDeltas: [],
|
|
271
1632
|
execute: async () => {
|
|
272
1633
|
const result = await this.client.mutate(`${base}/drafts/campaigns`, "POST", body, draftSchema);
|
|
273
|
-
if (result.ad_account_id !== accountId || result.status !== status) throw new
|
|
1634
|
+
if (result.ad_account_id !== accountId || result.status !== status) throw new AdportError6("PROVIDER_ERROR", "spotify: created draft response violated account/status expectations; inspect the draft before retrying");
|
|
274
1635
|
return [result.id];
|
|
275
1636
|
}
|
|
276
1637
|
};
|
|
@@ -279,7 +1640,7 @@ var SpotifyAdsProvider = class {
|
|
|
279
1640
|
const input = setStatusSchema.parse(op.payload);
|
|
280
1641
|
const path = `${base}/campaigns/${input.campaign_id}`;
|
|
281
1642
|
const current = await this.client.get(path, campaignSchema);
|
|
282
|
-
if (current.id !== input.campaign_id) throw new
|
|
1643
|
+
if (current.id !== input.campaign_id) throw new AdportError6("PROVIDER_ERROR", "spotify: campaign response ID mismatch");
|
|
283
1644
|
return {
|
|
284
1645
|
summary: `Change Spotify campaign "${current.name}" status`,
|
|
285
1646
|
changes: [`~ ${current.id} status: ${current.status} \u2192 ${input.status}`],
|
|
@@ -287,7 +1648,7 @@ var SpotifyAdsProvider = class {
|
|
|
287
1648
|
budgetDeltas: [],
|
|
288
1649
|
execute: async () => {
|
|
289
1650
|
const result = await this.client.mutate(path, "PATCH", { status: input.status }, campaignSchema);
|
|
290
|
-
if (result.id !== current.id || result.status !== input.status) throw new
|
|
1651
|
+
if (result.id !== current.id || result.status !== input.status) throw new AdportError6("PROVIDER_ERROR", "spotify: campaign update response mismatch; inspect before retrying");
|
|
291
1652
|
return [result.id];
|
|
292
1653
|
}
|
|
293
1654
|
};
|
|
@@ -305,19 +1666,19 @@ var SpotifyAdsProvider = class {
|
|
|
305
1666
|
execute: async () => {
|
|
306
1667
|
const result = await this.client.mutate(`${base}/ad_sets/${current.id}`, "PATCH", body, adSetSchema);
|
|
307
1668
|
if (result.id !== current.id || result.campaign_id !== current.campaign_id || budget && (result.budget.type !== budget.type || result.budget.micro_amount !== budget.micro_amount) || !budget && result.delivery !== body.delivery) {
|
|
308
|
-
throw new
|
|
1669
|
+
throw new AdportError6("PROVIDER_ERROR", "spotify: ad set update response mismatch; inspect before retrying");
|
|
309
1670
|
}
|
|
310
1671
|
return [result.id];
|
|
311
1672
|
}
|
|
312
1673
|
};
|
|
313
1674
|
}
|
|
314
|
-
|
|
1675
|
+
return managementWriteNames.has(op.tool) ? this.management.plan(op) : this.creatives.plan(op, guard);
|
|
315
1676
|
}
|
|
316
1677
|
};
|
|
317
1678
|
function normalize(stats, requested) {
|
|
318
1679
|
const raw = /* @__PURE__ */ new Map();
|
|
319
1680
|
for (const stat of stats) {
|
|
320
|
-
if (raw.has(stat.field_type)) throw new
|
|
1681
|
+
if (raw.has(stat.field_type)) throw new AdportError6("PROVIDER_ERROR", "spotify: duplicate report metric");
|
|
321
1682
|
raw.set(stat.field_type, stat.field_value);
|
|
322
1683
|
}
|
|
323
1684
|
const mapped = {};
|
|
@@ -332,27 +1693,70 @@ function normalize(stats, requested) {
|
|
|
332
1693
|
}
|
|
333
1694
|
|
|
334
1695
|
// src/tools.ts
|
|
335
|
-
import { z as
|
|
336
|
-
import { defineTool, guardedWriteTool } from "@adport/core";
|
|
1696
|
+
import { z as z13 } from "zod";
|
|
1697
|
+
import { defineTool as defineTool4, guardedWriteTool as guardedWriteTool4 } from "@adport/core";
|
|
1698
|
+
|
|
1699
|
+
// src/creative-tools.ts
|
|
1700
|
+
import { creativesOutput, defineTool as defineTool3, guardedWriteTool as guardedWriteTool3 } from "@adport/core";
|
|
1701
|
+
import { z as z12 } from "zod";
|
|
1702
|
+
var page2 = { limit: z12.number().int().positive().max(50).default(50), offset: z12.number().int().nonnegative().default(0) };
|
|
1703
|
+
var account2 = { account_id: spotifyId };
|
|
1704
|
+
var strings2 = z12.array(z12.string().min(1)).min(1).max(1e3);
|
|
1705
|
+
var estimate = { asset_format: assetFormat, bid_strategy: bidStrategy, targets: targets.refine((v) => Boolean(v.placements?.length), "Estimates require placements"), delivery_goal: deliveryGoal.optional(), frequency_caps: frequencyCaps.optional(), category: z12.string().regex(/^ADV_\d+_\d+$/).optional() };
|
|
1706
|
+
function spotifyCreativeTools(provider) {
|
|
1707
|
+
const read = (name2, description2, input, handler) => defineTool3({ name: name2, namespace: "spotify", description: description2, input, annotations: { readOnly: true }, handler });
|
|
1708
|
+
const write = (name2, description2, payload, kind = "update") => guardedWriteTool3({ name: name2, namespace: "spotify", provider: "spotify", description: description2, payload, kind });
|
|
1709
|
+
return [
|
|
1710
|
+
read("spotify_drafts", "List unpublished campaign, ad-set or ad drafts, with native pagination and hierarchy versions. This does not publish.", z12.object({ ...account2, entity: draftEntity, campaign_ids: z12.array(spotifyId).optional(), ad_set_ids: z12.array(spotifyId).optional(), ...page2 }).refine((v) => !(v.campaign_ids && v.entity !== "ad_sets") && !(v.ad_set_ids && v.entity !== "ads"), "Use campaign_ids for ad_sets or ad_set_ids for ads"), (input) => provider.creatives.drafts(input)),
|
|
1711
|
+
read("spotify_get_draft", "Read an account-owned draft and verify its parent hierarchy. Use the campaign draft version for validation/publication.", z12.object({ ...account2, entity: draftEntity, draft_id: spotifyId }), (input) => provider.creatives.get(input.account_id, input.entity, input.draft_id)),
|
|
1712
|
+
read("spotify_ad_sets", "Read published ad-set targeting, bidding, budgets and delivery, with pagination.", z12.object({ ...account2, campaign_ids: z12.array(spotifyId).optional(), ...page2 }), (input) => provider.creatives.page(input, "ad_sets", "ad_sets", { campaign_ids: input.campaign_ids })),
|
|
1713
|
+
defineTool3({ name: "spotify_ads", namespace: "spotify", description: "View published or draft ad copy and image/video/audio assets. Drafts include guarded copy-edit actions; publication remains separate.", input: z12.object({ ...account2, draft: z12.boolean().default(false), ad_set_ids: z12.array(spotifyId).optional(), ...page2 }), output: creativesOutput.passthrough(), presentation: "creatives", pagination: { cursorInput: "offset", cursorOutput: "next_offset" }, annotations: { readOnly: true }, handler: (input) => provider.creatives.ads(input) }),
|
|
1714
|
+
defineTool3({ name: "spotify_assets", namespace: "spotify", description: "View Spotify account image/video/audio assets and processing status with pagination.", input: z12.object({ ...account2, asset_types: z12.array(assetType).optional(), asset_statuses: z12.array(z12.enum(["ERROR", "PROCESSING", "READY", "WAITING_UPLOAD"])).optional(), name: z12.string().optional(), ...page2 }), output: creativesOutput.passthrough(), presentation: "creatives", pagination: { cursorInput: "offset", cursorOutput: "next_offset" }, annotations: { readOnly: true }, handler: (input) => provider.creatives.assets(input) }),
|
|
1715
|
+
read("spotify_get_asset", "Read an account-owned asset and processing status. No ad delivery changes.", z12.object({ ...account2, asset_id: spotifyId }), (input) => provider.creatives.asset(input.account_id, input.asset_id)),
|
|
1716
|
+
read("spotify_ad_categories", "Search Spotify\u2019s live advertiser-category codes for draft ad sets.", z12.object({ ...account2, q: z12.string().optional() }), (input) => provider.creatives.categories(input.q)),
|
|
1717
|
+
read("spotify_targeting_options", "Search native Spotify artist, genre, interest, language, playlist or podcast topic targeting.", z12.object({ ...account2, kind: z12.enum(["artists", "genres", "interests", "languages", "playlists", "episode_topics", "sensitive_topics"]), ids: strings2.optional(), q: z12.string().optional() }), (input) => provider.creatives.targeting(input)),
|
|
1718
|
+
read("spotify_geo_targets", "Search native geographical targeting IDs with country/type filters and pagination.", z12.object({ ...account2, country_code: z12.string().regex(/^[A-Z]{2}$/).optional(), ids: strings2.optional(), types: strings2.optional(), q: z12.string().optional(), language: z12.string().regex(/^[a-z]{2}$/).optional(), limit: z12.number().int().positive().max(1e3).default(50), offset: z12.number().int().nonnegative().default(0) }), (input) => provider.creatives.targeting({ ...input, kind: "geos" })),
|
|
1719
|
+
read("spotify_audience_estimate", "Get a non-binding audience/delivery estimate using a read-only POST. Native micro amounts and explicit placements are required; no audience or ad is created.", z12.object({ ...account2, ...estimate, start_date: z12.iso.datetime(), end_date: z12.iso.datetime().optional(), bid_micro_amount: z12.number().int().nonnegative().safe(), budget: budgetSchema.extend({ currency: z12.string().regex(/^[A-Z]{3}$/) }) }).refine((v) => !v.end_date || v.end_date > v.start_date, "End date must follow start date"), (input) => provider.creatives.estimate("audience", input)),
|
|
1720
|
+
read("spotify_bid_estimate", "Get a non-binding native bid estimate with explicit targeting/placements. No bids or delivery settings are changed.", z12.object({ ...account2, ...estimate, currency: z12.string().regex(/^[A-Z]{3}$/) }), (input) => provider.creatives.estimate("bid", input)),
|
|
1721
|
+
read("spotify_validate_draft", "Validate a specific campaign draft hierarchy version server-side without publishing. Returns native validation errors.", z12.object({ ...account2, ...publishDraft.shape }), (input) => provider.creatives.validate(input.account_id, input.draft_campaign_id, input.draft_hierarchy_version)),
|
|
1722
|
+
write("spotify_create_draft_ad_set", "Stage an unpublished ad set under a verified draft campaign. Monetary values are integer micros. Partial drafts are allowed; targeting requires placements and lifetime budgets require end_time.", createGroup, "create"),
|
|
1723
|
+
write("spotify_create_draft_ad", "Stage unpublished ad copy and existing account-owned asset IDs under a verified draft ad set. Does not publish or enable delivery.", createAd, "create"),
|
|
1724
|
+
write("spotify_update_draft_campaign", "Patch only supplied draft campaign fields. Publication is separate; status changes here affect only the draft.", updateCampaign),
|
|
1725
|
+
write("spotify_update_draft_ad_set", "Patch draft ad-set targeting, schedule, budget or bids. Preserves omitted nested targeting; arrays replace supplied dimensions. Amounts use micros.", updateGroup),
|
|
1726
|
+
write("spotify_update_draft_ad", "Patch unpublished ad copy/assets/CTA. Omitted assets and CTA fields are preserved; supplied tracking arrays replace the full array.", updateAd),
|
|
1727
|
+
write("spotify_create_draft_from_published", "Stage a copy of an account-owned published campaign/ad set/ad without changing delivery. Refuses to overwrite an existing draft.", draftMutation, "create"),
|
|
1728
|
+
write("spotify_delete_draft", "Delete only an unpublished draft. Delete child ad drafts first: parent deletion is refused while ads remain to prevent provider orphan records. Published entities remain unchanged.", draftMutation, "remove"),
|
|
1729
|
+
...["ads", "ad_sets"].map((entity) => write(`spotify_delete_draft_${entity}`, "Atomically delete account-owned drafts through the native batch endpoint. Delete child ads before ad sets to prevent provider orphan records. Published entities remain unchanged.", z12.object({ draft_ids: z12.array(spotifyId).min(1).max(entity === "ads" ? 100 : 40).refine((ids2) => new Set(ids2).size === ids2.length, "IDs must be unique") }), "remove")),
|
|
1730
|
+
write("spotify_publish_draft", "Spotify publishes ACTIVE even from a PAUSED draft. Blocked while paused_creation policy is enabled. Otherwise requires explicit acknowledge_active_publication=true, exact hierarchy version, budget checks and server validation.", publishDraft, "create"),
|
|
1731
|
+
write("spotify_create_asset", "Create account-owned asset metadata for a later checksum-bound upload. No creative is attached to an ad.", createAsset, "create"),
|
|
1732
|
+
write("spotify_upload_asset", "Upload SHA-256-approved image/video/audio to a new WAITING_UPLOAD asset. Uses native chunking above20MB; Adport cap100MiB, hosted staging50MiB. Existing assets cannot be overwritten.", uploadAsset, "create"),
|
|
1733
|
+
write("spotify_rename_asset", "Rename account-owned asset metadata without replacing media or changing delivery.", z12.object({ asset_id: spotifyId, name: z12.string().trim().min(2).max(120) }))
|
|
1734
|
+
];
|
|
1735
|
+
}
|
|
1736
|
+
|
|
1737
|
+
// src/tools.ts
|
|
337
1738
|
function spotifyTools(provider) {
|
|
338
1739
|
return [
|
|
339
|
-
|
|
1740
|
+
...spotifyCreativeTools(provider),
|
|
1741
|
+
...spotifyManagementTools(provider),
|
|
1742
|
+
...spotifyMeasurementTools(provider),
|
|
1743
|
+
defineTool4({
|
|
340
1744
|
name: "spotify_list_campaigns",
|
|
341
1745
|
namespace: "spotify",
|
|
342
1746
|
description: "List published Spotify Ads campaigns in the selected account.",
|
|
343
|
-
input:
|
|
1747
|
+
input: z13.object({ account_id: spotifyId }),
|
|
344
1748
|
annotations: { readOnly: true },
|
|
345
1749
|
handler: (input) => provider.listCampaigns(input.account_id)
|
|
346
1750
|
}),
|
|
347
|
-
|
|
1751
|
+
defineTool4({
|
|
348
1752
|
name: "spotify_get_ad_set",
|
|
349
1753
|
namespace: "spotify",
|
|
350
1754
|
description: "Read a Spotify ad set, including its budget and delivery setting.",
|
|
351
|
-
input:
|
|
1755
|
+
input: z13.object({ account_id: spotifyId, ad_set_id: spotifyId }),
|
|
352
1756
|
annotations: { readOnly: true },
|
|
353
1757
|
handler: (input) => provider.getAdSet(input.account_id, input.ad_set_id)
|
|
354
1758
|
}),
|
|
355
|
-
|
|
1759
|
+
guardedWriteTool4({
|
|
356
1760
|
name: "spotify_create_campaign_draft",
|
|
357
1761
|
namespace: "spotify",
|
|
358
1762
|
provider: "spotify",
|
|
@@ -360,7 +1764,7 @@ function spotifyTools(provider) {
|
|
|
360
1764
|
description: "Create an unpublished Spotify campaign draft, paused by policy. Does not publish or launch ads. Preview is local.",
|
|
361
1765
|
payload: createDraftSchema
|
|
362
1766
|
}),
|
|
363
|
-
|
|
1767
|
+
guardedWriteTool4({
|
|
364
1768
|
name: "spotify_set_campaign_status",
|
|
365
1769
|
namespace: "spotify",
|
|
366
1770
|
provider: "spotify",
|
|
@@ -368,7 +1772,7 @@ function spotifyTools(provider) {
|
|
|
368
1772
|
description: "Pause or activate an existing Spotify Ads campaign.",
|
|
369
1773
|
payload: setStatusSchema
|
|
370
1774
|
}),
|
|
371
|
-
|
|
1775
|
+
guardedWriteTool4({
|
|
372
1776
|
name: "spotify_set_budget",
|
|
373
1777
|
namespace: "spotify",
|
|
374
1778
|
provider: "spotify",
|
|
@@ -376,7 +1780,7 @@ function spotifyTools(provider) {
|
|
|
376
1780
|
description: "Change a Spotify ad-set budget in integer micros, preserving its current DAILY or LIFETIME type.",
|
|
377
1781
|
payload: setBudgetSchema
|
|
378
1782
|
}),
|
|
379
|
-
|
|
1783
|
+
guardedWriteTool4({
|
|
380
1784
|
name: "spotify_set_ad_set_delivery",
|
|
381
1785
|
namespace: "spotify",
|
|
382
1786
|
provider: "spotify",
|
|
@@ -409,7 +1813,7 @@ async function resolveSpotifyCredentials(store) {
|
|
|
409
1813
|
async function createSpotifyModule(store) {
|
|
410
1814
|
const credentials = await resolveSpotifyCredentials(store);
|
|
411
1815
|
if (!credentials) return void 0;
|
|
412
|
-
const provider = new SpotifyAdsProvider(new SpotifyAdsClient(credentials));
|
|
1816
|
+
const provider = new SpotifyAdsProvider(new SpotifyAdsClient(credentials), void 0, { resourceSecrets: new FileResourceSecretStore() });
|
|
413
1817
|
return { provider, tools: spotifyTools(provider) };
|
|
414
1818
|
}
|
|
415
1819
|
export {
|