@hermoso/ads 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +105 -2
- package/docs/bring-your-own-app.md +391 -0
- package/package.json +66 -4
- package/src/core.js +20 -0
- package/src/credentials.js +53 -0
- package/src/errors.js +29 -0
- package/src/hash.js +30 -0
- package/src/http.js +148 -0
- package/src/index.js +103 -0
- package/src/money.js +25 -0
- package/src/oauth.js +34 -0
- package/src/ops.js +49 -0
- package/src/platform.js +56 -0
- package/src/platforms/amazon-ads.js +218 -0
- package/src/platforms/apple-ads.js +236 -0
- package/src/platforms/applovin-ads.js +182 -0
- package/src/platforms/google-ads.js +435 -0
- package/src/platforms/index.js +21 -0
- package/src/platforms/linkedin-ads.js +297 -0
- package/src/platforms/meta.js +518 -0
- package/src/platforms/microsoft-ads.js +381 -0
- package/src/platforms/openai-ads.js +246 -0
- package/src/platforms/outbrain-ads.js +128 -0
- package/src/platforms/pinterest-ads.js +271 -0
- package/src/platforms/reddit-ads.js +259 -0
- package/src/platforms/snapchat-ads.js +276 -0
- package/src/platforms/taboola-ads.js +57 -0
- package/src/platforms/tiktok-ads.js +348 -0
- package/src/platforms/trade-desk.js +111 -0
- package/src/platforms/x-ads.js +274 -0
- package/src/safety.js +96 -0
- package/src/tools.js +81 -0
- package/src/zip.js +47 -0
package/src/http.js
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { AdsError, kindForStatus } from './errors.js';
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
export function buildUrl(base, path, query) {
|
|
5
|
+
const url = new URL(path && /^https?:/i.test(path) ? path : (base.replace(/\/+$/, '') + '/' + String(path ?? '').replace(/^\/+/, '')));
|
|
6
|
+
for (const [k, v] of Object.entries(query ?? {})) {
|
|
7
|
+
if (v === undefined || v === null) continue;
|
|
8
|
+
url.searchParams.set(k, typeof v === 'object' ? JSON.stringify(v) : String(v));
|
|
9
|
+
}
|
|
10
|
+
return url.toString();
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
async function readBody(res) {
|
|
14
|
+
const text = await res.text();
|
|
15
|
+
if (!text) return null;
|
|
16
|
+
try { return JSON.parse(text); } catch { return text; }
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Pull the most human message out of a vendor error body. Platforms can override. */
|
|
20
|
+
export function genericVendorMessage(body) {
|
|
21
|
+
if (body == null) return null;
|
|
22
|
+
if (typeof body === 'string') return body.slice(0, 500);
|
|
23
|
+
const e = body.error ?? body.errors?.[0] ?? body;
|
|
24
|
+
if (typeof e === 'string') return e;
|
|
25
|
+
return e?.error_user_msg ?? e?.message ?? e?.msg ?? e?.description ?? e?.error_description
|
|
26
|
+
?? body.message ?? body.error_description ?? null;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export class RequestContext {
|
|
30
|
+
constructor({ platform, op, account, store, fetch, publicFetch, hooks }) {
|
|
31
|
+
this.platform = platform;
|
|
32
|
+
this.op = op;
|
|
33
|
+
this.account = account;
|
|
34
|
+
this.store = store;
|
|
35
|
+
this._fetch = fetch;
|
|
36
|
+
this.publicFetch = publicFetch;
|
|
37
|
+
this.hooks = hooks;
|
|
38
|
+
this._creds = undefined;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
get fetch() { return this._fetch ?? globalThis.fetch; }
|
|
42
|
+
|
|
43
|
+
async creds() {
|
|
44
|
+
if (this._creds) return this._creds;
|
|
45
|
+
const p = this.platform;
|
|
46
|
+
const stored = this.store ? await this.store.get(this.account, p.provider) : null;
|
|
47
|
+
const missing = (p.credentials ?? []).filter((f) => {
|
|
48
|
+
if (!f.required) return false;
|
|
49
|
+
if (f.required === 'unlessRefresh' && stored?.refreshToken) return false;
|
|
50
|
+
return stored?.[f.name] == null || stored[f.name] === '';
|
|
51
|
+
});
|
|
52
|
+
if (!stored || missing.length) {
|
|
53
|
+
throw new AdsError('not_connected',
|
|
54
|
+
`${p.label} is not connected. Store credentials for provider "${p.provider}"` +
|
|
55
|
+
(missing.length ? ` (missing: ${missing.map((f) => f.name + (f.env ? ` / ${f.env}` : '')).join(', ')})` : '') + '. See https://github.com/hermoso-ai/hermoso/blob/main/packages/ads/docs/bring-your-own-app.md, or use hosted Hermoso (https://hermoso.ai), which connects with one click where supported.',
|
|
56
|
+
{ platform: p.id, hint: { provider: p.provider, fields: (p.credentials ?? []).map((f) => f.name) } });
|
|
57
|
+
}
|
|
58
|
+
let creds = { ...stored };
|
|
59
|
+
if (p.refresh && ((!creds.accessToken && (creds.refreshToken || p.mintsToken)) || (creds.expiresAt && Date.now() > Number(creds.expiresAt) - 60_000))) {
|
|
60
|
+
creds = await this.refreshCreds(creds);
|
|
61
|
+
}
|
|
62
|
+
this._creds = creds;
|
|
63
|
+
return creds;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async refreshCreds(creds) {
|
|
67
|
+
const p = this.platform;
|
|
68
|
+
if (!p.refresh) return creds;
|
|
69
|
+
const next = await p.refresh(creds, this);
|
|
70
|
+
if (!next) return creds;
|
|
71
|
+
const merged = { ...creds, ...next };
|
|
72
|
+
if (this.store?.set) await this.store.set(this.account, p.provider, merged);
|
|
73
|
+
this._creds = merged;
|
|
74
|
+
return merged;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* request({ method, path|url, query, headers, json, form, body, base, auth, raw })
|
|
79
|
+
* Returns the parsed body (or { status, headers, body } with raw: true).
|
|
80
|
+
*/
|
|
81
|
+
async request(opts, _retried = false) {
|
|
82
|
+
const p = this.platform;
|
|
83
|
+
const creds = opts.auth === false ? null : await this.creds();
|
|
84
|
+
const base = opts.base ?? (typeof p.baseUrl === 'function' ? p.baseUrl(creds ?? {}) : p.baseUrl);
|
|
85
|
+
const url = buildUrl(base, opts.url ?? opts.path, opts.query);
|
|
86
|
+
const headers = { accept: 'application/json', ...(creds && p.authHeaders ? await p.authHeaders(creds, { ...opts, url }, this) : {}), ...(opts.headers ?? {}) };
|
|
87
|
+
let body = opts.body;
|
|
88
|
+
if (opts.json !== undefined) {
|
|
89
|
+
body = JSON.stringify(opts.json);
|
|
90
|
+
if (!Object.keys(headers).some((h) => h.toLowerCase() === 'content-type')) headers['content-type'] = 'application/json';
|
|
91
|
+
} else if (opts.form !== undefined) {
|
|
92
|
+
const f = new URLSearchParams();
|
|
93
|
+
for (const [k, v] of Object.entries(opts.form)) if (v != null) f.set(k, typeof v === 'object' ? JSON.stringify(v) : String(v));
|
|
94
|
+
body = f.toString();
|
|
95
|
+
headers['content-type'] = 'application/x-www-form-urlencoded';
|
|
96
|
+
}
|
|
97
|
+
const method = (opts.method ?? 'GET').toUpperCase();
|
|
98
|
+
|
|
99
|
+
let res;
|
|
100
|
+
try {
|
|
101
|
+
res = await this.fetch(url, { method, headers, body });
|
|
102
|
+
} catch (e) {
|
|
103
|
+
throw new AdsError('vendor', `${p.label} could not be reached: ${e?.message ?? e}`, { platform: p.id, op: this.op });
|
|
104
|
+
}
|
|
105
|
+
const parsed = await readBody(res);
|
|
106
|
+
|
|
107
|
+
if (!res.ok) {
|
|
108
|
+
const err = this.toError(res.status, parsed, res.headers);
|
|
109
|
+
if (err.kind === 'auth' && !_retried && p.refresh && (creds?.refreshToken || p.mintsToken) && opts.auth !== false) {
|
|
110
|
+
await this.refreshCreds(creds);
|
|
111
|
+
return this.request(opts, true);
|
|
112
|
+
}
|
|
113
|
+
throw err;
|
|
114
|
+
}
|
|
115
|
+
if (p.checkBody) {
|
|
116
|
+
const inner = p.checkBody(parsed);
|
|
117
|
+
if (inner) {
|
|
118
|
+
const err = this.toError(inner.status ?? 400, parsed, res.headers, inner);
|
|
119
|
+
if (err.kind === 'auth' && !_retried && p.refresh && (creds?.refreshToken || p.mintsToken) && opts.auth !== false) {
|
|
120
|
+
await this.refreshCreds(creds);
|
|
121
|
+
return this.request(opts, true);
|
|
122
|
+
}
|
|
123
|
+
throw err;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return opts.raw ? { status: res.status, headers: res.headers, body: parsed } : parsed;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
toError(status, body, headers, preset) {
|
|
130
|
+
const p = this.platform;
|
|
131
|
+
const mapped = preset ?? (p.parseError ? p.parseError(status, body, headers) : null) ?? {};
|
|
132
|
+
const kind = mapped.kind ?? kindForStatus(status);
|
|
133
|
+
const secrets = Object.values(this._creds || {}).filter((v) => typeof v === 'string' && v.length >= 8);
|
|
134
|
+
const redact = (t) => secrets.reduce((acc, v) => acc.split(v).join('[redacted]'), String(t));
|
|
135
|
+
const vendor = redact(mapped.message ?? genericVendorMessage(body) ?? `HTTP ${status}`);
|
|
136
|
+
const retryAfter = headers?.get?.('retry-after') ?? undefined;
|
|
137
|
+
const lead = {
|
|
138
|
+
auth: `${p.label} rejected the credentials (expired or revoked); reconnect.`,
|
|
139
|
+
permission: `${p.label} refused: the token lacks a permission or a role on this account.`,
|
|
140
|
+
rate_limit: `${p.label} is rate limiting; wait before retrying.`,
|
|
141
|
+
not_found: `${p.label} could not find that object.`,
|
|
142
|
+
}[kind];
|
|
143
|
+
const message = mapped.userMessage ? redact(mapped.userMessage) : lead ? `${lead} ${vendor}` : `${p.label}: ${vendor}`;
|
|
144
|
+
return new AdsError(kind, message, {
|
|
145
|
+
platform: p.id, op: this.op, status, code: mapped.code, vendor, retryAfter: retryAfter ? Number(retryAfter) || retryAfter : undefined,
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { AdsError, isAdsError } from './errors.js';
|
|
2
|
+
import { RequestContext } from './http.js';
|
|
3
|
+
import { OPS, COMMON_PARAMS } from './ops.js';
|
|
4
|
+
import { requireArgs } from './safety.js';
|
|
5
|
+
import { coreHooks, defaultCredentialStore, publicFetch } from './core.js';
|
|
6
|
+
import { PLATFORMS } from './platforms/index.js';
|
|
7
|
+
|
|
8
|
+
export { AdsError, isAdsError } from './errors.js';
|
|
9
|
+
export { OPS, COMMON_PARAMS, LEVELS } from './ops.js';
|
|
10
|
+
export { memoryCredentialStore, envCredentialStore, layeredCredentialStore } from './credentials.js';
|
|
11
|
+
export { STATUS, normalizeStatus, checkLength } from './safety.js';
|
|
12
|
+
export { toMinor, toMicros, fromMinor, fromMicros } from './money.js';
|
|
13
|
+
export { PLATFORMS };
|
|
14
|
+
export { defaultCredentialStore as coreCredentialStore } from './core.js';
|
|
15
|
+
|
|
16
|
+
const NOOP_HOOKS = {
|
|
17
|
+
abuse: { check: async () => ({ allow: true }) },
|
|
18
|
+
audit: { record: async () => {} },
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* createAds({ account, credentials, fetch, publicFetch, hooks, platforms })
|
|
23
|
+
*
|
|
24
|
+
* const ads = createAds(); // core's credential store, account "default"
|
|
25
|
+
* await ads.meta.listCampaigns({ accountId: 'act_123' });
|
|
26
|
+
* await ads.run('google_ads', 'report', { accountId: '1234567890', level: 'campaign' });
|
|
27
|
+
*
|
|
28
|
+
* - account: which of your users/workspaces the credentials belong to (credential-store key).
|
|
29
|
+
* - credentials: a credentialStore (get/set/delete). Defaults to @hermoso/core's.
|
|
30
|
+
* - fetch: used for vendor API calls (tests inject a mock).
|
|
31
|
+
* - publicFetch: SSRF-guarded fetch for user-supplied URLs (defaults to core's fetchSafe).
|
|
32
|
+
* - hooks: { abuse, audit } overrides; defaults to core's hooks, read at call time so a host's
|
|
33
|
+
* setHooks() applies even after this client was created.
|
|
34
|
+
*/
|
|
35
|
+
export function createAds(opts = {}) {
|
|
36
|
+
const account = opts.account ?? 'default';
|
|
37
|
+
const store = opts.credentials ?? defaultCredentialStore();
|
|
38
|
+
const enabled = (opts.platforms ?? Object.keys(PLATFORMS)).map((id) => {
|
|
39
|
+
const p = PLATFORMS[id];
|
|
40
|
+
if (!p) throw new Error(`Unknown ads platform "${id}". Known: ${Object.keys(PLATFORMS).join(', ')}`);
|
|
41
|
+
return p;
|
|
42
|
+
});
|
|
43
|
+
const byId = new Map(enabled.map((p) => [p.id, p]));
|
|
44
|
+
|
|
45
|
+
const hooks = () => {
|
|
46
|
+
const h = opts.hooks ?? coreHooks() ?? {};
|
|
47
|
+
return { abuse: h.abuse ?? NOOP_HOOKS.abuse, audit: h.audit ?? NOOP_HOOKS.audit };
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
async function run(platformId, op, args = {}) {
|
|
51
|
+
const p = byId.get(platformId);
|
|
52
|
+
if (!p) throw new AdsError('validation', `Unknown platform "${platformId}". Known: ${[...byId.keys()].join(', ')}`, { field: 'platform' });
|
|
53
|
+
const def = p.ops[op];
|
|
54
|
+
if (!OPS[op]) throw new AdsError('validation', `Unknown operation "${op}". Known: ${Object.keys(OPS).join(', ')}`, { field: 'op' });
|
|
55
|
+
if (!def) throw new AdsError('unsupported', `${p.label} does not support ${op}.`, { platform: p.id, op });
|
|
56
|
+
|
|
57
|
+
const required = Object.entries(def.params ?? {}).filter(([, d]) => d.required).map(([n]) => n);
|
|
58
|
+
try {
|
|
59
|
+
requireArgs(args, required, `${p.label} ${op}`);
|
|
60
|
+
const write = OPS[op].write;
|
|
61
|
+
const h = hooks();
|
|
62
|
+
if (write) {
|
|
63
|
+
const verdict = await h.abuse.check({ event: `ads.${op}`, account, meta: { platform: p.id, level: args.level } });
|
|
64
|
+
if (verdict && verdict.allow === false) {
|
|
65
|
+
throw new AdsError('refused', verdict.reason ?? 'This action was refused by the host policy.', { platform: p.id, op });
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
const ctx = new RequestContext({
|
|
69
|
+
platform: p, op, account, store,
|
|
70
|
+
fetch: opts.fetch, publicFetch: opts.publicFetch ?? publicFetch() ?? opts.fetch, hooks: h,
|
|
71
|
+
});
|
|
72
|
+
const result = await def.run(ctx, args);
|
|
73
|
+
if (write) await h.audit.record({ event: `ads.${op}`, account, platform: p.id, level: args.level, id: args.id ?? result?.id });
|
|
74
|
+
return result;
|
|
75
|
+
} catch (e) {
|
|
76
|
+
if (isAdsError(e)) { e.platform ??= p.id; e.op ??= op; throw e; }
|
|
77
|
+
throw new AdsError('vendor', `${p.label} ${op} failed: ${e?.message ?? e}`, { platform: p.id, op });
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function describe(platformId) {
|
|
82
|
+
const list = platformId ? [byId.get(platformId)].filter(Boolean) : enabled;
|
|
83
|
+
return list.map((p) => ({
|
|
84
|
+
id: p.id,
|
|
85
|
+
label: p.label,
|
|
86
|
+
money: p.money,
|
|
87
|
+
credentials: (p.credentials ?? []).map(({ name, required, env, desc }) => ({ name, required: !!required, env, desc })),
|
|
88
|
+
notes: p.notes ?? [],
|
|
89
|
+
ops: Object.fromEntries(Object.entries(p.ops).map(([name, d]) => [name, {
|
|
90
|
+
summary: d.summary ?? OPS[name].summary,
|
|
91
|
+
write: OPS[name].write,
|
|
92
|
+
params: Object.fromEntries(Object.entries(d.params ?? {}).map(([k, v]) => [k, { ...(COMMON_PARAMS[k] ?? {}), ...v }])),
|
|
93
|
+
}])),
|
|
94
|
+
}));
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const client = { account, run, describe, platforms: enabled.map((p) => ({ id: p.id, label: p.label })) };
|
|
98
|
+
for (const p of enabled) {
|
|
99
|
+
client[p.id] = Object.fromEntries(Object.keys(p.ops).map((op) => [op, (args) => run(p.id, op, args)]));
|
|
100
|
+
}
|
|
101
|
+
return client;
|
|
102
|
+
}
|
|
103
|
+
export { getTools, adsGate } from './tools.js';
|
package/src/money.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { AdsError } from './errors.js';
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
/** Validate a plain amount. Zero is allowed only when `allowZero`. */
|
|
5
|
+
export function checkAmount(amount, { field = 'amount', allowZero = false } = {}) {
|
|
6
|
+
const n = typeof amount === 'string' && amount.trim() !== '' ? Number(amount) : amount;
|
|
7
|
+
if (typeof n !== 'number' || !Number.isFinite(n)) {
|
|
8
|
+
throw new AdsError('validation', `${field} must be a number in the account currency (e.g. 25.50)`, { field });
|
|
9
|
+
}
|
|
10
|
+
if (n < 0 || (!allowZero && n === 0)) {
|
|
11
|
+
throw new AdsError('validation', `${field} must be greater than zero`, { field });
|
|
12
|
+
}
|
|
13
|
+
return n;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** 25.5 -> 2550 (minor units: cents, pence...). */
|
|
17
|
+
export const toMinor = (amount, field) => Math.round(checkAmount(amount, { field }) * 100);
|
|
18
|
+
export const fromMinor = (v) => (v == null || v === '' ? null : Number(v) / 100);
|
|
19
|
+
|
|
20
|
+
/** 25.5 -> 25500000 (micros: 1,000,000 = one unit). */
|
|
21
|
+
export const toMicros = (amount, field) => Math.round(checkAmount(amount, { field }) * 1e6);
|
|
22
|
+
export const fromMicros = (v) => (v == null || v === '' ? null : Number(v) / 1e6);
|
|
23
|
+
|
|
24
|
+
/** Plain amount rounded to cents, for platforms that take major units. */
|
|
25
|
+
export const toMajor = (amount, field) => Math.round(checkAmount(amount, { field }) * 100) / 100;
|
package/src/oauth.js
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { AdsError } from './errors.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Standard OAuth 2.0 refresh_token grant. Most ad platforms accept client credentials in the
|
|
5
|
+
* form body; a few require HTTP Basic (`basicAuth: true`). Returns the fields to merge into the
|
|
6
|
+
* stored credentials, including a new refresh token when the vendor rotates it.
|
|
7
|
+
*/
|
|
8
|
+
export async function oauth2Refresh(ctx, creds, { tokenUrl, basicAuth = false, extra = {}, json = false }) {
|
|
9
|
+
if (!creds.refreshToken || !creds.clientId) return null;
|
|
10
|
+
const params = { grant_type: 'refresh_token', refresh_token: creds.refreshToken, ...extra };
|
|
11
|
+
const headers = { accept: 'application/json' };
|
|
12
|
+
if (basicAuth) {
|
|
13
|
+
headers.authorization = 'Basic ' + Buffer.from(`${creds.clientId}:${creds.clientSecret ?? ''}`).toString('base64');
|
|
14
|
+
} else {
|
|
15
|
+
params.client_id = creds.clientId;
|
|
16
|
+
if (creds.clientSecret) params.client_secret = creds.clientSecret;
|
|
17
|
+
}
|
|
18
|
+
let body;
|
|
19
|
+
if (json) { headers['content-type'] = 'application/json'; body = JSON.stringify(params); }
|
|
20
|
+
else { headers['content-type'] = 'application/x-www-form-urlencoded'; body = new URLSearchParams(params).toString(); }
|
|
21
|
+
const res = await ctx.fetch(tokenUrl, { method: 'POST', headers, body });
|
|
22
|
+
const text = await res.text();
|
|
23
|
+
let j; try { j = JSON.parse(text); } catch { j = { raw: text }; }
|
|
24
|
+
const data = j?.data && j.data.access_token ? j.data : j;
|
|
25
|
+
if (!res.ok || !data?.access_token) {
|
|
26
|
+
throw new AdsError('auth', `${ctx.platform.label} token refresh failed; reconnect. ${data?.error_description ?? data?.error ?? data?.message ?? ''}`.trim(),
|
|
27
|
+
{ platform: ctx.platform.id, status: res.status });
|
|
28
|
+
}
|
|
29
|
+
return {
|
|
30
|
+
accessToken: data.access_token,
|
|
31
|
+
...(data.refresh_token ? { refreshToken: data.refresh_token } : {}),
|
|
32
|
+
...(data.expires_in ? { expiresAt: Date.now() + Number(data.expires_in) * 1000 } : {}),
|
|
33
|
+
};
|
|
34
|
+
}
|
package/src/ops.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
|
|
2
|
+
export const OPS = {
|
|
3
|
+
listAccounts: { write: false, summary: 'List the ad accounts (or advertisers, customers, profiles, organisations) these credentials can reach.' },
|
|
4
|
+
listCampaigns: { write: false, summary: 'List campaigns in an ad account.' },
|
|
5
|
+
getCampaign: { write: false, summary: 'Read one campaign back from the platform.' },
|
|
6
|
+
createCampaign: { write: true, summary: 'Create a campaign. Always created paused.' },
|
|
7
|
+
updateCampaign: { write: true, summary: 'Rename or edit a campaign (not status or budget: use setStatus / setBudget).' },
|
|
8
|
+
listAdGroups: { write: false, summary: 'List ad groups (ad sets, line items, ad squads) in an account or campaign.' },
|
|
9
|
+
createAdGroup: { write: true, summary: 'Create an ad group / ad set with targeting and bidding. Always created paused.' },
|
|
10
|
+
updateAdGroup: { write: true, summary: 'Edit an ad group (targeting, bids, name).' },
|
|
11
|
+
listAds: { write: false, summary: 'List ads (or creatives / promoted posts).' },
|
|
12
|
+
createAd: { write: true, summary: 'Create an ad from a creative or existing post. Always created paused.' },
|
|
13
|
+
uploadAsset: { write: true, summary: 'Upload an image or video (from a public URL) to the account\'s asset library.' },
|
|
14
|
+
createCreative: { write: true, summary: 'Create a reusable creative from uploaded assets and copy.' },
|
|
15
|
+
listAudiences: { write: false, summary: 'List custom / saved audiences.' },
|
|
16
|
+
createAudience: { write: true, summary: 'Create a custom or lookalike audience.' },
|
|
17
|
+
setStatus: { write: true, summary: 'Pause, activate or archive a campaign, ad group or ad. Activation needs confirm: true.' },
|
|
18
|
+
setBudget: { write: true, summary: 'Change a campaign or ad group budget (plain amount in account currency). Raising needs confirm: true.' },
|
|
19
|
+
deleteObject: { write: true, summary: 'Delete (or archive, where the platform has no delete) a campaign, ad group or ad. Needs confirm: true.' },
|
|
20
|
+
report: { write: false, summary: 'Performance report: spend, impressions, clicks, conversions by level and date range.' },
|
|
21
|
+
searchTargeting: { write: false, summary: 'Search targeting options: locations, interests, keywords, job titles and more.' },
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
export const LEVELS = ['campaign', 'adGroup', 'ad'];
|
|
25
|
+
|
|
26
|
+
/** Common parameter docs used to describe ops to humans and agents. */
|
|
27
|
+
export const COMMON_PARAMS = {
|
|
28
|
+
accountId: { type: 'string', desc: 'Ad account id on this platform (as listAccounts returns it).' },
|
|
29
|
+
campaignId: { type: 'string', desc: 'Campaign id.' },
|
|
30
|
+
adGroupId: { type: 'string', desc: 'Ad group / ad set / line item id.' },
|
|
31
|
+
id: { type: 'string', desc: 'Object id.' },
|
|
32
|
+
level: { type: 'string', enum: LEVELS, desc: 'Which kind of object: campaign, adGroup or ad.' },
|
|
33
|
+
name: { type: 'string', desc: 'Name.' },
|
|
34
|
+
status: { type: 'string', enum: ['ACTIVE', 'PAUSED', 'ARCHIVED'], desc: 'Target status.' },
|
|
35
|
+
amount: { type: 'number', desc: 'Plain amount in the account currency (25.5 = 25.50). Never cents or micros.' },
|
|
36
|
+
dailyBudget: { type: 'number', desc: 'Daily budget, plain amount in account currency.' },
|
|
37
|
+
lifetimeBudget: { type: 'number', desc: 'Lifetime budget, plain amount in account currency.' },
|
|
38
|
+
confirm: { type: 'boolean', desc: 'Required to activate, raise a budget or delete. Ask the account owner first.' },
|
|
39
|
+
confirmName: { type: 'string', desc: 'Delete of a non-empty object: its exact name, echoed back.' },
|
|
40
|
+
confirmChildren: { type: 'number', desc: 'Delete of a non-empty object: the number of child objects that go with it.' },
|
|
41
|
+
since: { type: 'string', desc: 'Report start date, YYYY-MM-DD.' },
|
|
42
|
+
until: { type: 'string', desc: 'Report end date, YYYY-MM-DD.' },
|
|
43
|
+
query: { type: 'string', desc: 'Search text.' },
|
|
44
|
+
type: { type: 'string', desc: 'Targeting type to search (platform-specific, see describe).' },
|
|
45
|
+
fields: { type: 'object', desc: 'Raw vendor fields merged into the request body, for anything not modelled here.' },
|
|
46
|
+
limit: { type: 'number', desc: 'Max rows.' },
|
|
47
|
+
cursor: { type: 'string', desc: 'Pagination cursor from a previous call\'s `next`.' },
|
|
48
|
+
raw: { type: 'boolean', desc: 'Include the vendor\'s raw objects in the result.' },
|
|
49
|
+
};
|
package/src/platform.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { OPS } from './ops.js';
|
|
2
|
+
import { AdsError } from './errors.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Declare a platform. Shape:
|
|
6
|
+
* {
|
|
7
|
+
* id, label, provider, // provider = credential-store key
|
|
8
|
+
* credentials: [{ name, required, env, desc }],
|
|
9
|
+
* baseUrl: string | (creds) => string,
|
|
10
|
+
* authHeaders(creds, req) => headers,
|
|
11
|
+
* refresh?(creds, ctx) => partial creds,
|
|
12
|
+
* parseError?(status, body) => { kind, code, message, userMessage },
|
|
13
|
+
* checkBody?(body) => null | { kind, code, message }, // 200-with-error envelopes
|
|
14
|
+
* money: 'minor' | 'micros' | 'major',
|
|
15
|
+
* ops: { [opName]: { params?, summary?, run(ctx, args) } },
|
|
16
|
+
* setup: { app, scopes, review, docs }, // used by the bring-your-own-app doc
|
|
17
|
+
* }
|
|
18
|
+
*/
|
|
19
|
+
export function definePlatform(def) {
|
|
20
|
+
for (const name of Object.keys(def.ops)) {
|
|
21
|
+
if (!OPS[name]) throw new Error(`${def.id}: unknown op ${name}`);
|
|
22
|
+
}
|
|
23
|
+
return Object.freeze({ ...def, provider: def.provider ?? def.id });
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Normalised row: a few common fields plus the vendor object when `raw` is asked for. */
|
|
27
|
+
export function row(raw, picked, args) {
|
|
28
|
+
const out = {};
|
|
29
|
+
for (const [k, v] of Object.entries(picked)) if (v !== undefined && v !== null && v !== '') out[k] = v;
|
|
30
|
+
if (args?.raw) out.raw = raw;
|
|
31
|
+
return out;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function unsupported(platform, what) {
|
|
35
|
+
return new AdsError('unsupported', `${platform.label} does not support ${what}.`, { platform: platform.id });
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Map a unified level onto a platform's own object names. */
|
|
39
|
+
export function pickLevel(args, map, platform) {
|
|
40
|
+
const level = args?.level ?? 'campaign';
|
|
41
|
+
const v = map[level];
|
|
42
|
+
if (!v) throw new AdsError('validation', `${platform.label}: level must be one of ${Object.keys(map).join(', ')}`, { field: 'level' });
|
|
43
|
+
return v;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** ISO date helpers for reports: default to the last 7 full days. */
|
|
47
|
+
export function dateRange(args) {
|
|
48
|
+
const today = new Date();
|
|
49
|
+
const d = (x) => x.toISOString().slice(0, 10);
|
|
50
|
+
const until = args?.until ?? d(new Date(today.getTime() - 86400000));
|
|
51
|
+
const since = args?.since ?? d(new Date(new Date(until).getTime() - 6 * 86400000));
|
|
52
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(since) || !/^\d{4}-\d{2}-\d{2}$/.test(until)) {
|
|
53
|
+
throw new AdsError('validation', 'since/until must be YYYY-MM-DD', { field: 'since' });
|
|
54
|
+
}
|
|
55
|
+
return { since, until };
|
|
56
|
+
}
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
import { definePlatform, row, pickLevel, dateRange } from '../platform.js';
|
|
2
|
+
import { AdsError } from '../errors.js';
|
|
3
|
+
import { assertBornPaused, gateStatus, gateBudget, gateDelete, checkLength, STATUS } from '../safety.js';
|
|
4
|
+
import { toMajor } from '../money.js';
|
|
5
|
+
import { oauth2Refresh } from '../oauth.js';
|
|
6
|
+
import { decompress } from '../zip.js';
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
const HOSTS = { NA: 'https://advertising-api.amazon.com', EU: 'https://advertising-api-eu.amazon.com', FE: 'https://advertising-api-fe.amazon.com' };
|
|
10
|
+
const TOKEN_URL = 'https://api.amazon.com/auth/o2/token';
|
|
11
|
+
const SP = {
|
|
12
|
+
campaign: { path: '/sp/campaigns', media: 'application/vnd.spCampaign.v3+json', key: 'campaigns', id: 'campaignId', filter: 'campaignIdFilter' },
|
|
13
|
+
adGroup: { path: '/sp/adGroups', media: 'application/vnd.spAdGroup.v3+json', key: 'adGroups', id: 'adGroupId', filter: 'adGroupIdFilter' },
|
|
14
|
+
ad: { path: '/sp/productAds', media: 'application/vnd.spProductAd.v3+json', key: 'productAds', id: 'adId', filter: 'adIdFilter' },
|
|
15
|
+
keyword: { path: '/sp/keywords', media: 'application/vnd.spKeyword.v3+json', key: 'keywords', id: 'keywordId', filter: 'keywordIdFilter' },
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
const headers = (media, profileId) => ({ 'content-type': media, accept: media, 'Amazon-Advertising-API-Scope': String(profileId), prefer: 'return=representation' });
|
|
19
|
+
|
|
20
|
+
/** Creates and updates answer 207 with per-row success/error lists; any error fails the call. */
|
|
21
|
+
function multi(r, key, idKey) {
|
|
22
|
+
const part = r?.[key] ?? {};
|
|
23
|
+
if (part.error?.length) {
|
|
24
|
+
const e = part.error[0].errors?.[0];
|
|
25
|
+
const v = e?.errorValue ? Object.values(e.errorValue)[0] : null;
|
|
26
|
+
throw new AdsError('validation', `Amazon Ads refused: ${v?.message ?? e?.errorType ?? JSON.stringify(part.error[0])}`, { code: v?.reason ?? e?.errorType });
|
|
27
|
+
}
|
|
28
|
+
return (part.success ?? []).map((s) => ({ id: String(s[idKey] ?? s[key.replace(/s$/, '')]?.[idKey] ?? ''), entity: s[key.replace(/s$/, '')] }));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async function list(ctx, profileId, kind, body = {}) {
|
|
32
|
+
const e = SP[kind];
|
|
33
|
+
const r = await ctx.request({ method: 'POST', path: `${e.path}/list`, headers: headers(e.media, profileId), json: { maxResults: 1000, ...body } });
|
|
34
|
+
return r?.[e.key] ?? [];
|
|
35
|
+
}
|
|
36
|
+
const write = (ctx, profileId, kind, method, rows) => {
|
|
37
|
+
const e = SP[kind];
|
|
38
|
+
return ctx.request({ method, path: e.path, headers: headers(e.media, profileId), json: { [e.key]: rows } }).then((r) => multi(r, e.key, e.id));
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
function parseError(status, body) {
|
|
42
|
+
const message = body?.details ?? body?.detail ?? body?.message ?? body?.errors?.[0]?.message ?? body?.code;
|
|
43
|
+
if (status === 403) return { kind: 'permission', message, userMessage: `Amazon Ads refused this for the profile (check the profile id and the user's access). ${message ?? ''}`.trim() };
|
|
44
|
+
return message ? { message: String(message) } : null;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export default definePlatform({
|
|
48
|
+
id: 'amazon_ads',
|
|
49
|
+
label: 'Amazon Ads',
|
|
50
|
+
money: 'major',
|
|
51
|
+
credentials: [
|
|
52
|
+
{ name: 'clientId', required: true, env: 'AMAZON_ADS_CLIENT_ID', desc: 'Login with Amazon security profile client id (approved for the Ads API).' },
|
|
53
|
+
{ name: 'clientSecret', required: true, env: 'AMAZON_ADS_CLIENT_SECRET' },
|
|
54
|
+
{ name: 'refreshToken', required: true, env: 'AMAZON_ADS_REFRESH_TOKEN', desc: 'From a consent with scope advertising::campaign_management.' },
|
|
55
|
+
{ name: 'region', env: 'AMAZON_ADS_REGION', desc: 'NA (default), EU or FE.' },
|
|
56
|
+
],
|
|
57
|
+
baseUrl: (c) => HOSTS[String(c.region ?? 'NA').toUpperCase()] ?? HOSTS.NA,
|
|
58
|
+
authHeaders: (c) => ({ authorization: `Bearer ${c.accessToken}`, 'Amazon-Advertising-API-ClientId': c.clientId }),
|
|
59
|
+
refresh: (c, ctx) => oauth2Refresh(ctx, c, { tokenUrl: TOKEN_URL }),
|
|
60
|
+
parseError,
|
|
61
|
+
notes: [
|
|
62
|
+
'accountId is the advertising PROFILE id (one per advertiser per marketplace), from listAccounts.',
|
|
63
|
+
'Profiles appear only after the account has created at least one campaign in the Amazon Ads console.',
|
|
64
|
+
'A seller advertises by SKU, a vendor by ASIN.',
|
|
65
|
+
'Archiving is permanent on Amazon: an archived object cannot be re-enabled.',
|
|
66
|
+
'Negative keywords are created enabled on purpose: they only exclude traffic.',
|
|
67
|
+
],
|
|
68
|
+
setup: {
|
|
69
|
+
app: 'A Login with Amazon security profile (developer.amazon.com), then an Amazon Ads API access request linking that client id (advertising.amazon.com > API).',
|
|
70
|
+
scopes: ['advertising::campaign_management'],
|
|
71
|
+
review: 'Amazon reviews the Ads API application (usually about a business day) and grants API access to one client id per company.',
|
|
72
|
+
hosted: { connect: 'app', note: 'Hosted Hermoso connects with one click where supported, with no developer app of your own.' },
|
|
73
|
+
docs: 'https://advertising.amazon.com/API/docs/en-us/',
|
|
74
|
+
},
|
|
75
|
+
ops: {
|
|
76
|
+
listAccounts: {
|
|
77
|
+
run: async (ctx, a) => {
|
|
78
|
+
const r = await ctx.request({ path: '/v2/profiles' });
|
|
79
|
+
return { items: (r ?? []).map((p) => row(p, { id: String(p.profileId), name: p.accountInfo?.name, country: p.countryCode, currency: p.currencyCode, type: p.accountInfo?.type, timezone: p.timezone }, a)) };
|
|
80
|
+
},
|
|
81
|
+
},
|
|
82
|
+
listCampaigns: {
|
|
83
|
+
params: { accountId: { required: true, desc: 'Profile id.' } },
|
|
84
|
+
run: async (ctx, a) => ({ items: (await list(ctx, a.accountId, 'campaign', { stateFilter: { include: ['ENABLED', 'PAUSED'] } })).map((c) => row(c, { id: String(c.campaignId), name: c.name, status: c.state, targetingType: c.targetingType, dailyBudget: c.budget?.budget, startDate: c.startDate }, a)) }),
|
|
85
|
+
},
|
|
86
|
+
getCampaign: {
|
|
87
|
+
params: { accountId: { required: true }, id: { required: true } },
|
|
88
|
+
run: async (ctx, a) => {
|
|
89
|
+
const [c] = await list(ctx, a.accountId, 'campaign', { campaignIdFilter: { include: [String(a.id)] } });
|
|
90
|
+
if (!c) throw new AdsError('not_found', `Campaign ${a.id} not found.`);
|
|
91
|
+
return row(c, { id: String(c.campaignId), name: c.name, status: c.state, targetingType: c.targetingType, dailyBudget: c.budget?.budget, bidding: c.dynamicBidding }, a);
|
|
92
|
+
},
|
|
93
|
+
},
|
|
94
|
+
createCampaign: {
|
|
95
|
+
params: { accountId: { required: true }, name: { required: true }, dailyBudget: { required: true }, targetingType: { type: 'string', enum: ['AUTO', 'MANUAL'], desc: 'Default MANUAL.' }, startDate: { type: 'string' }, biddingStrategy: { type: 'string', desc: 'LEGACY_FOR_SALES (default), AUTO_FOR_SALES, MANUAL.' } },
|
|
96
|
+
run: async (ctx, a) => {
|
|
97
|
+
assertBornPaused(a, 'campaign');
|
|
98
|
+
checkLength('name', a.name, 128);
|
|
99
|
+
const [d] = await write(ctx, a.accountId, 'campaign', 'POST', [{ name: a.name, targetingType: a.targetingType ?? 'MANUAL', state: 'PAUSED', budget: { budgetType: 'DAILY', budget: toMajor(a.dailyBudget, 'dailyBudget') },
|
|
100
|
+
...(a.startDate ? { startDate: a.startDate } : {}), dynamicBidding: { strategy: a.biddingStrategy ?? 'LEGACY_FOR_SALES' }, ...(a.fields ?? {}) }]);
|
|
101
|
+
return { id: d.id, status: STATUS.PAUSED };
|
|
102
|
+
},
|
|
103
|
+
},
|
|
104
|
+
listAdGroups: {
|
|
105
|
+
params: { accountId: { required: true }, campaignId: {} },
|
|
106
|
+
run: async (ctx, a) => ({ items: (await list(ctx, a.accountId, 'adGroup', { stateFilter: { include: ['ENABLED', 'PAUSED'] }, ...(a.campaignId ? { campaignIdFilter: { include: [String(a.campaignId)] } } : {}) })).map((g) => row(g, { id: String(g.adGroupId), name: g.name, status: g.state, campaignId: String(g.campaignId), defaultBid: g.defaultBid }, a)) }),
|
|
107
|
+
},
|
|
108
|
+
createAdGroup: {
|
|
109
|
+
params: { accountId: { required: true }, campaignId: { required: true }, name: { required: true }, defaultBid: { type: 'number', required: true }, keywords: { type: 'array', desc: 'Optional [{text, matchType: BROAD|PHRASE|EXACT, bid}] (strings are BROAD).' } },
|
|
110
|
+
run: async (ctx, a) => {
|
|
111
|
+
assertBornPaused(a, 'ad group');
|
|
112
|
+
checkLength('name', a.name, 255);
|
|
113
|
+
const [g] = await write(ctx, a.accountId, 'adGroup', 'POST', [{ campaignId: String(a.campaignId), name: a.name, defaultBid: toMajor(a.defaultBid, 'defaultBid'), state: 'PAUSED', ...(a.fields ?? {}) }]);
|
|
114
|
+
const kws = (a.keywords ?? []).map((k) => (typeof k === 'string' ? { text: k } : k));
|
|
115
|
+
let keywordIds = [];
|
|
116
|
+
if (kws.length) keywordIds = (await write(ctx, a.accountId, 'keyword', 'POST', kws.map((k) => ({ campaignId: String(a.campaignId), adGroupId: g.id, keywordText: k.text, matchType: k.matchType ?? 'BROAD', state: 'PAUSED', ...(k.bid != null ? { bid: toMajor(k.bid, 'bid') } : {}) })))).map((x) => x.id);
|
|
117
|
+
return { id: g.id, status: STATUS.PAUSED, keywordIds };
|
|
118
|
+
},
|
|
119
|
+
},
|
|
120
|
+
listAds: {
|
|
121
|
+
params: { accountId: { required: true }, adGroupId: {} },
|
|
122
|
+
run: async (ctx, a) => ({ items: (await list(ctx, a.accountId, 'ad', { stateFilter: { include: ['ENABLED', 'PAUSED'] }, ...(a.adGroupId ? { adGroupIdFilter: { include: [String(a.adGroupId)] } } : {}) })).map((x) => row(x, { id: String(x.adId), status: x.state, adGroupId: String(x.adGroupId), sku: x.sku, asin: x.asin }, a)) }),
|
|
123
|
+
},
|
|
124
|
+
createAd: {
|
|
125
|
+
params: { accountId: { required: true }, campaignId: { required: true }, adGroupId: { required: true }, sku: { type: 'string', desc: 'Sellers advertise by SKU.' }, asin: { type: 'string', desc: 'Vendors advertise by ASIN.' } },
|
|
126
|
+
run: async (ctx, a) => {
|
|
127
|
+
assertBornPaused(a, 'product ad');
|
|
128
|
+
if (!!a.sku === !!a.asin) throw new AdsError('validation', 'Give sku (sellers) or asin (vendors), not both.', { field: 'sku' });
|
|
129
|
+
if (a.asin && !/^[A-Z0-9]{10}$/.test(a.asin)) throw new AdsError('validation', 'asin must be 10 letters/digits.', { field: 'asin' });
|
|
130
|
+
const [d] = await write(ctx, a.accountId, 'ad', 'POST', [{ campaignId: String(a.campaignId), adGroupId: String(a.adGroupId), state: 'PAUSED', ...(a.sku ? { sku: a.sku } : { asin: a.asin }) }]);
|
|
131
|
+
return { id: d.id, status: STATUS.PAUSED };
|
|
132
|
+
},
|
|
133
|
+
},
|
|
134
|
+
setStatus: {
|
|
135
|
+
params: { accountId: { required: true }, id: { required: true }, level: {}, status: { required: true } },
|
|
136
|
+
run: async (ctx, a) => {
|
|
137
|
+
const status = gateStatus(a);
|
|
138
|
+
if (status === STATUS.ARCHIVED) return ctx.platform.ops.deleteObject.run(ctx, a);
|
|
139
|
+
const kind = pickLevel(a, { campaign: 'campaign', adGroup: 'adGroup', ad: 'ad' }, ctx.platform);
|
|
140
|
+
await write(ctx, a.accountId, kind, 'PUT', [{ [SP[kind].id]: String(a.id), state: status === STATUS.ACTIVE ? 'ENABLED' : 'PAUSED' }]);
|
|
141
|
+
return { id: String(a.id), status };
|
|
142
|
+
},
|
|
143
|
+
},
|
|
144
|
+
setBudget: {
|
|
145
|
+
params: { accountId: { required: true }, id: { required: true, desc: 'Campaign id.' }, amount: { required: true } },
|
|
146
|
+
run: async (ctx, a) => {
|
|
147
|
+
const [c] = await list(ctx, a.accountId, 'campaign', { campaignIdFilter: { include: [String(a.id)] } });
|
|
148
|
+
if (!c) throw new AdsError('not_found', `Campaign ${a.id} not found.`);
|
|
149
|
+
gateBudget(a, c.budget?.budget);
|
|
150
|
+
await write(ctx, a.accountId, 'campaign', 'PUT', [{ campaignId: String(a.id), budget: { budgetType: 'DAILY', budget: toMajor(a.amount) } }]);
|
|
151
|
+
return { id: String(a.id), dailyBudget: toMajor(a.amount), previous: c.budget?.budget };
|
|
152
|
+
},
|
|
153
|
+
},
|
|
154
|
+
deleteObject: {
|
|
155
|
+
params: { accountId: { required: true }, id: { required: true }, level: { required: true }, confirm: {}, confirmName: {}, confirmChildren: {} },
|
|
156
|
+
run: async (ctx, a) => {
|
|
157
|
+
const kind = pickLevel(a, { campaign: 'campaign', adGroup: 'adGroup', ad: 'ad' }, ctx.platform);
|
|
158
|
+
const e = SP[kind];
|
|
159
|
+
const [cur] = await list(ctx, a.accountId, kind, { [e.filter]: { include: [String(a.id)] } });
|
|
160
|
+
if (!cur) throw new AdsError('not_found', `${kind} ${a.id} not found.`);
|
|
161
|
+
const children = [];
|
|
162
|
+
if (kind === 'campaign') children.push({ label: 'ad groups', count: (await list(ctx, a.accountId, 'adGroup', { campaignIdFilter: { include: [String(a.id)] }, stateFilter: { include: ['ENABLED', 'PAUSED'] } })).length });
|
|
163
|
+
if (kind === 'adGroup') children.push({ label: 'product ads', count: (await list(ctx, a.accountId, 'ad', { adGroupIdFilter: { include: [String(a.id)] }, stateFilter: { include: ['ENABLED', 'PAUSED'] } })).length });
|
|
164
|
+
gateDelete(a, { what: kind, name: cur.name, children, live: cur.state === 'ENABLED', note: 'Archiving is permanent on Amazon.' });
|
|
165
|
+
const r = await ctx.request({ method: 'POST', path: `${e.path}/delete`, headers: headers(e.media, a.accountId), json: { [e.filter]: { include: [String(a.id)] } } });
|
|
166
|
+
multi(r, e.key, e.id);
|
|
167
|
+
return { id: String(a.id), status: STATUS.ARCHIVED };
|
|
168
|
+
},
|
|
169
|
+
},
|
|
170
|
+
report: {
|
|
171
|
+
params: {
|
|
172
|
+
accountId: { required: true }, since: {}, until: {}, reportId: { type: 'string', desc: 'Resume a pending report.' },
|
|
173
|
+
reportType: { type: 'string', desc: 'spCampaigns (default), spTargeting, spSearchTerm, spAdvertisedProduct.' }, timeUnit: { type: 'string', enum: ['SUMMARY', 'DAILY'] },
|
|
174
|
+
columns: { type: 'array' }, maxPolls: { type: 'number' }, pollMs: { type: 'number' },
|
|
175
|
+
},
|
|
176
|
+
run: async (ctx, a) => {
|
|
177
|
+
let id = a.reportId;
|
|
178
|
+
if (!id) {
|
|
179
|
+
const { since, until } = dateRange(a);
|
|
180
|
+
if ((Date.parse(until) - Date.parse(since)) / 86400000 > 31) throw new AdsError('validation', 'Amazon reports cover at most 31 days.', { field: 'since' });
|
|
181
|
+
const type = a.reportType ?? 'spCampaigns';
|
|
182
|
+
const groupBy = { spCampaigns: ['campaign'], spTargeting: ['targeting'], spSearchTerm: ['searchTerm'], spAdvertisedProduct: ['advertiser'] }[type] ?? ['campaign'];
|
|
183
|
+
const columns = a.columns ?? ['campaignName', 'campaignId', 'impressions', 'clicks', 'cost', 'purchases7d', 'sales7d'];
|
|
184
|
+
try {
|
|
185
|
+
const r = await ctx.request({ method: 'POST', path: '/reporting/reports', headers: { 'content-type': 'application/vnd.createasyncreportrequest.v3+json', 'Amazon-Advertising-API-Scope': String(a.accountId) },
|
|
186
|
+
json: { name: `report ${since}..${until}`, startDate: since, endDate: until, configuration: { adProduct: 'SPONSORED_PRODUCTS', reportTypeId: type, groupBy, columns, timeUnit: a.timeUnit ?? 'SUMMARY', format: 'GZIP_JSON' } } });
|
|
187
|
+
id = r.reportId;
|
|
188
|
+
} catch (e) {
|
|
189
|
+
const m = /([0-9a-f]{8}-[0-9a-f-]{27})/i.exec(e.vendor ?? '');
|
|
190
|
+
if (e.status === 425 && m) id = m[1]; else throw e;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
const maxPolls = a.maxPolls ?? 10; const pollMs = a.pollMs ?? 5000;
|
|
194
|
+
for (let i = 0; i < maxPolls; i++) {
|
|
195
|
+
const s = await ctx.request({ path: `/reporting/reports/${id}`, headers: { 'Amazon-Advertising-API-Scope': String(a.accountId) } });
|
|
196
|
+
if (s.status === 'FAILED') throw new AdsError('vendor', `Amazon could not build the report: ${s.failureReason ?? 'unknown reason'}`);
|
|
197
|
+
if (s.status === 'COMPLETED') {
|
|
198
|
+
const host = new URL(s.url).hostname;
|
|
199
|
+
if (!/\.amazonaws\.com$/.test(host)) throw new AdsError('vendor', 'Unexpected report download host.');
|
|
200
|
+
const res = await ctx.fetch(s.url);
|
|
201
|
+
return { rows: JSON.parse(decompress(Buffer.from(await res.arrayBuffer())).toString('utf8')) };
|
|
202
|
+
}
|
|
203
|
+
if (i < maxPolls - 1) await new Promise((r) => setTimeout(r, pollMs));
|
|
204
|
+
}
|
|
205
|
+
return { pending: true, reportId: id, note: 'Still building; call report again with reportId.' };
|
|
206
|
+
},
|
|
207
|
+
},
|
|
208
|
+
searchTargeting: {
|
|
209
|
+
params: { accountId: { required: true }, type: { required: true, enum: ['keywords'] }, query: { required: true, desc: 'Comma-separated ASINs to get keyword ideas for.' } },
|
|
210
|
+
run: async (ctx, a) => {
|
|
211
|
+
const media = 'application/vnd.spkeywordsrecommendation.v5+json';
|
|
212
|
+
const r = await ctx.request({ method: 'POST', path: '/sp/targets/keywords/recommendations', headers: headers(media, a.accountId), json: { recommendationType: 'KEYWORDS_FOR_ASINS', asins: String(a.query).split(',').map((s) => s.trim()), bidsEnabled: true } });
|
|
213
|
+
const list = Array.isArray(r) ? r : (r.keywordTargetList ?? []);
|
|
214
|
+
return { items: list.map((k) => ({ keyword: k.keyword, rank: k.rank, bids: (k.bidInfo ?? []).map((b) => ({ matchType: b.matchType, suggested: b.suggestedBid?.suggested != null ? b.suggestedBid.suggested / 100 : null })) })), note: 'Suggested bids are converted from minor units; zero-decimal currencies (JPY) may need no conversion.' };
|
|
215
|
+
},
|
|
216
|
+
},
|
|
217
|
+
},
|
|
218
|
+
});
|