@adport/provider-tiktok 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 +201 -0
- package/dist/index.d.ts +80 -0
- package/dist/index.js +464 -0
- package/dist/index.js.map +1 -0
- package/package.json +34 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Yannick Westermann
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { AdProvider, ProviderCapabilities, StandardActions, Account, NormalizedQuery, Report, WriteOperation, WriteGuard, WritePreview, WriteResult, AnyToolDefinition, CredentialStore, ProviderModule } from '@adport/core';
|
|
2
|
+
|
|
3
|
+
interface TikTokCredentials {
|
|
4
|
+
/** Long-term access token (does not expire; revoked by the advertiser). */
|
|
5
|
+
accessToken: string;
|
|
6
|
+
appId?: string;
|
|
7
|
+
secret?: string;
|
|
8
|
+
/** Use the sandbox environment (sandbox-ads.tiktok.com). */
|
|
9
|
+
sandbox?: boolean;
|
|
10
|
+
}
|
|
11
|
+
declare const TIKTOK_API_VERSION = "v1.3";
|
|
12
|
+
/**
|
|
13
|
+
* TikTok Business API client. Peculiarities handled here:
|
|
14
|
+
* - every endpoint needs a TRAILING SLASH (404 otherwise)
|
|
15
|
+
* - business errors arrive as HTTP 200 with a non-zero envelope `code`
|
|
16
|
+
* - array query params are JSON-encoded strings
|
|
17
|
+
*/
|
|
18
|
+
declare class TikTokClient {
|
|
19
|
+
private readonly credentials;
|
|
20
|
+
private readonly fetchImpl;
|
|
21
|
+
readonly baseUrl: string;
|
|
22
|
+
constructor(credentials: TikTokCredentials, fetchImpl?: typeof fetch);
|
|
23
|
+
get<T>(path: string, params?: Record<string, string | number | unknown[] | object | undefined>): Promise<T>;
|
|
24
|
+
post<T>(path: string, body: Record<string, unknown>): Promise<T>;
|
|
25
|
+
private send;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** TikTok budgets are floats in whole account-currency units. */
|
|
29
|
+
declare const UNITS_TO_MICROS = 1000000;
|
|
30
|
+
interface TikTokCampaign {
|
|
31
|
+
campaign_id: string;
|
|
32
|
+
campaign_name: string;
|
|
33
|
+
operation_status: 'ENABLE' | 'DISABLE';
|
|
34
|
+
secondary_status?: string;
|
|
35
|
+
budget: number;
|
|
36
|
+
budget_mode: string;
|
|
37
|
+
objective_type: string;
|
|
38
|
+
}
|
|
39
|
+
declare class TikTokAdsProvider implements AdProvider {
|
|
40
|
+
private readonly client;
|
|
41
|
+
private readonly app;
|
|
42
|
+
readonly id = "tiktok";
|
|
43
|
+
constructor(client: TikTokClient, app: {
|
|
44
|
+
appId: string;
|
|
45
|
+
secret: string;
|
|
46
|
+
});
|
|
47
|
+
capabilities(): ProviderCapabilities;
|
|
48
|
+
standardActions(): StandardActions;
|
|
49
|
+
listAccounts(): Promise<Account[]>;
|
|
50
|
+
report(query: NormalizedQuery): Promise<Report>;
|
|
51
|
+
private toReportRow;
|
|
52
|
+
rawReport(input: {
|
|
53
|
+
account_id: string;
|
|
54
|
+
data_level: string;
|
|
55
|
+
dimensions: string[];
|
|
56
|
+
metrics: string[];
|
|
57
|
+
start_date: string;
|
|
58
|
+
end_date: string;
|
|
59
|
+
page_size?: number;
|
|
60
|
+
}): Promise<Array<Record<string, unknown>>>;
|
|
61
|
+
listCampaigns(accountId: string, campaignIds?: string[]): Promise<TikTokCampaign[]>;
|
|
62
|
+
previewWrite(op: WriteOperation, guard: WriteGuard): Promise<WritePreview>;
|
|
63
|
+
applyWrite(op: WriteOperation, guard: WriteGuard): Promise<WriteResult>;
|
|
64
|
+
private plan;
|
|
65
|
+
private planCreateCampaign;
|
|
66
|
+
private planSetStatus;
|
|
67
|
+
private planSetBudget;
|
|
68
|
+
private appId;
|
|
69
|
+
private secret;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
declare function tiktokTools(provider: TikTokAdsProvider): AnyToolDefinition[];
|
|
73
|
+
|
|
74
|
+
declare function resolveTikTokCredentials(store: CredentialStore): Promise<(TikTokCredentials & {
|
|
75
|
+
appId: string;
|
|
76
|
+
secret: string;
|
|
77
|
+
}) | undefined>;
|
|
78
|
+
declare function createTikTokModule(store: CredentialStore): Promise<ProviderModule | undefined>;
|
|
79
|
+
|
|
80
|
+
export { TIKTOK_API_VERSION, TikTokAdsProvider, TikTokClient, type TikTokCredentials, UNITS_TO_MICROS, createTikTokModule, resolveTikTokCredentials, tiktokTools };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,464 @@
|
|
|
1
|
+
// src/client.ts
|
|
2
|
+
import { AdportError } from "@adport/core";
|
|
3
|
+
var TIKTOK_API_VERSION = "v1.3";
|
|
4
|
+
var PROD_BASE = "https://business-api.tiktok.com/open_api";
|
|
5
|
+
var SANDBOX_BASE = "https://sandbox-ads.tiktok.com/open_api";
|
|
6
|
+
var CODE_HINTS = {
|
|
7
|
+
40105: "The access token is invalid \u2014 re-run `adport connect tiktok`.",
|
|
8
|
+
40102: "The access token expired or was revoked \u2014 re-run `adport connect tiktok`.",
|
|
9
|
+
40100: "Rate limited (app level) \u2014 back off and retry.",
|
|
10
|
+
40133: "Rate limited (advertiser level) \u2014 back off and retry."
|
|
11
|
+
};
|
|
12
|
+
var TikTokClient = class {
|
|
13
|
+
constructor(credentials, fetchImpl = fetch) {
|
|
14
|
+
this.credentials = credentials;
|
|
15
|
+
this.fetchImpl = fetchImpl;
|
|
16
|
+
this.baseUrl = `${credentials.sandbox ? SANDBOX_BASE : PROD_BASE}/${TIKTOK_API_VERSION}`;
|
|
17
|
+
}
|
|
18
|
+
credentials;
|
|
19
|
+
fetchImpl;
|
|
20
|
+
baseUrl;
|
|
21
|
+
async get(path, params = {}) {
|
|
22
|
+
const search = new URLSearchParams();
|
|
23
|
+
for (const [key, value] of Object.entries(params)) {
|
|
24
|
+
if (value === void 0) continue;
|
|
25
|
+
search.set(key, typeof value === "object" ? JSON.stringify(value) : String(value));
|
|
26
|
+
}
|
|
27
|
+
const query = search.size > 0 ? `?${search}` : "";
|
|
28
|
+
return this.send(`${path}${query}`, { method: "GET" });
|
|
29
|
+
}
|
|
30
|
+
async post(path, body) {
|
|
31
|
+
return this.send(path, { method: "POST", body: JSON.stringify(body) });
|
|
32
|
+
}
|
|
33
|
+
async send(pathWithQuery, init) {
|
|
34
|
+
const [path, query] = pathWithQuery.split("?");
|
|
35
|
+
const url = `${this.baseUrl}/${path.replace(/^\/|\/$/g, "")}/${query ? `?${query}` : ""}`;
|
|
36
|
+
const response = await this.fetchImpl(url, {
|
|
37
|
+
method: init.method,
|
|
38
|
+
headers: {
|
|
39
|
+
"Access-Token": this.credentials.accessToken,
|
|
40
|
+
...init.body ? { "content-type": "application/json" } : {}
|
|
41
|
+
},
|
|
42
|
+
body: init.body
|
|
43
|
+
});
|
|
44
|
+
const raw = await response.text();
|
|
45
|
+
if (!response.ok) {
|
|
46
|
+
throw new AdportError("PROVIDER_ERROR", `TikTok API HTTP ${response.status} for ${path} (check method and trailing slash)`, raw);
|
|
47
|
+
}
|
|
48
|
+
const envelope = JSON.parse(raw);
|
|
49
|
+
if (envelope.code !== 0) {
|
|
50
|
+
const hint = CODE_HINTS[envelope.code];
|
|
51
|
+
throw new AdportError(
|
|
52
|
+
"PROVIDER_ERROR",
|
|
53
|
+
`TikTok API error ${envelope.code}: ${envelope.message}${hint ? `
|
|
54
|
+
${hint}` : ""}` + (envelope.request_id ? ` [request_id: ${envelope.request_id}]` : ""),
|
|
55
|
+
envelope
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
return envelope.data ?? {};
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
// src/provider.ts
|
|
63
|
+
import {
|
|
64
|
+
AdportError as AdportError2,
|
|
65
|
+
resolveDateRange
|
|
66
|
+
} from "@adport/core";
|
|
67
|
+
var UNITS_TO_MICROS = 1e6;
|
|
68
|
+
var DATA_LEVEL = {
|
|
69
|
+
account: "AUCTION_ADVERTISER",
|
|
70
|
+
campaign: "AUCTION_CAMPAIGN",
|
|
71
|
+
ad_group: "AUCTION_ADGROUP",
|
|
72
|
+
ad: "AUCTION_AD"
|
|
73
|
+
};
|
|
74
|
+
var ID_DIMENSION = {
|
|
75
|
+
account: "advertiser_id",
|
|
76
|
+
campaign: "campaign_id",
|
|
77
|
+
ad_group: "adgroup_id",
|
|
78
|
+
ad: "ad_id"
|
|
79
|
+
};
|
|
80
|
+
var TikTokAdsProvider = class {
|
|
81
|
+
constructor(client, app) {
|
|
82
|
+
this.client = client;
|
|
83
|
+
this.app = app;
|
|
84
|
+
}
|
|
85
|
+
client;
|
|
86
|
+
app;
|
|
87
|
+
id = "tiktok";
|
|
88
|
+
capabilities() {
|
|
89
|
+
return { serverDryRun: false };
|
|
90
|
+
}
|
|
91
|
+
standardActions() {
|
|
92
|
+
return {
|
|
93
|
+
pauseCampaign: (accountId, campaignId) => ({
|
|
94
|
+
tool: "tiktok_set_campaign_status",
|
|
95
|
+
input: { account_id: accountId, campaign_ids: [campaignId], operation_status: "DISABLE" }
|
|
96
|
+
})
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
async listAccounts() {
|
|
100
|
+
const authorized = await this.client.get(
|
|
101
|
+
"oauth2/advertiser/get",
|
|
102
|
+
{ app_id: this.appId(), secret: this.secret() }
|
|
103
|
+
);
|
|
104
|
+
const ids = (authorized.list ?? []).map((a) => a.advertiser_id);
|
|
105
|
+
if (ids.length === 0) return [];
|
|
106
|
+
const info = await this.client.get("advertiser/info", { advertiser_ids: ids.slice(0, 100), fields: ["name", "currency", "status", "timezone"] });
|
|
107
|
+
const byId = new Map((info.list ?? []).map((i) => [i.advertiser_id, i]));
|
|
108
|
+
return ids.map((id) => {
|
|
109
|
+
const details = byId.get(id);
|
|
110
|
+
return {
|
|
111
|
+
provider: this.id,
|
|
112
|
+
id,
|
|
113
|
+
name: details?.name ?? (authorized.list ?? []).find((a) => a.advertiser_id === id)?.advertiser_name ?? id,
|
|
114
|
+
currency: details?.currency,
|
|
115
|
+
status: details?.status?.replace("STATUS_", "")
|
|
116
|
+
};
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
async report(query) {
|
|
120
|
+
const range = resolveDateRange(query.dateRange);
|
|
121
|
+
const accountIds = query.accountIds ?? (await this.listAccounts()).map((a) => a.id);
|
|
122
|
+
const level = DATA_LEVEL[query.level];
|
|
123
|
+
const idDim = ID_DIMENSION[query.level];
|
|
124
|
+
const nameMetric = { campaign: "campaign_name", ad_group: "adgroup_name", ad: "ad_name" }[query.level];
|
|
125
|
+
const rows = [];
|
|
126
|
+
for (const accountId of accountIds) {
|
|
127
|
+
const data = await this.client.get("report/integrated/get", {
|
|
128
|
+
advertiser_id: accountId,
|
|
129
|
+
report_type: "BASIC",
|
|
130
|
+
data_level: level,
|
|
131
|
+
dimensions: [idDim],
|
|
132
|
+
metrics: [
|
|
133
|
+
...nameMetric ? [nameMetric] : [],
|
|
134
|
+
"spend",
|
|
135
|
+
"impressions",
|
|
136
|
+
"clicks",
|
|
137
|
+
"conversion",
|
|
138
|
+
"complete_payment_roas",
|
|
139
|
+
"total_complete_payment_rate"
|
|
140
|
+
],
|
|
141
|
+
start_date: range.start,
|
|
142
|
+
end_date: range.end,
|
|
143
|
+
page: 1,
|
|
144
|
+
page_size: Math.min(query.limit ?? 200, 1e3)
|
|
145
|
+
});
|
|
146
|
+
for (const row of data.list ?? []) {
|
|
147
|
+
rows.push(this.toReportRow(row, accountId, query, idDim, nameMetric));
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
return { rows };
|
|
151
|
+
}
|
|
152
|
+
toReportRow(row, accountId, query, idDim, nameMetric) {
|
|
153
|
+
const num = (key) => Number(row.metrics[key] ?? 0);
|
|
154
|
+
const spend = num("spend");
|
|
155
|
+
const impressions = num("impressions");
|
|
156
|
+
const clicks = num("clicks");
|
|
157
|
+
const conversions = num("conversion");
|
|
158
|
+
const conversionValue = num("total_complete_payment_rate");
|
|
159
|
+
const all = {
|
|
160
|
+
spend: round2(spend),
|
|
161
|
+
impressions,
|
|
162
|
+
clicks,
|
|
163
|
+
conversions,
|
|
164
|
+
conversion_value: round2(conversionValue),
|
|
165
|
+
ctr: impressions > 0 ? round2(clicks / impressions * 100) : 0,
|
|
166
|
+
cpc: clicks > 0 ? round2(spend / clicks) : 0,
|
|
167
|
+
cpm: impressions > 0 ? round2(spend / impressions * 1e3) : 0,
|
|
168
|
+
cpa: conversions > 0 ? round2(spend / conversions) : 0,
|
|
169
|
+
roas: spend > 0 ? round2(conversionValue / spend) : 0
|
|
170
|
+
};
|
|
171
|
+
const entityId = row.dimensions[idDim] ?? "";
|
|
172
|
+
return {
|
|
173
|
+
provider: this.id,
|
|
174
|
+
accountId,
|
|
175
|
+
entity: {
|
|
176
|
+
level: query.level,
|
|
177
|
+
id: entityId,
|
|
178
|
+
name: (nameMetric ? row.metrics[nameMetric] : void 0) ?? entityId
|
|
179
|
+
},
|
|
180
|
+
metrics: Object.fromEntries(query.metrics.map((m) => [m, all[m]]))
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
async rawReport(input) {
|
|
184
|
+
const data = await this.client.get("report/integrated/get", {
|
|
185
|
+
advertiser_id: input.account_id,
|
|
186
|
+
report_type: "BASIC",
|
|
187
|
+
data_level: input.data_level,
|
|
188
|
+
dimensions: input.dimensions,
|
|
189
|
+
metrics: input.metrics,
|
|
190
|
+
start_date: input.start_date,
|
|
191
|
+
end_date: input.end_date,
|
|
192
|
+
page: 1,
|
|
193
|
+
page_size: Math.min(input.page_size ?? 200, 1e3)
|
|
194
|
+
});
|
|
195
|
+
return data.list ?? [];
|
|
196
|
+
}
|
|
197
|
+
async listCampaigns(accountId, campaignIds) {
|
|
198
|
+
const data = await this.client.get("campaign/get", {
|
|
199
|
+
advertiser_id: accountId,
|
|
200
|
+
...campaignIds ? { filtering: { campaign_ids: campaignIds } } : {},
|
|
201
|
+
page: 1,
|
|
202
|
+
page_size: campaignIds ? campaignIds.length : 100
|
|
203
|
+
});
|
|
204
|
+
return data.list ?? [];
|
|
205
|
+
}
|
|
206
|
+
async previewWrite(op, guard) {
|
|
207
|
+
const plan = await this.plan(op, guard);
|
|
208
|
+
return {
|
|
209
|
+
summary: plan.summary,
|
|
210
|
+
changes: plan.changes,
|
|
211
|
+
coercions: plan.coercions,
|
|
212
|
+
budgetDeltas: plan.budgetDeltas,
|
|
213
|
+
serverValidated: false
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
async applyWrite(op, guard) {
|
|
217
|
+
const plan = await this.plan(op, guard);
|
|
218
|
+
const resourceIds = await plan.execute();
|
|
219
|
+
return { applied: true, resourceIds };
|
|
220
|
+
}
|
|
221
|
+
async plan(op, guard) {
|
|
222
|
+
const payload = op.payload;
|
|
223
|
+
switch (op.tool) {
|
|
224
|
+
case "tiktok_create_campaign":
|
|
225
|
+
return this.planCreateCampaign(op.accountId, payload, guard);
|
|
226
|
+
case "tiktok_set_campaign_status":
|
|
227
|
+
return this.planSetStatus(op.accountId, payload);
|
|
228
|
+
case "tiktok_set_budget":
|
|
229
|
+
return this.planSetBudget(op.accountId, payload);
|
|
230
|
+
default:
|
|
231
|
+
throw new AdportError2("PROVIDER_ERROR", `tiktok: unsupported write tool ${op.tool}`);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
async planCreateCampaign(accountId, payload, guard) {
|
|
235
|
+
const coercions = [];
|
|
236
|
+
let operationStatus = payload.operation_status ?? "ENABLE";
|
|
237
|
+
if (guard.forcePausedCreation && operationStatus === "ENABLE") {
|
|
238
|
+
operationStatus = "DISABLE";
|
|
239
|
+
coercions.push("operation_status coerced to DISABLE (paused) by policy (paused_creation)");
|
|
240
|
+
}
|
|
241
|
+
if (payload.budget_mode !== "BUDGET_MODE_INFINITE" && !payload.budget) {
|
|
242
|
+
throw new AdportError2("INVALID_INPUT", `tiktok: budget is required for ${payload.budget_mode}`);
|
|
243
|
+
}
|
|
244
|
+
const budgetDeltas = [];
|
|
245
|
+
if (payload.budget) {
|
|
246
|
+
budgetDeltas.push({
|
|
247
|
+
target: `new campaign "${payload.campaign_name}" ${payload.budget_mode === "BUDGET_MODE_DAY" ? "daily" : "total"} budget`,
|
|
248
|
+
toMicros: payload.budget * UNITS_TO_MICROS
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
return {
|
|
252
|
+
summary: `Create TikTok campaign "${payload.campaign_name}" (${payload.objective_type}, ${operationStatus === "DISABLE" ? "paused" : "active"})`,
|
|
253
|
+
changes: [
|
|
254
|
+
`+ campaign "${payload.campaign_name}" objective=${payload.objective_type} ${payload.budget_mode}` + (payload.budget ? ` budget=${payload.budget}` : "") + ` operation_status=${operationStatus}`
|
|
255
|
+
],
|
|
256
|
+
coercions,
|
|
257
|
+
budgetDeltas,
|
|
258
|
+
execute: async () => {
|
|
259
|
+
const data = await this.client.post("campaign/create", {
|
|
260
|
+
advertiser_id: accountId,
|
|
261
|
+
campaign_name: payload.campaign_name,
|
|
262
|
+
objective_type: payload.objective_type,
|
|
263
|
+
budget_mode: payload.budget_mode,
|
|
264
|
+
...payload.budget ? { budget: payload.budget } : {},
|
|
265
|
+
operation_status: operationStatus
|
|
266
|
+
});
|
|
267
|
+
return data.campaign_id ? [data.campaign_id] : [];
|
|
268
|
+
}
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
async planSetStatus(accountId, payload) {
|
|
272
|
+
const campaigns = await this.listCampaigns(accountId, payload.campaign_ids);
|
|
273
|
+
const changes = payload.campaign_ids.map((id) => {
|
|
274
|
+
const campaign = campaigns.find((c) => c.campaign_id === id);
|
|
275
|
+
return `~ campaign ${id} ("${campaign?.campaign_name ?? "?"}") operation_status ${campaign?.operation_status ?? "?"} \u2192 ${payload.operation_status}`;
|
|
276
|
+
});
|
|
277
|
+
return {
|
|
278
|
+
summary: `Set ${payload.campaign_ids.length} TikTok campaign(s) \u2192 ${payload.operation_status === "DISABLE" ? "paused" : "active"}`,
|
|
279
|
+
changes,
|
|
280
|
+
coercions: [],
|
|
281
|
+
budgetDeltas: [],
|
|
282
|
+
execute: async () => {
|
|
283
|
+
await this.client.post("campaign/status/update", {
|
|
284
|
+
advertiser_id: accountId,
|
|
285
|
+
campaign_ids: payload.campaign_ids,
|
|
286
|
+
operation_status: payload.operation_status
|
|
287
|
+
});
|
|
288
|
+
return payload.campaign_ids;
|
|
289
|
+
}
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
async planSetBudget(accountId, payload) {
|
|
293
|
+
const campaigns = await this.listCampaigns(accountId, [payload.campaign_id]);
|
|
294
|
+
const campaign = campaigns[0];
|
|
295
|
+
if (!campaign) {
|
|
296
|
+
throw new AdportError2("PROVIDER_ERROR", `tiktok: campaign ${payload.campaign_id} not found in advertiser ${accountId}`);
|
|
297
|
+
}
|
|
298
|
+
if (campaign.budget_mode === "BUDGET_MODE_INFINITE") {
|
|
299
|
+
throw new AdportError2("PROVIDER_ERROR", `tiktok: campaign "${campaign.campaign_name}" has no budget (BUDGET_MODE_INFINITE)`);
|
|
300
|
+
}
|
|
301
|
+
return {
|
|
302
|
+
summary: `Change TikTok campaign "${campaign.campaign_name}" budget ${campaign.budget} \u2192 ${payload.budget} (${campaign.budget_mode})`,
|
|
303
|
+
changes: [
|
|
304
|
+
`~ campaign ${payload.campaign_id} budget ${campaign.budget} \u2192 ${payload.budget}`,
|
|
305
|
+
"! TikTok requires the new budget to be \u2265105% of already-spent amount; the API rejects violations"
|
|
306
|
+
],
|
|
307
|
+
coercions: [],
|
|
308
|
+
budgetDeltas: [
|
|
309
|
+
{
|
|
310
|
+
target: `campaign "${campaign.campaign_name}" ${campaign.budget_mode === "BUDGET_MODE_DAY" ? "daily" : "total"} budget`,
|
|
311
|
+
fromMicros: campaign.budget * UNITS_TO_MICROS,
|
|
312
|
+
toMicros: payload.budget * UNITS_TO_MICROS
|
|
313
|
+
}
|
|
314
|
+
],
|
|
315
|
+
execute: async () => {
|
|
316
|
+
await this.client.post("campaign/update", {
|
|
317
|
+
advertiser_id: accountId,
|
|
318
|
+
campaign_id: payload.campaign_id,
|
|
319
|
+
budget: payload.budget
|
|
320
|
+
});
|
|
321
|
+
return [payload.campaign_id];
|
|
322
|
+
}
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
appId() {
|
|
326
|
+
return this.app.appId;
|
|
327
|
+
}
|
|
328
|
+
secret() {
|
|
329
|
+
return this.app.secret;
|
|
330
|
+
}
|
|
331
|
+
};
|
|
332
|
+
function round2(n) {
|
|
333
|
+
return Math.round(n * 100) / 100;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
// src/tools.ts
|
|
337
|
+
import { defineTool, guardedWriteTool } from "@adport/core";
|
|
338
|
+
import { z } from "zod";
|
|
339
|
+
var OBJECTIVES = [
|
|
340
|
+
"REACH",
|
|
341
|
+
"TRAFFIC",
|
|
342
|
+
"VIDEO_VIEWS",
|
|
343
|
+
"LEAD_GENERATION",
|
|
344
|
+
"ENGAGEMENT",
|
|
345
|
+
"APP_PROMOTION",
|
|
346
|
+
"WEB_CONVERSIONS",
|
|
347
|
+
"PRODUCT_SALES"
|
|
348
|
+
];
|
|
349
|
+
var operationStatusSchema = z.enum(["ENABLE", "DISABLE"]);
|
|
350
|
+
function tiktokTools(provider) {
|
|
351
|
+
return [
|
|
352
|
+
defineTool({
|
|
353
|
+
name: "tiktok_campaigns",
|
|
354
|
+
namespace: "tiktok",
|
|
355
|
+
description: "List TikTok campaigns (id, name, operation_status ENABLE/DISABLE, budget, budget_mode, objective).",
|
|
356
|
+
input: z.object({
|
|
357
|
+
account_id: z.string().describe("Advertiser id"),
|
|
358
|
+
campaign_ids: z.array(z.string()).optional()
|
|
359
|
+
}),
|
|
360
|
+
annotations: { readOnly: true },
|
|
361
|
+
async handler(input) {
|
|
362
|
+
const campaigns = await provider.listCampaigns(input.account_id, input.campaign_ids);
|
|
363
|
+
return { campaigns };
|
|
364
|
+
}
|
|
365
|
+
}),
|
|
366
|
+
defineTool({
|
|
367
|
+
name: "tiktok_report",
|
|
368
|
+
namespace: "tiktok",
|
|
369
|
+
description: "Raw TikTok synchronous reporting (report/integrated). Metric values come back as strings; note total_complete_payment_rate is total purchase VALUE (misleading name), complete_payment_roas is purchase ROAS.",
|
|
370
|
+
input: z.object({
|
|
371
|
+
account_id: z.string(),
|
|
372
|
+
data_level: z.enum(["AUCTION_ADVERTISER", "AUCTION_CAMPAIGN", "AUCTION_ADGROUP", "AUCTION_AD"]).default("AUCTION_CAMPAIGN"),
|
|
373
|
+
dimensions: z.array(z.string()).min(1).default(["campaign_id"]),
|
|
374
|
+
metrics: z.array(z.string()).min(1).default(["spend", "impressions", "clicks", "conversion"]),
|
|
375
|
+
start_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
|
|
376
|
+
end_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
|
|
377
|
+
page_size: z.number().int().positive().max(1e3).default(200)
|
|
378
|
+
}),
|
|
379
|
+
annotations: { readOnly: true },
|
|
380
|
+
async handler(input) {
|
|
381
|
+
const rows = await provider.rawReport(input);
|
|
382
|
+
return { rows, row_count: rows.length };
|
|
383
|
+
}
|
|
384
|
+
}),
|
|
385
|
+
guardedWriteTool({
|
|
386
|
+
name: "tiktok_create_campaign",
|
|
387
|
+
namespace: "tiktok",
|
|
388
|
+
description: "Create a TikTok campaign. Budget is a float in whole account-currency units (min ~20 USD-equivalent for DAY/TOTAL modes). TikTok has no server-side dry run \u2014 the preview is a client-side diff.",
|
|
389
|
+
provider: "tiktok",
|
|
390
|
+
kind: "create",
|
|
391
|
+
payload: z.object({
|
|
392
|
+
campaign_name: z.string().min(1).max(512),
|
|
393
|
+
objective_type: z.enum(OBJECTIVES).default("TRAFFIC"),
|
|
394
|
+
budget_mode: z.enum(["BUDGET_MODE_DAY", "BUDGET_MODE_TOTAL", "BUDGET_MODE_INFINITE"]).default("BUDGET_MODE_DAY"),
|
|
395
|
+
budget: z.number().positive().optional().describe("Whole currency units (float), required unless BUDGET_MODE_INFINITE"),
|
|
396
|
+
operation_status: operationStatusSchema.optional()
|
|
397
|
+
})
|
|
398
|
+
}),
|
|
399
|
+
guardedWriteTool({
|
|
400
|
+
name: "tiktok_set_campaign_status",
|
|
401
|
+
namespace: "tiktok",
|
|
402
|
+
description: "Enable or pause (DISABLE) up to 20 TikTok campaigns.",
|
|
403
|
+
provider: "tiktok",
|
|
404
|
+
kind: "update",
|
|
405
|
+
payload: z.object({
|
|
406
|
+
campaign_ids: z.array(z.string()).min(1).max(20),
|
|
407
|
+
operation_status: operationStatusSchema
|
|
408
|
+
})
|
|
409
|
+
}),
|
|
410
|
+
guardedWriteTool({
|
|
411
|
+
name: "tiktok_set_budget",
|
|
412
|
+
namespace: "tiktok",
|
|
413
|
+
description: "Change a TikTok campaign's budget (whole currency units). TikTok rejects new budgets below 105% of current spend.",
|
|
414
|
+
provider: "tiktok",
|
|
415
|
+
kind: "update",
|
|
416
|
+
payload: z.object({
|
|
417
|
+
campaign_id: z.string(),
|
|
418
|
+
budget: z.number().positive()
|
|
419
|
+
})
|
|
420
|
+
})
|
|
421
|
+
];
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
// src/index.ts
|
|
425
|
+
async function resolveTikTokCredentials(store) {
|
|
426
|
+
const record = await store.get("tiktok");
|
|
427
|
+
if (record?.data.access_token && record.data.app_id && record.data.secret) {
|
|
428
|
+
return {
|
|
429
|
+
accessToken: record.data.access_token,
|
|
430
|
+
appId: record.data.app_id,
|
|
431
|
+
secret: record.data.secret,
|
|
432
|
+
sandbox: record.data.sandbox === "true"
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
const env = process.env;
|
|
436
|
+
if (env.TIKTOK_ACCESS_TOKEN && env.TIKTOK_APP_ID && env.TIKTOK_APP_SECRET) {
|
|
437
|
+
return {
|
|
438
|
+
accessToken: env.TIKTOK_ACCESS_TOKEN,
|
|
439
|
+
appId: env.TIKTOK_APP_ID,
|
|
440
|
+
secret: env.TIKTOK_APP_SECRET,
|
|
441
|
+
sandbox: env.TIKTOK_SANDBOX === "true"
|
|
442
|
+
};
|
|
443
|
+
}
|
|
444
|
+
return void 0;
|
|
445
|
+
}
|
|
446
|
+
async function createTikTokModule(store) {
|
|
447
|
+
const credentials = await resolveTikTokCredentials(store);
|
|
448
|
+
if (!credentials) return void 0;
|
|
449
|
+
const provider = new TikTokAdsProvider(new TikTokClient(credentials), {
|
|
450
|
+
appId: credentials.appId,
|
|
451
|
+
secret: credentials.secret
|
|
452
|
+
});
|
|
453
|
+
return { provider, tools: tiktokTools(provider) };
|
|
454
|
+
}
|
|
455
|
+
export {
|
|
456
|
+
TIKTOK_API_VERSION,
|
|
457
|
+
TikTokAdsProvider,
|
|
458
|
+
TikTokClient,
|
|
459
|
+
UNITS_TO_MICROS,
|
|
460
|
+
createTikTokModule,
|
|
461
|
+
resolveTikTokCredentials,
|
|
462
|
+
tiktokTools
|
|
463
|
+
};
|
|
464
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/client.ts","../src/provider.ts","../src/tools.ts","../src/index.ts"],"sourcesContent":["import { AdportError } from '@adport/core';\n\nexport interface TikTokCredentials {\n /** Long-term access token (does not expire; revoked by the advertiser). */\n accessToken: string;\n appId?: string;\n secret?: string;\n /** Use the sandbox environment (sandbox-ads.tiktok.com). */\n sandbox?: boolean;\n}\n\nexport const TIKTOK_API_VERSION = 'v1.3';\nconst PROD_BASE = 'https://business-api.tiktok.com/open_api';\nconst SANDBOX_BASE = 'https://sandbox-ads.tiktok.com/open_api';\n\n/** Business-error codes worth a targeted hint. */\nconst CODE_HINTS: Record<number, string> = {\n 40105: 'The access token is invalid — re-run `adport connect tiktok`.',\n 40102: 'The access token expired or was revoked — re-run `adport connect tiktok`.',\n 40100: 'Rate limited (app level) — back off and retry.',\n 40133: 'Rate limited (advertiser level) — back off and retry.',\n};\n\n/**\n * TikTok Business API client. Peculiarities handled here:\n * - every endpoint needs a TRAILING SLASH (404 otherwise)\n * - business errors arrive as HTTP 200 with a non-zero envelope `code`\n * - array query params are JSON-encoded strings\n */\nexport class TikTokClient {\n readonly baseUrl: string;\n\n constructor(\n private readonly credentials: TikTokCredentials,\n private readonly fetchImpl: typeof fetch = fetch,\n ) {\n this.baseUrl = `${credentials.sandbox ? SANDBOX_BASE : PROD_BASE}/${TIKTOK_API_VERSION}`;\n }\n\n async get<T>(path: string, params: Record<string, string | number | unknown[] | object | undefined> = {}): Promise<T> {\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined) continue;\n search.set(key, typeof value === 'object' ? JSON.stringify(value) : String(value));\n }\n const query = search.size > 0 ? `?${search}` : '';\n return this.send<T>(`${path}${query}`, { method: 'GET' });\n }\n\n async post<T>(path: string, body: Record<string, unknown>): Promise<T> {\n return this.send<T>(path, { method: 'POST', body: JSON.stringify(body) });\n }\n\n private async send<T>(pathWithQuery: string, init: { method: string; body?: string }): Promise<T> {\n // Trailing slash is mandatory before the query string.\n const [path, query] = pathWithQuery.split('?');\n const url = `${this.baseUrl}/${path!.replace(/^\\/|\\/$/g, '')}/${query ? `?${query}` : ''}`;\n const response = await this.fetchImpl(url, {\n method: init.method,\n headers: {\n 'Access-Token': this.credentials.accessToken,\n ...(init.body ? { 'content-type': 'application/json' } : {}),\n },\n body: init.body,\n });\n const raw = await response.text();\n if (!response.ok) {\n throw new AdportError('PROVIDER_ERROR', `TikTok API HTTP ${response.status} for ${path} (check method and trailing slash)`, raw);\n }\n const envelope = JSON.parse(raw) as { code: number; message: string; request_id?: string; data?: T };\n if (envelope.code !== 0) {\n const hint = CODE_HINTS[envelope.code];\n throw new AdportError(\n 'PROVIDER_ERROR',\n `TikTok API error ${envelope.code}: ${envelope.message}${hint ? `\\n ${hint}` : ''}` +\n (envelope.request_id ? ` [request_id: ${envelope.request_id}]` : ''),\n envelope,\n );\n }\n return (envelope.data ?? {}) as T;\n }\n}\n","import {\n AdportError,\n resolveDateRange,\n type Account,\n type AdProvider,\n type MetricName,\n type NormalizedQuery,\n type ProviderCapabilities,\n type Report,\n type ReportRow,\n type StandardActions,\n type WriteGuard,\n type WriteOperation,\n type WritePreview,\n type WriteResult,\n} from '@adport/core';\nimport { TikTokClient } from './client.js';\n\n/** TikTok budgets are floats in whole account-currency units. */\nexport const UNITS_TO_MICROS = 1_000_000;\n\nconst DATA_LEVEL = {\n account: 'AUCTION_ADVERTISER',\n campaign: 'AUCTION_CAMPAIGN',\n ad_group: 'AUCTION_ADGROUP',\n ad: 'AUCTION_AD',\n} as const;\n\nconst ID_DIMENSION = {\n account: 'advertiser_id',\n campaign: 'campaign_id',\n ad_group: 'adgroup_id',\n ad: 'ad_id',\n} as const;\n\ninterface TikTokCampaign {\n campaign_id: string;\n campaign_name: string;\n operation_status: 'ENABLE' | 'DISABLE';\n secondary_status?: string;\n budget: number;\n budget_mode: string;\n objective_type: string;\n}\n\ninterface WritePlan {\n summary: string;\n changes: string[];\n coercions: string[];\n budgetDeltas: WritePreview['budgetDeltas'];\n execute: () => Promise<string[]>;\n}\n\nexport class TikTokAdsProvider implements AdProvider {\n readonly id = 'tiktok';\n\n constructor(\n private readonly client: TikTokClient,\n private readonly app: { appId: string; secret: string },\n ) {}\n\n capabilities(): ProviderCapabilities {\n // No server-side dry run in the Marketing API — previews are client-side diffs.\n return { serverDryRun: false };\n }\n\n standardActions(): StandardActions {\n return {\n pauseCampaign: (accountId, campaignId) => ({\n tool: 'tiktok_set_campaign_status',\n input: { account_id: accountId, campaign_ids: [campaignId], operation_status: 'DISABLE' },\n }),\n };\n }\n\n async listAccounts(): Promise<Account[]> {\n const authorized = await this.client.get<{ list?: Array<{ advertiser_id: string; advertiser_name: string }> }>(\n 'oauth2/advertiser/get',\n { app_id: this.appId(), secret: this.secret() },\n );\n const ids = (authorized.list ?? []).map((a) => a.advertiser_id);\n if (ids.length === 0) return [];\n const info = await this.client.get<{\n list?: Array<{ advertiser_id: string; name?: string; currency?: string; status?: string; timezone?: string }>;\n }>('advertiser/info', { advertiser_ids: ids.slice(0, 100), fields: ['name', 'currency', 'status', 'timezone'] });\n const byId = new Map((info.list ?? []).map((i) => [i.advertiser_id, i]));\n return ids.map((id) => {\n const details = byId.get(id);\n return {\n provider: this.id,\n id,\n name: details?.name ?? (authorized.list ?? []).find((a) => a.advertiser_id === id)?.advertiser_name ?? id,\n currency: details?.currency,\n status: details?.status?.replace('STATUS_', ''),\n };\n });\n }\n\n async report(query: NormalizedQuery): Promise<Report> {\n const range = resolveDateRange(query.dateRange);\n const accountIds = query.accountIds ?? (await this.listAccounts()).map((a) => a.id);\n const level = DATA_LEVEL[query.level];\n const idDim = ID_DIMENSION[query.level];\n const nameMetric = { campaign: 'campaign_name', ad_group: 'adgroup_name', ad: 'ad_name' }[\n query.level as string\n ];\n\n const rows: ReportRow[] = [];\n for (const accountId of accountIds) {\n const data = await this.client.get<{\n list?: Array<{ dimensions: Record<string, string>; metrics: Record<string, string> }>;\n page_info?: { total_number?: number };\n }>('report/integrated/get', {\n advertiser_id: accountId,\n report_type: 'BASIC',\n data_level: level,\n dimensions: [idDim],\n metrics: [\n ...(nameMetric ? [nameMetric] : []),\n 'spend',\n 'impressions',\n 'clicks',\n 'conversion',\n 'complete_payment_roas',\n 'total_complete_payment_rate',\n ],\n start_date: range.start,\n end_date: range.end,\n page: 1,\n page_size: Math.min(query.limit ?? 200, 1000),\n });\n for (const row of data.list ?? []) {\n rows.push(this.toReportRow(row, accountId, query, idDim, nameMetric));\n }\n }\n return { rows };\n }\n\n private toReportRow(\n row: { dimensions: Record<string, string>; metrics: Record<string, string> },\n accountId: string,\n query: NormalizedQuery,\n idDim: string,\n nameMetric?: string,\n ): ReportRow {\n // All TikTok metric values are strings (\"14.68\"); spend is whole currency units.\n const num = (key: string) => Number(row.metrics[key] ?? 0);\n const spend = num('spend');\n const impressions = num('impressions');\n const clicks = num('clicks');\n const conversions = num('conversion');\n // total_complete_payment_rate is (despite the name) total purchase VALUE.\n const conversionValue = num('total_complete_payment_rate');\n const all: Record<MetricName, number> = {\n spend: round2(spend),\n impressions,\n clicks,\n conversions,\n conversion_value: round2(conversionValue),\n ctr: impressions > 0 ? round2((clicks / impressions) * 100) : 0,\n cpc: clicks > 0 ? round2(spend / clicks) : 0,\n cpm: impressions > 0 ? round2((spend / impressions) * 1000) : 0,\n cpa: conversions > 0 ? round2(spend / conversions) : 0,\n roas: spend > 0 ? round2(conversionValue / spend) : 0,\n };\n const entityId = row.dimensions[idDim] ?? '';\n return {\n provider: this.id,\n accountId,\n entity: {\n level: query.level,\n id: entityId,\n name: (nameMetric ? row.metrics[nameMetric] : undefined) ?? entityId,\n },\n metrics: Object.fromEntries(query.metrics.map((m) => [m, all[m]])),\n };\n }\n\n async rawReport(input: {\n account_id: string;\n data_level: string;\n dimensions: string[];\n metrics: string[];\n start_date: string;\n end_date: string;\n page_size?: number;\n }): Promise<Array<Record<string, unknown>>> {\n const data = await this.client.get<{ list?: Array<Record<string, unknown>> }>('report/integrated/get', {\n advertiser_id: input.account_id,\n report_type: 'BASIC',\n data_level: input.data_level,\n dimensions: input.dimensions,\n metrics: input.metrics,\n start_date: input.start_date,\n end_date: input.end_date,\n page: 1,\n page_size: Math.min(input.page_size ?? 200, 1000),\n });\n return data.list ?? [];\n }\n\n async listCampaigns(accountId: string, campaignIds?: string[]): Promise<TikTokCampaign[]> {\n const data = await this.client.get<{ list?: TikTokCampaign[] }>('campaign/get', {\n advertiser_id: accountId,\n ...(campaignIds ? { filtering: { campaign_ids: campaignIds } } : {}),\n page: 1,\n page_size: campaignIds ? campaignIds.length : 100,\n });\n return data.list ?? [];\n }\n\n async previewWrite(op: WriteOperation, guard: WriteGuard): Promise<WritePreview> {\n const plan = await this.plan(op, guard);\n // No validate_only equivalent — the preview is a client-side diff from live lookups.\n return {\n summary: plan.summary,\n changes: plan.changes,\n coercions: plan.coercions,\n budgetDeltas: plan.budgetDeltas,\n serverValidated: false,\n };\n }\n\n async applyWrite(op: WriteOperation, guard: WriteGuard): Promise<WriteResult> {\n const plan = await this.plan(op, guard);\n const resourceIds = await plan.execute();\n return { applied: true, resourceIds };\n }\n\n private async plan(op: WriteOperation, guard: WriteGuard): Promise<WritePlan> {\n const payload = op.payload as never;\n switch (op.tool) {\n case 'tiktok_create_campaign':\n return this.planCreateCampaign(op.accountId, payload, guard);\n case 'tiktok_set_campaign_status':\n return this.planSetStatus(op.accountId, payload);\n case 'tiktok_set_budget':\n return this.planSetBudget(op.accountId, payload);\n default:\n throw new AdportError('PROVIDER_ERROR', `tiktok: unsupported write tool ${op.tool}`);\n }\n }\n\n private async planCreateCampaign(\n accountId: string,\n payload: { campaign_name: string; objective_type: string; budget_mode: string; budget?: number; operation_status?: string },\n guard: WriteGuard,\n ): Promise<WritePlan> {\n const coercions: string[] = [];\n // TikTok creates campaigns ENABLED by default; DISABLE is its \"paused\".\n let operationStatus = payload.operation_status ?? 'ENABLE';\n if (guard.forcePausedCreation && operationStatus === 'ENABLE') {\n operationStatus = 'DISABLE';\n coercions.push('operation_status coerced to DISABLE (paused) by policy (paused_creation)');\n }\n if (payload.budget_mode !== 'BUDGET_MODE_INFINITE' && !payload.budget) {\n throw new AdportError('INVALID_INPUT', `tiktok: budget is required for ${payload.budget_mode}`);\n }\n const budgetDeltas: WritePreview['budgetDeltas'] = [];\n if (payload.budget) {\n budgetDeltas.push({\n target: `new campaign \"${payload.campaign_name}\" ${payload.budget_mode === 'BUDGET_MODE_DAY' ? 'daily' : 'total'} budget`,\n toMicros: payload.budget * UNITS_TO_MICROS,\n });\n }\n return {\n summary: `Create TikTok campaign \"${payload.campaign_name}\" (${payload.objective_type}, ${operationStatus === 'DISABLE' ? 'paused' : 'active'})`,\n changes: [\n `+ campaign \"${payload.campaign_name}\" objective=${payload.objective_type} ${payload.budget_mode}` +\n (payload.budget ? ` budget=${payload.budget}` : '') +\n ` operation_status=${operationStatus}`,\n ],\n coercions,\n budgetDeltas,\n execute: async () => {\n const data = await this.client.post<{ campaign_id?: string }>('campaign/create', {\n advertiser_id: accountId,\n campaign_name: payload.campaign_name,\n objective_type: payload.objective_type,\n budget_mode: payload.budget_mode,\n ...(payload.budget ? { budget: payload.budget } : {}),\n operation_status: operationStatus,\n });\n return data.campaign_id ? [data.campaign_id] : [];\n },\n };\n }\n\n private async planSetStatus(\n accountId: string,\n payload: { campaign_ids: string[]; operation_status: 'ENABLE' | 'DISABLE' },\n ): Promise<WritePlan> {\n const campaigns = await this.listCampaigns(accountId, payload.campaign_ids);\n const changes = payload.campaign_ids.map((id) => {\n const campaign = campaigns.find((c) => c.campaign_id === id);\n return `~ campaign ${id} (\"${campaign?.campaign_name ?? '?'}\") operation_status ${campaign?.operation_status ?? '?'} → ${payload.operation_status}`;\n });\n return {\n summary: `Set ${payload.campaign_ids.length} TikTok campaign(s) → ${payload.operation_status === 'DISABLE' ? 'paused' : 'active'}`,\n changes,\n coercions: [],\n budgetDeltas: [],\n execute: async () => {\n await this.client.post('campaign/status/update', {\n advertiser_id: accountId,\n campaign_ids: payload.campaign_ids,\n operation_status: payload.operation_status,\n });\n return payload.campaign_ids;\n },\n };\n }\n\n private async planSetBudget(\n accountId: string,\n payload: { campaign_id: string; budget: number },\n ): Promise<WritePlan> {\n const campaigns = await this.listCampaigns(accountId, [payload.campaign_id]);\n const campaign = campaigns[0];\n if (!campaign) {\n throw new AdportError('PROVIDER_ERROR', `tiktok: campaign ${payload.campaign_id} not found in advertiser ${accountId}`);\n }\n if (campaign.budget_mode === 'BUDGET_MODE_INFINITE') {\n throw new AdportError('PROVIDER_ERROR', `tiktok: campaign \"${campaign.campaign_name}\" has no budget (BUDGET_MODE_INFINITE)`);\n }\n return {\n summary: `Change TikTok campaign \"${campaign.campaign_name}\" budget ${campaign.budget} → ${payload.budget} (${campaign.budget_mode})`,\n changes: [\n `~ campaign ${payload.campaign_id} budget ${campaign.budget} → ${payload.budget}`,\n '! TikTok requires the new budget to be ≥105% of already-spent amount; the API rejects violations',\n ],\n coercions: [],\n budgetDeltas: [\n {\n target: `campaign \"${campaign.campaign_name}\" ${campaign.budget_mode === 'BUDGET_MODE_DAY' ? 'daily' : 'total'} budget`,\n fromMicros: campaign.budget * UNITS_TO_MICROS,\n toMicros: payload.budget * UNITS_TO_MICROS,\n },\n ],\n execute: async () => {\n await this.client.post('campaign/update', {\n advertiser_id: accountId,\n campaign_id: payload.campaign_id,\n budget: payload.budget,\n });\n return [payload.campaign_id];\n },\n };\n }\n\n private appId(): string {\n return this.app.appId;\n }\n\n private secret(): string {\n return this.app.secret;\n }\n}\n\nfunction round2(n: number): number {\n return Math.round(n * 100) / 100;\n}\n","import { defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport type { TikTokAdsProvider } from './provider.js';\n\nconst OBJECTIVES = [\n 'REACH',\n 'TRAFFIC',\n 'VIDEO_VIEWS',\n 'LEAD_GENERATION',\n 'ENGAGEMENT',\n 'APP_PROMOTION',\n 'WEB_CONVERSIONS',\n 'PRODUCT_SALES',\n] as const;\n\nconst operationStatusSchema = z.enum(['ENABLE', 'DISABLE']);\n\nexport function tiktokTools(provider: TikTokAdsProvider): AnyToolDefinition[] {\n return [\n defineTool({\n name: 'tiktok_campaigns',\n namespace: 'tiktok',\n description: 'List TikTok campaigns (id, name, operation_status ENABLE/DISABLE, budget, budget_mode, objective).',\n input: z.object({\n account_id: z.string().describe('Advertiser id'),\n campaign_ids: z.array(z.string()).optional(),\n }),\n annotations: { readOnly: true },\n async handler(input) {\n const campaigns = await provider.listCampaigns(input.account_id, input.campaign_ids);\n return { campaigns };\n },\n }),\n defineTool({\n name: 'tiktok_report',\n namespace: 'tiktok',\n description:\n 'Raw TikTok synchronous reporting (report/integrated). Metric values come back as strings; ' +\n 'note total_complete_payment_rate is total purchase VALUE (misleading name), complete_payment_roas is purchase ROAS.',\n input: z.object({\n account_id: z.string(),\n data_level: z.enum(['AUCTION_ADVERTISER', 'AUCTION_CAMPAIGN', 'AUCTION_ADGROUP', 'AUCTION_AD']).default('AUCTION_CAMPAIGN'),\n dimensions: z.array(z.string()).min(1).default(['campaign_id']),\n metrics: z.array(z.string()).min(1).default(['spend', 'impressions', 'clicks', 'conversion']),\n start_date: z.string().regex(/^\\d{4}-\\d{2}-\\d{2}$/),\n end_date: z.string().regex(/^\\d{4}-\\d{2}-\\d{2}$/),\n page_size: z.number().int().positive().max(1000).default(200),\n }),\n annotations: { readOnly: true },\n async handler(input) {\n const rows = await provider.rawReport(input);\n return { rows, row_count: rows.length };\n },\n }),\n guardedWriteTool({\n name: 'tiktok_create_campaign',\n namespace: 'tiktok',\n description:\n 'Create a TikTok campaign. Budget is a float in whole account-currency units (min ~20 USD-equivalent for ' +\n 'DAY/TOTAL modes). TikTok has no server-side dry run — the preview is a client-side diff.',\n provider: 'tiktok',\n kind: 'create',\n payload: z.object({\n campaign_name: z.string().min(1).max(512),\n objective_type: z.enum(OBJECTIVES).default('TRAFFIC'),\n budget_mode: z.enum(['BUDGET_MODE_DAY', 'BUDGET_MODE_TOTAL', 'BUDGET_MODE_INFINITE']).default('BUDGET_MODE_DAY'),\n budget: z.number().positive().optional().describe('Whole currency units (float), required unless BUDGET_MODE_INFINITE'),\n operation_status: operationStatusSchema.optional(),\n }),\n }),\n guardedWriteTool({\n name: 'tiktok_set_campaign_status',\n namespace: 'tiktok',\n description: 'Enable or pause (DISABLE) up to 20 TikTok campaigns.',\n provider: 'tiktok',\n kind: 'update',\n payload: z.object({\n campaign_ids: z.array(z.string()).min(1).max(20),\n operation_status: operationStatusSchema,\n }),\n }),\n guardedWriteTool({\n name: 'tiktok_set_budget',\n namespace: 'tiktok',\n description:\n \"Change a TikTok campaign's budget (whole currency units). TikTok rejects new budgets below 105% of current spend.\",\n provider: 'tiktok',\n kind: 'update',\n payload: z.object({\n campaign_id: z.string(),\n budget: z.number().positive(),\n }),\n }),\n ];\n}\n","import type { CredentialStore, ProviderModule } from '@adport/core';\nimport { TikTokClient, type TikTokCredentials } from './client.js';\nimport { TikTokAdsProvider } from './provider.js';\nimport { tiktokTools } from './tools.js';\n\nexport { TikTokClient, TIKTOK_API_VERSION, type TikTokCredentials } from './client.js';\nexport { TikTokAdsProvider, UNITS_TO_MICROS } from './provider.js';\nexport { tiktokTools } from './tools.js';\n\nexport async function resolveTikTokCredentials(\n store: CredentialStore,\n): Promise<(TikTokCredentials & { appId: string; secret: string }) | undefined> {\n const record = await store.get('tiktok');\n if (record?.data.access_token && record.data.app_id && record.data.secret) {\n return {\n accessToken: record.data.access_token,\n appId: record.data.app_id,\n secret: record.data.secret,\n sandbox: record.data.sandbox === 'true',\n };\n }\n const env = process.env;\n if (env.TIKTOK_ACCESS_TOKEN && env.TIKTOK_APP_ID && env.TIKTOK_APP_SECRET) {\n return {\n accessToken: env.TIKTOK_ACCESS_TOKEN,\n appId: env.TIKTOK_APP_ID,\n secret: env.TIKTOK_APP_SECRET,\n sandbox: env.TIKTOK_SANDBOX === 'true',\n };\n }\n return undefined;\n}\n\nexport async function createTikTokModule(store: CredentialStore): Promise<ProviderModule | undefined> {\n const credentials = await resolveTikTokCredentials(store);\n if (!credentials) return undefined;\n const provider = new TikTokAdsProvider(new TikTokClient(credentials), {\n appId: credentials.appId,\n secret: credentials.secret,\n });\n return { provider, tools: tiktokTools(provider) };\n}\n"],"mappings":";AAAA,SAAS,mBAAmB;AAWrB,IAAM,qBAAqB;AAClC,IAAM,YAAY;AAClB,IAAM,eAAe;AAGrB,IAAM,aAAqC;AAAA,EACzC,OAAO;AAAA,EACP,OAAO;AAAA,EACP,OAAO;AAAA,EACP,OAAO;AACT;AAQO,IAAM,eAAN,MAAmB;AAAA,EAGxB,YACmB,aACA,YAA0B,OAC3C;AAFiB;AACA;AAEjB,SAAK,UAAU,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AAO,KAAK;AAAA,MACnB,QAAQ,OAAO,KAAK;AAAA,MACpB,SAAS,OAAO,KAAK,YAAY;AAAA,IACnC;AAAA,EACF;AACA,QAAM,MAAM,QAAQ;AACpB,MAAI,IAAI,uBAAuB,IAAI,iBAAiB,IAAI,mBAAmB;AACzE,WAAO;AAAA,MACL,aAAa,IAAI;AAAA,MACjB,OAAO,IAAI;AAAA,MACX,QAAQ,IAAI;AAAA,MACZ,SAAS,IAAI,mBAAmB;AAAA,IAClC;AAAA,EACF;AACA,SAAO;AACT;AAEA,eAAsB,mBAAmB,OAA6D;AACpG,QAAM,cAAc,MAAM,yBAAyB,KAAK;AACxD,MAAI,CAAC,YAAa,QAAO;AACzB,QAAM,WAAW,IAAI,kBAAkB,IAAI,aAAa,WAAW,GAAG;AAAA,IACpE,OAAO,YAAY;AAAA,IACnB,QAAQ,YAAY;AAAA,EACtB,CAAC;AACD,SAAO,EAAE,UAAU,OAAO,YAAY,QAAQ,EAAE;AAClD;","names":["AdportError"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@adport/provider-tiktok",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "TikTok Ads provider for adport — TikTok Business/Marketing API v1.3 with sandbox support",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"import": "./dist/index.js"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"dist"
|
|
17
|
+
],
|
|
18
|
+
"dependencies": {
|
|
19
|
+
"zod": "^3.25.0",
|
|
20
|
+
"@adport/core": "0.1.0"
|
|
21
|
+
},
|
|
22
|
+
"devDependencies": {
|
|
23
|
+
"@types/node": "^22.10.0",
|
|
24
|
+
"tsup": "^8.3.0",
|
|
25
|
+
"typescript": "^5.8.0",
|
|
26
|
+
"vitest": "^3.0.0"
|
|
27
|
+
},
|
|
28
|
+
"scripts": {
|
|
29
|
+
"build": "tsup src/index.ts --format esm --dts --sourcemap --clean",
|
|
30
|
+
"test": "vitest run",
|
|
31
|
+
"typecheck": "tsc --noEmit",
|
|
32
|
+
"clean": "rm -rf dist"
|
|
33
|
+
}
|
|
34
|
+
}
|