@adport/provider-apple 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 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.
@@ -0,0 +1,112 @@
1
+ import { AdProvider, ProviderCapabilities, StandardActions, Account, NormalizedQuery, Report, WriteOperation, WriteGuard, WritePreview, WriteResult, AnyToolDefinition, CredentialStore, ProviderModule } from '@adport/core';
2
+
3
+ interface AppleCredentials {
4
+ clientId: string;
5
+ teamId: string;
6
+ keyId: string;
7
+ /** PEM contents of the .p8 EC private key. */
8
+ privateKeyPem: string;
9
+ }
10
+ /**
11
+ * VERSION ISOLATION: everything version-specific lives in these constants and
12
+ * the envelope helpers. The Campaign Management API v5 sunsets 2027-01-26; the
13
+ * successor "Apple Ads Platform API" (v1, preview July 2026) changes, per
14
+ * Apple's preview guide: base URL → https://api.ads.apple.com/v1, envelope
15
+ * `data` → `result`, X-AP-Context orgId= → adAccountId=, GET-all//find →
16
+ * POST /{entity}/query, error shape → {error:{code,message,details[]}}.
17
+ * Migrate here when the Platform API reference goes live.
18
+ */
19
+ declare const APPLE_ADS_BASE = "https://api.searchads.apple.com/api/v5";
20
+ interface AppleEnvelope<T> {
21
+ data: T;
22
+ pagination?: {
23
+ totalResults: number;
24
+ startIndex: number;
25
+ itemsPerPage: number;
26
+ } | null;
27
+ error?: {
28
+ errors?: Array<{
29
+ messageCode?: string;
30
+ message?: string;
31
+ field?: string;
32
+ }>;
33
+ } | null;
34
+ }
35
+ declare class AppleAdsClient {
36
+ private readonly credentials;
37
+ private readonly fetchImpl;
38
+ private accessToken?;
39
+ constructor(credentials: AppleCredentials, fetchImpl?: typeof fetch);
40
+ getAccessToken(): Promise<string>;
41
+ /** orgId (as X-AP-Context) is required on all endpoints except /acls and /me. */
42
+ request<T>(method: 'GET' | 'POST' | 'PUT', path: string, options?: {
43
+ orgId?: string;
44
+ body?: unknown;
45
+ }): Promise<AppleEnvelope<T>>;
46
+ }
47
+ /** v5 error shape: {"error": {"errors": [{"messageCode", "message", "field"}]}} */
48
+ declare function formatAppleError(status: number, raw: string): string;
49
+
50
+ interface ClientSecretInput {
51
+ /** SEARCHADS.<uuid> */
52
+ clientId: string;
53
+ /** SEARCHADS.<uuid> — equals clientId for self-managed orgs. */
54
+ teamId: string;
55
+ /** keyId of the public key uploaded in the Apple Ads UI. */
56
+ keyId: string;
57
+ /** EC prime256v1 private key, PEM (.p8 contents). */
58
+ privateKeyPem: string;
59
+ /** Secret lifetime in seconds; Apple caps exp at iat + 180 days. */
60
+ lifetimeSeconds?: number;
61
+ }
62
+ /**
63
+ * Apple Ads client secret: a self-signed ES256 JWT (header {alg, kid}; claims
64
+ * iss=teamId, sub=clientId, aud=https://appleid.apple.com, iat, exp≤iat+180d).
65
+ * We mint a short-lived secret per token request instead of storing one.
66
+ */
67
+ declare function createClientSecret(input: ClientSecretInput, now?: Date): string;
68
+
69
+ /** Apple Money amounts are strings in whole currency units. */
70
+ declare const UNITS_TO_MICROS = 1000000;
71
+ interface Money {
72
+ amount: string;
73
+ currency: string;
74
+ }
75
+ interface AppleCampaign {
76
+ id: number;
77
+ name: string;
78
+ status: 'ENABLED' | 'PAUSED';
79
+ servingStatus?: string;
80
+ displayStatus?: string;
81
+ dailyBudgetAmount?: Money;
82
+ adamId?: number;
83
+ countriesOrRegions?: string[];
84
+ billingEvent?: string;
85
+ supplySources?: string[];
86
+ }
87
+ declare class AppleAdsProvider implements AdProvider {
88
+ private readonly client;
89
+ readonly id = "apple";
90
+ constructor(client: AppleAdsClient);
91
+ capabilities(): ProviderCapabilities;
92
+ standardActions(): StandardActions;
93
+ /** Apple "accounts" are organizations from the user ACL. */
94
+ listAccounts(): Promise<Account[]>;
95
+ listCampaigns(orgId: string, limit?: number): Promise<AppleCampaign[]>;
96
+ getCampaign(orgId: string, campaignId: string): Promise<AppleCampaign>;
97
+ report(query: NormalizedQuery): Promise<Report>;
98
+ private toReportRow;
99
+ previewWrite(op: WriteOperation, guard: WriteGuard): Promise<WritePreview>;
100
+ applyWrite(op: WriteOperation, guard: WriteGuard): Promise<WriteResult>;
101
+ private plan;
102
+ private planCreateCampaign;
103
+ private planSetStatus;
104
+ private planSetBudget;
105
+ }
106
+
107
+ declare function appleTools(provider: AppleAdsProvider): AnyToolDefinition[];
108
+
109
+ declare function resolveAppleCredentials(store: CredentialStore): Promise<AppleCredentials | undefined>;
110
+ declare function createAppleModule(store: CredentialStore): Promise<ProviderModule | undefined>;
111
+
112
+ export { APPLE_ADS_BASE, AppleAdsClient, AppleAdsProvider, type AppleCredentials, type AppleEnvelope, type ClientSecretInput, UNITS_TO_MICROS, appleTools, createAppleModule, createClientSecret, formatAppleError, resolveAppleCredentials };
package/dist/index.js ADDED
@@ -0,0 +1,419 @@
1
+ // src/client.ts
2
+ import { AdportError } from "@adport/core";
3
+
4
+ // src/jwt.ts
5
+ import { createPrivateKey, sign } from "crypto";
6
+ function b64url(data) {
7
+ return Buffer.from(data).toString("base64url");
8
+ }
9
+ function createClientSecret(input, now = /* @__PURE__ */ new Date()) {
10
+ const iat = Math.floor(now.getTime() / 1e3);
11
+ const lifetime = Math.min(input.lifetimeSeconds ?? 3600, 180 * 86400 - 60);
12
+ const header = { alg: "ES256", kid: input.keyId };
13
+ const payload = {
14
+ iss: input.teamId,
15
+ iat,
16
+ exp: iat + lifetime,
17
+ aud: "https://appleid.apple.com",
18
+ sub: input.clientId
19
+ };
20
+ const signingInput = `${b64url(JSON.stringify(header))}.${b64url(JSON.stringify(payload))}`;
21
+ const key = createPrivateKey(input.privateKeyPem);
22
+ const signature = sign("sha256", Buffer.from(signingInput), { key, dsaEncoding: "ieee-p1363" });
23
+ return `${signingInput}.${b64url(signature)}`;
24
+ }
25
+
26
+ // src/client.ts
27
+ var TOKEN_URL = "https://appleid.apple.com/auth/oauth2/token";
28
+ var APPLE_ADS_BASE = "https://api.searchads.apple.com/api/v5";
29
+ var AppleAdsClient = class {
30
+ constructor(credentials, fetchImpl = fetch) {
31
+ this.credentials = credentials;
32
+ this.fetchImpl = fetchImpl;
33
+ }
34
+ credentials;
35
+ fetchImpl;
36
+ accessToken;
37
+ async getAccessToken() {
38
+ if (this.accessToken && this.accessToken.expiresAt > Date.now()) {
39
+ return this.accessToken.token;
40
+ }
41
+ const clientSecret = createClientSecret(this.credentials);
42
+ const response = await this.fetchImpl(TOKEN_URL, {
43
+ method: "POST",
44
+ headers: { "content-type": "application/x-www-form-urlencoded" },
45
+ body: new URLSearchParams({
46
+ grant_type: "client_credentials",
47
+ client_id: this.credentials.clientId,
48
+ client_secret: clientSecret,
49
+ scope: "searchadsorg"
50
+ })
51
+ });
52
+ const raw = await response.text();
53
+ if (!response.ok) {
54
+ throw new AdportError(
55
+ "PROVIDER_ERROR",
56
+ `Apple Ads OAuth failed (${response.status}). Check clientId/teamId/keyId and that the public key is uploaded in Account Settings > API.`,
57
+ safeJson(raw)
58
+ );
59
+ }
60
+ const data = JSON.parse(raw);
61
+ this.accessToken = { token: data.access_token, expiresAt: Date.now() + (data.expires_in - 60) * 1e3 };
62
+ return this.accessToken.token;
63
+ }
64
+ /** orgId (as X-AP-Context) is required on all endpoints except /acls and /me. */
65
+ async request(method, path, options = {}) {
66
+ const token = await this.getAccessToken();
67
+ const response = await this.fetchImpl(`${APPLE_ADS_BASE}/${path.replace(/^\//, "")}`, {
68
+ method,
69
+ headers: {
70
+ authorization: `Bearer ${token}`,
71
+ ...options.orgId ? { "X-AP-Context": `orgId=${options.orgId}` } : {},
72
+ ...options.body !== void 0 ? { "content-type": "application/json" } : {}
73
+ },
74
+ body: options.body === void 0 ? void 0 : JSON.stringify(options.body)
75
+ });
76
+ const raw = await response.text();
77
+ if (!response.ok) {
78
+ throw new AdportError("PROVIDER_ERROR", formatAppleError(response.status, raw), safeJson(raw));
79
+ }
80
+ return raw ? JSON.parse(raw) : { data: void 0 };
81
+ }
82
+ };
83
+ function safeJson(raw) {
84
+ try {
85
+ return JSON.parse(raw);
86
+ } catch {
87
+ return raw;
88
+ }
89
+ }
90
+ function formatAppleError(status, raw) {
91
+ const parsed = safeJson(raw);
92
+ const items = parsed?.error?.errors ?? [];
93
+ const head = `Apple Ads API error (HTTP ${status})`;
94
+ if (items.length === 0) return head;
95
+ const lines = items.map(
96
+ (e) => `${e.messageCode ?? "?"}: ${e.message ?? ""}${e.field && e.field !== "null" ? ` (field: ${e.field})` : ""}`
97
+ );
98
+ const hint = status === 401 ? "\n Token or org access problem \u2014 check credentials and org roles." : "";
99
+ return `${head}
100
+ ${lines.join("\n ")}${hint}`;
101
+ }
102
+
103
+ // src/provider.ts
104
+ import {
105
+ AdportError as AdportError2,
106
+ resolveDateRange
107
+ } from "@adport/core";
108
+ var UNITS_TO_MICROS = 1e6;
109
+ var AppleAdsProvider = class {
110
+ constructor(client) {
111
+ this.client = client;
112
+ }
113
+ client;
114
+ id = "apple";
115
+ capabilities() {
116
+ return { serverDryRun: false };
117
+ }
118
+ standardActions() {
119
+ return {
120
+ pauseCampaign: (accountId, campaignId) => ({
121
+ tool: "apple_set_campaign_status",
122
+ input: { account_id: accountId, campaign_id: campaignId, status: "PAUSED" }
123
+ })
124
+ };
125
+ }
126
+ /** Apple "accounts" are organizations from the user ACL. */
127
+ async listAccounts() {
128
+ const envelope = await this.client.request("GET", "acls");
129
+ return (envelope.data ?? []).map((acl) => ({
130
+ provider: this.id,
131
+ id: String(acl.orgId),
132
+ name: acl.orgName,
133
+ currency: acl.currency,
134
+ status: acl.roleNames?.join(",") || void 0
135
+ }));
136
+ }
137
+ async listCampaigns(orgId, limit = 100) {
138
+ const envelope = await this.client.request("GET", `campaigns?limit=${limit}&offset=0`, {
139
+ orgId
140
+ });
141
+ return envelope.data ?? [];
142
+ }
143
+ async getCampaign(orgId, campaignId) {
144
+ const envelope = await this.client.request("POST", "campaigns/find", {
145
+ orgId,
146
+ body: {
147
+ conditions: [{ field: "id", operator: "EQUALS", values: [String(campaignId)] }],
148
+ pagination: { offset: 0, limit: 1 }
149
+ }
150
+ });
151
+ const campaign = envelope.data?.[0];
152
+ if (!campaign) {
153
+ throw new AdportError2("PROVIDER_ERROR", `apple: campaign ${campaignId} not found in org ${orgId}`);
154
+ }
155
+ return campaign;
156
+ }
157
+ async report(query) {
158
+ if (query.level !== "campaign" && query.level !== "account") {
159
+ throw new AdportError2("INVALID_INPUT", "apple: report supports campaign and account levels in v0");
160
+ }
161
+ const range = resolveDateRange(query.dateRange);
162
+ const accountIds = query.accountIds ?? (await this.listAccounts()).map((a) => a.id);
163
+ const rows = [];
164
+ for (const orgId of accountIds) {
165
+ const envelope = await this.client.request(
166
+ "POST",
167
+ "reports/campaigns",
168
+ {
169
+ orgId,
170
+ body: {
171
+ startTime: range.start,
172
+ endTime: range.end,
173
+ selector: {
174
+ orderBy: [{ field: "countryOrRegion", sortOrder: "ASCENDING" }],
175
+ pagination: { offset: 0, limit: Math.min(query.limit ?? 200, 1e3) }
176
+ },
177
+ timeZone: "UTC",
178
+ returnRowTotals: true,
179
+ returnGrandTotals: true,
180
+ returnRecordsWithNoMetrics: false
181
+ }
182
+ }
183
+ );
184
+ for (const row of envelope.data?.reportingDataResponse?.row ?? []) {
185
+ rows.push(this.toReportRow(row, orgId, query));
186
+ }
187
+ }
188
+ return { rows };
189
+ }
190
+ toReportRow(row, orgId, query) {
191
+ const total = row.total ?? {};
192
+ const spend = Number(total.localSpend?.amount ?? 0);
193
+ const impressions = total.impressions ?? 0;
194
+ const clicks = total.taps ?? 0;
195
+ const conversions = total.totalInstalls ?? 0;
196
+ const all = {
197
+ spend: round2(spend),
198
+ impressions,
199
+ clicks,
200
+ conversions,
201
+ conversion_value: 0,
202
+ ctr: impressions > 0 ? round2(clicks / impressions * 100) : 0,
203
+ cpc: clicks > 0 ? round2(spend / clicks) : 0,
204
+ cpm: impressions > 0 ? round2(spend / impressions * 1e3) : 0,
205
+ cpa: conversions > 0 ? round2(spend / conversions) : 0,
206
+ roas: 0
207
+ };
208
+ return {
209
+ provider: this.id,
210
+ accountId: orgId,
211
+ entity: {
212
+ level: "campaign",
213
+ id: String(row.metadata?.campaignId ?? ""),
214
+ name: row.metadata?.campaignName ?? "",
215
+ status: row.metadata?.campaignStatus
216
+ },
217
+ metrics: Object.fromEntries(query.metrics.map((m) => [m, all[m]]))
218
+ };
219
+ }
220
+ async previewWrite(op, guard) {
221
+ const plan = await this.plan(op, guard);
222
+ return {
223
+ summary: plan.summary,
224
+ changes: plan.changes,
225
+ coercions: plan.coercions,
226
+ budgetDeltas: plan.budgetDeltas,
227
+ serverValidated: false
228
+ };
229
+ }
230
+ async applyWrite(op, guard) {
231
+ const plan = await this.plan(op, guard);
232
+ const resourceIds = await plan.execute();
233
+ return { applied: true, resourceIds };
234
+ }
235
+ async plan(op, guard) {
236
+ const payload = op.payload;
237
+ switch (op.tool) {
238
+ case "apple_create_campaign":
239
+ return this.planCreateCampaign(op.accountId, payload, guard);
240
+ case "apple_set_campaign_status":
241
+ return this.planSetStatus(op.accountId, payload);
242
+ case "apple_set_budget":
243
+ return this.planSetBudget(op.accountId, payload);
244
+ default:
245
+ throw new AdportError2("PROVIDER_ERROR", `apple: unsupported write tool ${op.tool}`);
246
+ }
247
+ }
248
+ async planCreateCampaign(orgId, payload, guard) {
249
+ const coercions = [];
250
+ let status = payload.status ?? "ENABLED";
251
+ if (guard.forcePausedCreation && status === "ENABLED") {
252
+ status = "PAUSED";
253
+ coercions.push("status coerced to PAUSED by policy (paused_creation)");
254
+ }
255
+ const body = {
256
+ orgId: Number(orgId),
257
+ name: payload.name,
258
+ adamId: payload.adam_id,
259
+ countriesOrRegions: payload.countries_or_regions,
260
+ dailyBudgetAmount: { amount: String(payload.daily_budget), currency: payload.currency },
261
+ adChannelType: "SEARCH",
262
+ billingEvent: "TAPS",
263
+ supplySources: ["APPSTORE_SEARCH_RESULTS"],
264
+ status
265
+ };
266
+ return {
267
+ summary: `Create Apple Ads campaign "${payload.name}" (${status}) \u2014 daily budget ${payload.daily_budget} ${payload.currency}`,
268
+ changes: [
269
+ `+ campaign "${payload.name}" app=${payload.adam_id} regions=[${payload.countries_or_regions.join(", ")}] status=${status}`
270
+ ],
271
+ coercions,
272
+ budgetDeltas: [
273
+ { target: `new campaign "${payload.name}" daily budget`, toMicros: payload.daily_budget * UNITS_TO_MICROS }
274
+ ],
275
+ execute: async () => {
276
+ const envelope = await this.client.request("POST", "campaigns", { orgId, body });
277
+ return envelope.data?.id ? [String(envelope.data.id)] : [];
278
+ }
279
+ };
280
+ }
281
+ async planSetStatus(orgId, payload) {
282
+ const current = await this.getCampaign(orgId, payload.campaign_id);
283
+ return {
284
+ summary: `Set Apple campaign "${current.name}" status ${current.status} \u2192 ${payload.status}`,
285
+ changes: [`~ campaign ${payload.campaign_id} status ${current.status} \u2192 ${payload.status}`],
286
+ coercions: [],
287
+ budgetDeltas: [],
288
+ execute: async () => {
289
+ await this.client.request("PUT", `campaigns/${payload.campaign_id}`, {
290
+ orgId,
291
+ body: { campaign: { status: payload.status } }
292
+ });
293
+ return [payload.campaign_id];
294
+ }
295
+ };
296
+ }
297
+ async planSetBudget(orgId, payload) {
298
+ const current = await this.getCampaign(orgId, payload.campaign_id);
299
+ const fromAmount = current.dailyBudgetAmount ? Number(current.dailyBudgetAmount.amount) : void 0;
300
+ const currency = current.dailyBudgetAmount?.currency ?? "USD";
301
+ return {
302
+ summary: `Change Apple campaign "${current.name}" daily budget ${fromAmount ?? "(unset)"} \u2192 ${payload.daily_budget} ${currency}`,
303
+ changes: [`~ campaign ${payload.campaign_id} dailyBudgetAmount ${fromAmount ?? "(unset)"} \u2192 ${payload.daily_budget}`],
304
+ coercions: [],
305
+ budgetDeltas: [
306
+ {
307
+ target: `campaign "${current.name}" daily budget`,
308
+ ...fromAmount !== void 0 ? { fromMicros: fromAmount * UNITS_TO_MICROS } : {},
309
+ toMicros: payload.daily_budget * UNITS_TO_MICROS
310
+ }
311
+ ],
312
+ execute: async () => {
313
+ await this.client.request("PUT", `campaigns/${payload.campaign_id}`, {
314
+ orgId,
315
+ body: { campaign: { dailyBudgetAmount: { amount: String(payload.daily_budget), currency } } }
316
+ });
317
+ return [payload.campaign_id];
318
+ }
319
+ };
320
+ }
321
+ };
322
+ function round2(n) {
323
+ return Math.round(n * 100) / 100;
324
+ }
325
+
326
+ // src/tools.ts
327
+ import { defineTool, guardedWriteTool } from "@adport/core";
328
+ import { z } from "zod";
329
+ var statusSchema = z.enum(["ENABLED", "PAUSED"]);
330
+ function appleTools(provider) {
331
+ return [
332
+ defineTool({
333
+ name: "apple_campaigns",
334
+ namespace: "apple",
335
+ description: "List Apple Ads campaigns for an organization (id, name, status, servingStatus, dailyBudgetAmount as string Money).",
336
+ input: z.object({
337
+ account_id: z.string().describe("Apple Ads organization id (orgId)"),
338
+ limit: z.number().int().positive().max(1e3).default(100)
339
+ }),
340
+ annotations: { readOnly: true },
341
+ async handler(input) {
342
+ const campaigns = await provider.listCampaigns(input.account_id, input.limit);
343
+ return { campaigns };
344
+ }
345
+ }),
346
+ guardedWriteTool({
347
+ name: "apple_create_campaign",
348
+ namespace: "apple",
349
+ description: "Create an Apple Ads search campaign (App Store search results, TAPS billing). daily_budget is a float in whole currency units; adam_id is the App Store app id. Apple has no dry run \u2014 previews are client-side diffs.",
350
+ provider: "apple",
351
+ kind: "create",
352
+ payload: z.object({
353
+ name: z.string().min(1),
354
+ adam_id: z.number().int().positive().describe("App Store app id (adamId)"),
355
+ countries_or_regions: z.array(z.string().length(2)).min(1),
356
+ daily_budget: z.number().positive(),
357
+ currency: z.string().length(3).describe("Org currency, e.g. USD/EUR"),
358
+ status: statusSchema.optional()
359
+ })
360
+ }),
361
+ guardedWriteTool({
362
+ name: "apple_set_campaign_status",
363
+ namespace: "apple",
364
+ description: "Enable or pause an Apple Ads campaign.",
365
+ provider: "apple",
366
+ kind: "update",
367
+ payload: z.object({ campaign_id: z.string(), status: statusSchema })
368
+ }),
369
+ guardedWriteTool({
370
+ name: "apple_set_budget",
371
+ namespace: "apple",
372
+ description: "Change an Apple Ads campaign's daily budget (float, whole currency units).",
373
+ provider: "apple",
374
+ kind: "update",
375
+ payload: z.object({ campaign_id: z.string(), daily_budget: z.number().positive() })
376
+ })
377
+ ];
378
+ }
379
+
380
+ // src/index.ts
381
+ async function resolveAppleCredentials(store) {
382
+ const record = await store.get("apple");
383
+ if (record?.data.client_id && record.data.team_id && record.data.key_id && record.data.private_key) {
384
+ return {
385
+ clientId: record.data.client_id,
386
+ teamId: record.data.team_id,
387
+ keyId: record.data.key_id,
388
+ privateKeyPem: record.data.private_key
389
+ };
390
+ }
391
+ const env = process.env;
392
+ if (env.APPLE_ADS_CLIENT_ID && env.APPLE_ADS_TEAM_ID && env.APPLE_ADS_KEY_ID && env.APPLE_ADS_PRIVATE_KEY) {
393
+ return {
394
+ clientId: env.APPLE_ADS_CLIENT_ID,
395
+ teamId: env.APPLE_ADS_TEAM_ID,
396
+ keyId: env.APPLE_ADS_KEY_ID,
397
+ privateKeyPem: env.APPLE_ADS_PRIVATE_KEY
398
+ };
399
+ }
400
+ return void 0;
401
+ }
402
+ async function createAppleModule(store) {
403
+ const credentials = await resolveAppleCredentials(store);
404
+ if (!credentials) return void 0;
405
+ const provider = new AppleAdsProvider(new AppleAdsClient(credentials));
406
+ return { provider, tools: appleTools(provider) };
407
+ }
408
+ export {
409
+ APPLE_ADS_BASE,
410
+ AppleAdsClient,
411
+ AppleAdsProvider,
412
+ UNITS_TO_MICROS,
413
+ appleTools,
414
+ createAppleModule,
415
+ createClientSecret,
416
+ formatAppleError,
417
+ resolveAppleCredentials
418
+ };
419
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/client.ts","../src/jwt.ts","../src/provider.ts","../src/tools.ts","../src/index.ts"],"sourcesContent":["import { AdportError } from '@adport/core';\nimport { createClientSecret } from './jwt.js';\n\nexport interface AppleCredentials {\n clientId: string;\n teamId: string;\n keyId: string;\n /** PEM contents of the .p8 EC private key. */\n privateKeyPem: string;\n}\n\nconst TOKEN_URL = 'https://appleid.apple.com/auth/oauth2/token';\n\n/**\n * VERSION ISOLATION: everything version-specific lives in these constants and\n * the envelope helpers. The Campaign Management API v5 sunsets 2027-01-26; the\n * successor \"Apple Ads Platform API\" (v1, preview July 2026) changes, per\n * Apple's preview guide: base URL → https://api.ads.apple.com/v1, envelope\n * `data` → `result`, X-AP-Context orgId= → adAccountId=, GET-all//find →\n * POST /{entity}/query, error shape → {error:{code,message,details[]}}.\n * Migrate here when the Platform API reference goes live.\n */\nexport const APPLE_ADS_BASE = 'https://api.searchads.apple.com/api/v5';\n\nexport interface AppleEnvelope<T> {\n data: T;\n pagination?: { totalResults: number; startIndex: number; itemsPerPage: number } | null;\n error?: { errors?: Array<{ messageCode?: string; message?: string; field?: string }> } | null;\n}\n\nexport class AppleAdsClient {\n private accessToken?: { token: string; expiresAt: number };\n\n constructor(\n private readonly credentials: AppleCredentials,\n private readonly fetchImpl: typeof fetch = fetch,\n ) {}\n\n async getAccessToken(): Promise<string> {\n if (this.accessToken && this.accessToken.expiresAt > Date.now()) {\n return this.accessToken.token;\n }\n // Mint a fresh short-lived client secret per request — no 180-day rotation to manage.\n const clientSecret = createClientSecret(this.credentials);\n const response = await this.fetchImpl(TOKEN_URL, {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n grant_type: 'client_credentials',\n client_id: this.credentials.clientId,\n client_secret: clientSecret,\n scope: 'searchadsorg',\n }),\n });\n const raw = await response.text();\n if (!response.ok) {\n throw new AdportError(\n 'PROVIDER_ERROR',\n `Apple Ads OAuth failed (${response.status}). Check clientId/teamId/keyId and that the public key is uploaded in Account Settings > API.`,\n safeJson(raw),\n );\n }\n const data = JSON.parse(raw) as { access_token: string; expires_in: number };\n this.accessToken = { token: data.access_token, expiresAt: Date.now() + (data.expires_in - 60) * 1000 };\n return this.accessToken.token;\n }\n\n /** orgId (as X-AP-Context) is required on all endpoints except /acls and /me. */\n async request<T>(\n method: 'GET' | 'POST' | 'PUT',\n path: string,\n options: { orgId?: string; body?: unknown } = {},\n ): Promise<AppleEnvelope<T>> {\n const token = await this.getAccessToken();\n const response = await this.fetchImpl(`${APPLE_ADS_BASE}/${path.replace(/^\\//, '')}`, {\n method,\n headers: {\n authorization: `Bearer ${token}`,\n ...(options.orgId ? { 'X-AP-Context': `orgId=${options.orgId}` } : {}),\n ...(options.body !== undefined ? { 'content-type': 'application/json' } : {}),\n },\n body: options.body === undefined ? undefined : JSON.stringify(options.body),\n });\n const raw = await response.text();\n if (!response.ok) {\n throw new AdportError('PROVIDER_ERROR', formatAppleError(response.status, raw), safeJson(raw));\n }\n return (raw ? JSON.parse(raw) : { data: undefined }) as AppleEnvelope<T>;\n }\n}\n\nfunction safeJson(raw: string): unknown {\n try {\n return JSON.parse(raw);\n } catch {\n return raw;\n }\n}\n\n/** v5 error shape: {\"error\": {\"errors\": [{\"messageCode\", \"message\", \"field\"}]}} */\nexport function formatAppleError(status: number, raw: string): string {\n const parsed = safeJson(raw) as {\n error?: { errors?: Array<{ messageCode?: string; message?: string; field?: string }> };\n };\n const items = parsed?.error?.errors ?? [];\n const head = `Apple Ads API error (HTTP ${status})`;\n if (items.length === 0) return head;\n const lines = items.map(\n (e) => `${e.messageCode ?? '?'}: ${e.message ?? ''}${e.field && e.field !== 'null' ? ` (field: ${e.field})` : ''}`,\n );\n const hint = status === 401 ? '\\n Token or org access problem — check credentials and org roles.' : '';\n return `${head}\\n ${lines.join('\\n ')}${hint}`;\n}\n","import { createPrivateKey, sign } from 'node:crypto';\n\nexport interface ClientSecretInput {\n /** SEARCHADS.<uuid> */\n clientId: string;\n /** SEARCHADS.<uuid> — equals clientId for self-managed orgs. */\n teamId: string;\n /** keyId of the public key uploaded in the Apple Ads UI. */\n keyId: string;\n /** EC prime256v1 private key, PEM (.p8 contents). */\n privateKeyPem: string;\n /** Secret lifetime in seconds; Apple caps exp at iat + 180 days. */\n lifetimeSeconds?: number;\n}\n\nfunction b64url(data: Buffer | string): string {\n return Buffer.from(data).toString('base64url');\n}\n\n/**\n * Apple Ads client secret: a self-signed ES256 JWT (header {alg, kid}; claims\n * iss=teamId, sub=clientId, aud=https://appleid.apple.com, iat, exp≤iat+180d).\n * We mint a short-lived secret per token request instead of storing one.\n */\nexport function createClientSecret(input: ClientSecretInput, now = new Date()): string {\n const iat = Math.floor(now.getTime() / 1000);\n const lifetime = Math.min(input.lifetimeSeconds ?? 3600, 180 * 86_400 - 60);\n const header = { alg: 'ES256', kid: input.keyId };\n const payload = {\n iss: input.teamId,\n iat,\n exp: iat + lifetime,\n aud: 'https://appleid.apple.com',\n sub: input.clientId,\n };\n const signingInput = `${b64url(JSON.stringify(header))}.${b64url(JSON.stringify(payload))}`;\n const key = createPrivateKey(input.privateKeyPem);\n // JWS ES256 requires the raw r||s signature form, not ASN.1/DER.\n const signature = sign('sha256', Buffer.from(signingInput), { key, dsaEncoding: 'ieee-p1363' });\n return `${signingInput}.${b64url(signature)}`;\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 { AppleAdsClient } from './client.js';\n\n/** Apple Money amounts are strings in whole currency units. */\nexport const UNITS_TO_MICROS = 1_000_000;\n\ninterface Money {\n amount: string;\n currency: string;\n}\n\ninterface AppleCampaign {\n id: number;\n name: string;\n status: 'ENABLED' | 'PAUSED';\n servingStatus?: string;\n displayStatus?: string;\n dailyBudgetAmount?: Money;\n adamId?: number;\n countriesOrRegions?: string[];\n billingEvent?: string;\n supplySources?: string[];\n}\n\ninterface SpendRow {\n impressions?: number;\n taps?: number;\n ttr?: number;\n totalInstalls?: number;\n localSpend?: Money;\n tapInstallCPI?: Money;\n tapInstallRate?: number;\n}\n\ninterface ReportingRow {\n other?: boolean;\n total?: SpendRow;\n metadata?: { campaignId?: number; campaignName?: string; campaignStatus?: 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 AppleAdsProvider implements AdProvider {\n readonly id = 'apple';\n\n constructor(private readonly client: AppleAdsClient) {}\n\n capabilities(): ProviderCapabilities {\n // No validate-only mode in the Campaign Management API — client-side previews.\n return { serverDryRun: false };\n }\n\n standardActions(): StandardActions {\n return {\n pauseCampaign: (accountId, campaignId) => ({\n tool: 'apple_set_campaign_status',\n input: { account_id: accountId, campaign_id: campaignId, status: 'PAUSED' },\n }),\n };\n }\n\n /** Apple \"accounts\" are organizations from the user ACL. */\n async listAccounts(): Promise<Account[]> {\n const envelope = await this.client.request<\n Array<{ orgId: number; orgName: string; currency?: string; roleNames?: string[]; timeZone?: string }>\n >('GET', 'acls');\n return (envelope.data ?? []).map((acl) => ({\n provider: this.id,\n id: String(acl.orgId),\n name: acl.orgName,\n currency: acl.currency,\n status: acl.roleNames?.join(',') || undefined,\n }));\n }\n\n async listCampaigns(orgId: string, limit = 100): Promise<AppleCampaign[]> {\n const envelope = await this.client.request<AppleCampaign[]>('GET', `campaigns?limit=${limit}&offset=0`, {\n orgId,\n });\n return envelope.data ?? [];\n }\n\n async getCampaign(orgId: string, campaignId: string): Promise<AppleCampaign> {\n const envelope = await this.client.request<AppleCampaign[]>('POST', 'campaigns/find', {\n orgId,\n body: {\n conditions: [{ field: 'id', operator: 'EQUALS', values: [String(campaignId)] }],\n pagination: { offset: 0, limit: 1 },\n },\n });\n const campaign = envelope.data?.[0];\n if (!campaign) {\n throw new AdportError('PROVIDER_ERROR', `apple: campaign ${campaignId} not found in org ${orgId}`);\n }\n return campaign;\n }\n\n async report(query: NormalizedQuery): Promise<Report> {\n if (query.level !== 'campaign' && query.level !== 'account') {\n throw new AdportError('INVALID_INPUT', 'apple: report supports campaign and account levels in v0');\n }\n const range = resolveDateRange(query.dateRange);\n const accountIds = query.accountIds ?? (await this.listAccounts()).map((a) => a.id);\n const rows: ReportRow[] = [];\n for (const orgId of accountIds) {\n const envelope = await this.client.request<{ reportingDataResponse?: { row?: ReportingRow[] } }>(\n 'POST',\n 'reports/campaigns',\n {\n orgId,\n body: {\n startTime: range.start,\n endTime: range.end,\n selector: {\n orderBy: [{ field: 'countryOrRegion', sortOrder: 'ASCENDING' }],\n pagination: { offset: 0, limit: Math.min(query.limit ?? 200, 1000) },\n },\n timeZone: 'UTC',\n returnRowTotals: true,\n returnGrandTotals: true,\n returnRecordsWithNoMetrics: false,\n },\n },\n );\n for (const row of envelope.data?.reportingDataResponse?.row ?? []) {\n rows.push(this.toReportRow(row, orgId, query));\n }\n }\n return { rows };\n }\n\n private toReportRow(row: ReportingRow, orgId: string, query: NormalizedQuery): ReportRow {\n const total = row.total ?? {};\n const spend = Number(total.localSpend?.amount ?? 0);\n const impressions = total.impressions ?? 0;\n // Apple has taps, not clicks; installs are the conversion event. No revenue metric exists.\n const clicks = total.taps ?? 0;\n const conversions = total.totalInstalls ?? 0;\n const all: Record<MetricName, number> = {\n spend: round2(spend),\n impressions,\n clicks,\n conversions,\n conversion_value: 0,\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: 0,\n };\n return {\n provider: this.id,\n accountId: orgId,\n entity: {\n level: 'campaign',\n id: String(row.metadata?.campaignId ?? ''),\n name: row.metadata?.campaignName ?? '',\n status: row.metadata?.campaignStatus,\n },\n metrics: Object.fromEntries(query.metrics.map((m) => [m, all[m]])),\n };\n }\n\n async previewWrite(op: WriteOperation, guard: WriteGuard): Promise<WritePreview> {\n const plan = await this.plan(op, guard);\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 'apple_create_campaign':\n return this.planCreateCampaign(op.accountId, payload, guard);\n case 'apple_set_campaign_status':\n return this.planSetStatus(op.accountId, payload);\n case 'apple_set_budget':\n return this.planSetBudget(op.accountId, payload);\n default:\n throw new AdportError('PROVIDER_ERROR', `apple: unsupported write tool ${op.tool}`);\n }\n }\n\n private async planCreateCampaign(\n orgId: string,\n payload: {\n name: string;\n adam_id: number;\n countries_or_regions: string[];\n daily_budget: number;\n currency: string;\n status?: string;\n },\n guard: WriteGuard,\n ): Promise<WritePlan> {\n const coercions: string[] = [];\n let status = payload.status ?? 'ENABLED';\n if (guard.forcePausedCreation && status === 'ENABLED') {\n status = 'PAUSED';\n coercions.push('status coerced to PAUSED by policy (paused_creation)');\n }\n // budgetAmount (lifetime) was removed in v5.6 — dailyBudgetAmount only.\n const body = {\n orgId: Number(orgId),\n name: payload.name,\n adamId: payload.adam_id,\n countriesOrRegions: payload.countries_or_regions,\n dailyBudgetAmount: { amount: String(payload.daily_budget), currency: payload.currency },\n adChannelType: 'SEARCH',\n billingEvent: 'TAPS',\n supplySources: ['APPSTORE_SEARCH_RESULTS'],\n status,\n };\n return {\n summary: `Create Apple Ads campaign \"${payload.name}\" (${status}) — daily budget ${payload.daily_budget} ${payload.currency}`,\n changes: [\n `+ campaign \"${payload.name}\" app=${payload.adam_id} regions=[${payload.countries_or_regions.join(', ')}] status=${status}`,\n ],\n coercions,\n budgetDeltas: [\n { target: `new campaign \"${payload.name}\" daily budget`, toMicros: payload.daily_budget * UNITS_TO_MICROS },\n ],\n execute: async () => {\n const envelope = await this.client.request<AppleCampaign>('POST', 'campaigns', { orgId, body });\n return envelope.data?.id ? [String(envelope.data.id)] : [];\n },\n };\n }\n\n private async planSetStatus(\n orgId: string,\n payload: { campaign_id: string; status: 'ENABLED' | 'PAUSED' },\n ): Promise<WritePlan> {\n const current = await this.getCampaign(orgId, payload.campaign_id);\n return {\n summary: `Set Apple campaign \"${current.name}\" status ${current.status} → ${payload.status}`,\n changes: [`~ campaign ${payload.campaign_id} status ${current.status} → ${payload.status}`],\n coercions: [],\n budgetDeltas: [],\n execute: async () => {\n await this.client.request('PUT', `campaigns/${payload.campaign_id}`, {\n orgId,\n body: { campaign: { status: payload.status } },\n });\n return [payload.campaign_id];\n },\n };\n }\n\n private async planSetBudget(\n orgId: string,\n payload: { campaign_id: string; daily_budget: number },\n ): Promise<WritePlan> {\n const current = await this.getCampaign(orgId, payload.campaign_id);\n const fromAmount = current.dailyBudgetAmount ? Number(current.dailyBudgetAmount.amount) : undefined;\n const currency = current.dailyBudgetAmount?.currency ?? 'USD';\n return {\n summary: `Change Apple campaign \"${current.name}\" daily budget ${fromAmount ?? '(unset)'} → ${payload.daily_budget} ${currency}`,\n changes: [`~ campaign ${payload.campaign_id} dailyBudgetAmount ${fromAmount ?? '(unset)'} → ${payload.daily_budget}`],\n coercions: [],\n budgetDeltas: [\n {\n target: `campaign \"${current.name}\" daily budget`,\n ...(fromAmount !== undefined ? { fromMicros: fromAmount * UNITS_TO_MICROS } : {}),\n toMicros: payload.daily_budget * UNITS_TO_MICROS,\n },\n ],\n execute: async () => {\n await this.client.request('PUT', `campaigns/${payload.campaign_id}`, {\n orgId,\n body: { campaign: { dailyBudgetAmount: { amount: String(payload.daily_budget), currency } } },\n });\n return [payload.campaign_id];\n },\n };\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 { AppleAdsProvider } from './provider.js';\n\nconst statusSchema = z.enum(['ENABLED', 'PAUSED']);\n\nexport function appleTools(provider: AppleAdsProvider): AnyToolDefinition[] {\n return [\n defineTool({\n name: 'apple_campaigns',\n namespace: 'apple',\n description:\n 'List Apple Ads campaigns for an organization (id, name, status, servingStatus, dailyBudgetAmount as string Money).',\n input: z.object({\n account_id: z.string().describe('Apple Ads organization id (orgId)'),\n limit: z.number().int().positive().max(1000).default(100),\n }),\n annotations: { readOnly: true },\n async handler(input) {\n const campaigns = await provider.listCampaigns(input.account_id, input.limit);\n return { campaigns };\n },\n }),\n guardedWriteTool({\n name: 'apple_create_campaign',\n namespace: 'apple',\n description:\n 'Create an Apple Ads search campaign (App Store search results, TAPS billing). ' +\n 'daily_budget is a float in whole currency units; adam_id is the App Store app id. ' +\n 'Apple has no dry run — previews are client-side diffs.',\n provider: 'apple',\n kind: 'create',\n payload: z.object({\n name: z.string().min(1),\n adam_id: z.number().int().positive().describe('App Store app id (adamId)'),\n countries_or_regions: z.array(z.string().length(2)).min(1),\n daily_budget: z.number().positive(),\n currency: z.string().length(3).describe('Org currency, e.g. USD/EUR'),\n status: statusSchema.optional(),\n }),\n }),\n guardedWriteTool({\n name: 'apple_set_campaign_status',\n namespace: 'apple',\n description: 'Enable or pause an Apple Ads campaign.',\n provider: 'apple',\n kind: 'update',\n payload: z.object({ campaign_id: z.string(), status: statusSchema }),\n }),\n guardedWriteTool({\n name: 'apple_set_budget',\n namespace: 'apple',\n description: \"Change an Apple Ads campaign's daily budget (float, whole currency units).\",\n provider: 'apple',\n kind: 'update',\n payload: z.object({ campaign_id: z.string(), daily_budget: z.number().positive() }),\n }),\n ];\n}\n","import type { CredentialStore, ProviderModule } from '@adport/core';\nimport { AppleAdsClient, type AppleCredentials } from './client.js';\nimport { AppleAdsProvider } from './provider.js';\nimport { appleTools } from './tools.js';\n\nexport { AppleAdsClient, APPLE_ADS_BASE, formatAppleError, type AppleCredentials, type AppleEnvelope } from './client.js';\nexport { createClientSecret, type ClientSecretInput } from './jwt.js';\nexport { AppleAdsProvider, UNITS_TO_MICROS } from './provider.js';\nexport { appleTools } from './tools.js';\n\nexport async function resolveAppleCredentials(store: CredentialStore): Promise<AppleCredentials | undefined> {\n const record = await store.get('apple');\n if (record?.data.client_id && record.data.team_id && record.data.key_id && record.data.private_key) {\n return {\n clientId: record.data.client_id,\n teamId: record.data.team_id,\n keyId: record.data.key_id,\n privateKeyPem: record.data.private_key,\n };\n }\n const env = process.env;\n if (env.APPLE_ADS_CLIENT_ID && env.APPLE_ADS_TEAM_ID && env.APPLE_ADS_KEY_ID && env.APPLE_ADS_PRIVATE_KEY) {\n return {\n clientId: env.APPLE_ADS_CLIENT_ID,\n teamId: env.APPLE_ADS_TEAM_ID,\n keyId: env.APPLE_ADS_KEY_ID,\n privateKeyPem: env.APPLE_ADS_PRIVATE_KEY,\n };\n }\n return undefined;\n}\n\nexport async function createAppleModule(store: CredentialStore): Promise<ProviderModule | undefined> {\n const credentials = await resolveAppleCredentials(store);\n if (!credentials) return undefined;\n const provider = new AppleAdsProvider(new AppleAdsClient(credentials));\n return { provider, tools: appleTools(provider) };\n}\n"],"mappings":";AAAA,SAAS,mBAAmB;;;ACA5B,SAAS,kBAAkB,YAAY;AAevC,SAAS,OAAO,MAA+B;AAC7C,SAAO,OAAO,KAAK,IAAI,EAAE,SAAS,WAAW;AAC/C;AAOO,SAAS,mBAAmB,OAA0B,MAAM,oBAAI,KAAK,GAAW;AACrF,QAAM,MAAM,KAAK,MAAM,IAAI,QAAQ,IAAI,GAAI;AAC3C,QAAM,WAAW,KAAK,IAAI,MAAM,mBAAmB,MAAM,MAAM,QAAS,EAAE;AAC1E,QAAM,SAAS,EAAE,KAAK,SAAS,KAAK,MAAM,MAAM;AAChD,QAAM,UAAU;AAAA,IACd,KAAK,MAAM;AAAA,IACX;AAAA,IACA,KAAK,MAAM;AAAA,IACX,KAAK;AAAA,IACL,KAAK,MAAM;AAAA,EACb;AACA,QAAM,eAAe,GAAG,OAAO,KAAK,UAAU,MAAM,CAAC,CAAC,IAAI,OAAO,KAAK,UAAU,OAAO,CAAC,CAAC;AACzF,QAAM,MAAM,iBAAiB,MAAM,aAAa;AAEhD,Q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AACT;AAEA,eAAsB,kBAAkB,OAA6D;AACnG,QAAM,cAAc,MAAM,wBAAwB,KAAK;AACvD,MAAI,CAAC,YAAa,QAAO;AACzB,QAAM,WAAW,IAAI,iBAAiB,IAAI,eAAe,WAAW,CAAC;AACrE,SAAO,EAAE,UAAU,OAAO,WAAW,QAAQ,EAAE;AACjD;","names":["AdportError"]}
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@adport/provider-apple",
3
+ "version": "0.1.0",
4
+ "description": "Apple Ads (Apple Search Ads) provider for adport — Campaign Management API with ES256 OAuth",
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
+ }