@adport/provider-spotify 0.6.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 +130 -0
- package/dist/index.js +431 -0
- package/dist/index.js.map +1 -0
- package/package.json +33 -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,130 @@
|
|
|
1
|
+
import { AdProvider, StandardActions, Account, NormalizedQuery, Report, WriteOperation, WriteGuard, WritePreview, WriteResult, AnyToolDefinition, CredentialStore, ProviderModule } from '@adport/core';
|
|
2
|
+
import * as node_url from 'node:url';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
|
|
5
|
+
declare const SPOTIFY_API_BASE = "https://api-partner.spotify.com/ads/v3/";
|
|
6
|
+
declare const SPOTIFY_TOKEN_URL = "https://accounts.spotify.com/api/token";
|
|
7
|
+
interface SpotifyCredentials {
|
|
8
|
+
clientId: string;
|
|
9
|
+
clientSecret: string;
|
|
10
|
+
refreshToken: string;
|
|
11
|
+
onRefreshToken?: (refreshToken: string) => Promise<void>;
|
|
12
|
+
}
|
|
13
|
+
declare function buildSpotifyAuthUrl(clientId: string, redirectUri: string, state: string): string;
|
|
14
|
+
declare function exchangeSpotifyCode(input: {
|
|
15
|
+
clientId: string;
|
|
16
|
+
clientSecret: string;
|
|
17
|
+
code: string;
|
|
18
|
+
redirectUri: string;
|
|
19
|
+
}, fetchImpl?: typeof fetch): Promise<string>;
|
|
20
|
+
declare class SpotifyAdsClient {
|
|
21
|
+
private readonly credentials;
|
|
22
|
+
private readonly fetchImpl;
|
|
23
|
+
private token?;
|
|
24
|
+
private refreshToken;
|
|
25
|
+
private refreshing?;
|
|
26
|
+
constructor(credentials: SpotifyCredentials, fetchImpl?: typeof fetch);
|
|
27
|
+
get<T>(path: string, schema: z.ZodType<T>, params?: node_url.URLSearchParams): Promise<T>;
|
|
28
|
+
mutate<T>(path: string, method: 'POST' | 'PATCH', body: unknown, schema: z.ZodType<T>): Promise<T>;
|
|
29
|
+
private request;
|
|
30
|
+
private accessToken;
|
|
31
|
+
private refresh;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
declare class SpotifyAdsProvider implements AdProvider {
|
|
35
|
+
private readonly client;
|
|
36
|
+
readonly id = "spotify";
|
|
37
|
+
constructor(client: SpotifyAdsClient);
|
|
38
|
+
capabilities(): {
|
|
39
|
+
serverDryRun: boolean;
|
|
40
|
+
};
|
|
41
|
+
standardActions(): StandardActions;
|
|
42
|
+
listAccounts(): Promise<Account[]>;
|
|
43
|
+
listCampaigns(accountId: string): Promise<{
|
|
44
|
+
[x: string]: unknown;
|
|
45
|
+
id: string;
|
|
46
|
+
name: string;
|
|
47
|
+
status: string;
|
|
48
|
+
}[]>;
|
|
49
|
+
getAdSet(accountId: string, adSetId: string): Promise<{
|
|
50
|
+
[x: string]: unknown;
|
|
51
|
+
id: string;
|
|
52
|
+
campaign_id: string;
|
|
53
|
+
name: string;
|
|
54
|
+
budget: {
|
|
55
|
+
micro_amount: number;
|
|
56
|
+
type: "DAILY" | "LIFETIME";
|
|
57
|
+
};
|
|
58
|
+
delivery: "ON" | "OFF";
|
|
59
|
+
}>;
|
|
60
|
+
report(query: NormalizedQuery): Promise<Report>;
|
|
61
|
+
previewWrite(op: WriteOperation, guard: WriteGuard): Promise<WritePreview>;
|
|
62
|
+
applyWrite(op: WriteOperation, guard: WriteGuard): Promise<WriteResult>;
|
|
63
|
+
private plan;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
declare function spotifyTools(provider: SpotifyAdsProvider): AnyToolDefinition[];
|
|
67
|
+
|
|
68
|
+
declare const accountSchema: z.ZodObject<{
|
|
69
|
+
id: z.ZodUUID;
|
|
70
|
+
name: z.ZodString;
|
|
71
|
+
currency_code: z.ZodString;
|
|
72
|
+
status: z.ZodString;
|
|
73
|
+
business_id: z.ZodOptional<z.ZodUUID>;
|
|
74
|
+
test_account_type: z.ZodOptional<z.ZodString>;
|
|
75
|
+
}, z.core.$loose>;
|
|
76
|
+
declare const campaignSchema: z.ZodObject<{
|
|
77
|
+
id: z.ZodUUID;
|
|
78
|
+
name: z.ZodString;
|
|
79
|
+
status: z.ZodString;
|
|
80
|
+
}, z.core.$loose>;
|
|
81
|
+
declare const draftSchema: z.ZodObject<{
|
|
82
|
+
id: z.ZodUUID;
|
|
83
|
+
name: z.ZodString;
|
|
84
|
+
status: z.ZodString;
|
|
85
|
+
ad_account_id: z.ZodUUID;
|
|
86
|
+
}, z.core.$loose>;
|
|
87
|
+
declare const adSetSchema: z.ZodObject<{
|
|
88
|
+
id: z.ZodUUID;
|
|
89
|
+
campaign_id: z.ZodUUID;
|
|
90
|
+
name: z.ZodString;
|
|
91
|
+
budget: z.ZodObject<{
|
|
92
|
+
micro_amount: z.ZodNumber;
|
|
93
|
+
type: z.ZodEnum<{
|
|
94
|
+
DAILY: "DAILY";
|
|
95
|
+
LIFETIME: "LIFETIME";
|
|
96
|
+
}>;
|
|
97
|
+
}, z.core.$strip>;
|
|
98
|
+
delivery: z.ZodEnum<{
|
|
99
|
+
ON: "ON";
|
|
100
|
+
OFF: "OFF";
|
|
101
|
+
}>;
|
|
102
|
+
}, z.core.$loose>;
|
|
103
|
+
declare const reportSchema: z.ZodObject<{
|
|
104
|
+
continuation_token: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
105
|
+
granularity: z.ZodEnum<{
|
|
106
|
+
LIFETIME: "LIFETIME";
|
|
107
|
+
DAY: "DAY";
|
|
108
|
+
HOUR: "HOUR";
|
|
109
|
+
}>;
|
|
110
|
+
rows: z.ZodArray<z.ZodObject<{
|
|
111
|
+
entity_type: z.ZodEnum<{
|
|
112
|
+
AD_ACCOUNT: "AD_ACCOUNT";
|
|
113
|
+
CAMPAIGN: "CAMPAIGN";
|
|
114
|
+
AD_SET: "AD_SET";
|
|
115
|
+
AD: "AD";
|
|
116
|
+
}>;
|
|
117
|
+
entity_id: z.ZodUUID;
|
|
118
|
+
entity_name: z.ZodString;
|
|
119
|
+
entity_status: z.ZodString;
|
|
120
|
+
stats: z.ZodArray<z.ZodObject<{
|
|
121
|
+
field_type: z.ZodString;
|
|
122
|
+
field_value: z.ZodNumber;
|
|
123
|
+
}, z.core.$strip>>;
|
|
124
|
+
}, z.core.$loose>>;
|
|
125
|
+
}, z.core.$loose>;
|
|
126
|
+
|
|
127
|
+
declare function resolveSpotifyCredentials(store: CredentialStore): Promise<SpotifyCredentials | undefined>;
|
|
128
|
+
declare function createSpotifyModule(store: CredentialStore): Promise<ProviderModule | undefined>;
|
|
129
|
+
|
|
130
|
+
export { SPOTIFY_API_BASE, SPOTIFY_TOKEN_URL, SpotifyAdsClient, SpotifyAdsProvider, type SpotifyCredentials, accountSchema, adSetSchema, buildSpotifyAuthUrl, campaignSchema, createSpotifyModule, draftSchema, exchangeSpotifyCode, reportSchema, resolveSpotifyCredentials, spotifyTools };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,431 @@
|
|
|
1
|
+
// src/client.ts
|
|
2
|
+
import { AdportError } from "@adport/core";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
var SPOTIFY_API_BASE = "https://api-partner.spotify.com/ads/v3/";
|
|
5
|
+
var SPOTIFY_TOKEN_URL = "https://accounts.spotify.com/api/token";
|
|
6
|
+
var tokenSchema = z.object({
|
|
7
|
+
access_token: z.string().min(1),
|
|
8
|
+
expires_in: z.number().positive(),
|
|
9
|
+
refresh_token: z.string().min(1).optional()
|
|
10
|
+
});
|
|
11
|
+
function buildSpotifyAuthUrl(clientId, redirectUri, state) {
|
|
12
|
+
return `https://accounts.spotify.com/authorize/?${new URLSearchParams({
|
|
13
|
+
client_id: clientId,
|
|
14
|
+
response_type: "code",
|
|
15
|
+
redirect_uri: redirectUri,
|
|
16
|
+
state
|
|
17
|
+
})}`;
|
|
18
|
+
}
|
|
19
|
+
async function tokenRequest(credentials, body, fetchImpl) {
|
|
20
|
+
const response = await fetchImpl(SPOTIFY_TOKEN_URL, {
|
|
21
|
+
method: "POST",
|
|
22
|
+
headers: {
|
|
23
|
+
authorization: `Basic ${Buffer.from(`${credentials.clientId}:${credentials.clientSecret}`).toString("base64")}`,
|
|
24
|
+
"content-type": "application/x-www-form-urlencoded"
|
|
25
|
+
},
|
|
26
|
+
body,
|
|
27
|
+
redirect: "error",
|
|
28
|
+
signal: AbortSignal.timeout(3e4)
|
|
29
|
+
});
|
|
30
|
+
if (!response.ok) throw new AdportError("PROVIDER_ERROR", `spotify: OAuth ${body.get("grant_type")} failed (HTTP ${response.status})`);
|
|
31
|
+
const parsed = tokenSchema.safeParse(await response.json());
|
|
32
|
+
if (!parsed.success) throw new AdportError("PROVIDER_ERROR", "spotify: malformed OAuth response");
|
|
33
|
+
return parsed.data;
|
|
34
|
+
}
|
|
35
|
+
async function exchangeSpotifyCode(input, fetchImpl = fetch) {
|
|
36
|
+
const token = await tokenRequest(input, new URLSearchParams({ grant_type: "authorization_code", code: input.code, redirect_uri: input.redirectUri }), fetchImpl);
|
|
37
|
+
if (!token.refresh_token) throw new AdportError("PROVIDER_ERROR", "spotify: OAuth exchange did not return a refresh token");
|
|
38
|
+
return token.refresh_token;
|
|
39
|
+
}
|
|
40
|
+
var SpotifyAdsClient = class {
|
|
41
|
+
constructor(credentials, fetchImpl = fetch) {
|
|
42
|
+
this.credentials = credentials;
|
|
43
|
+
this.fetchImpl = fetchImpl;
|
|
44
|
+
this.refreshToken = credentials.refreshToken;
|
|
45
|
+
}
|
|
46
|
+
credentials;
|
|
47
|
+
fetchImpl;
|
|
48
|
+
token;
|
|
49
|
+
refreshToken;
|
|
50
|
+
refreshing;
|
|
51
|
+
async get(path, schema, params = new URLSearchParams()) {
|
|
52
|
+
return this.request(path, "GET", schema, void 0, params);
|
|
53
|
+
}
|
|
54
|
+
async mutate(path, method, body, schema) {
|
|
55
|
+
return this.request(path, method, schema, body);
|
|
56
|
+
}
|
|
57
|
+
async request(path, method, schema, body, params = new URLSearchParams(), retry = true) {
|
|
58
|
+
if (!/^[a-z_]+(?:\/[a-zA-Z0-9_-]+)*$/.test(path)) throw new AdportError("INVALID_INPUT", "spotify: invalid API resource path");
|
|
59
|
+
const url = new URL(path, SPOTIFY_API_BASE);
|
|
60
|
+
url.search = params.toString();
|
|
61
|
+
const token = await this.accessToken();
|
|
62
|
+
const response = await this.fetchImpl(url.href, {
|
|
63
|
+
method,
|
|
64
|
+
headers: { authorization: `Bearer ${token}`, ...body !== void 0 ? { "content-type": "application/json" } : {} },
|
|
65
|
+
...body !== void 0 ? { body: JSON.stringify(body) } : {},
|
|
66
|
+
redirect: "error",
|
|
67
|
+
signal: AbortSignal.timeout(3e4)
|
|
68
|
+
});
|
|
69
|
+
if (response.status === 401 && method === "GET" && retry) {
|
|
70
|
+
if (this.token?.value === token) this.token = void 0;
|
|
71
|
+
return this.request(path, method, schema, body, params, false);
|
|
72
|
+
}
|
|
73
|
+
if (!response.ok) {
|
|
74
|
+
const advice = response.status === 403 ? " Check Ads API terms/allowlisting and ad-account permissions; reauthorization alone may not help." : "";
|
|
75
|
+
throw new AdportError("PROVIDER_ERROR", `spotify: HTTP ${response.status}.${advice}`);
|
|
76
|
+
}
|
|
77
|
+
const parsed = schema.safeParse(await response.json());
|
|
78
|
+
if (!parsed.success) throw new AdportError("PROVIDER_ERROR", "spotify: malformed API response");
|
|
79
|
+
return parsed.data;
|
|
80
|
+
}
|
|
81
|
+
async accessToken() {
|
|
82
|
+
if (this.token && this.token.expiresAt > Date.now() + 6e4) return this.token.value;
|
|
83
|
+
if (!this.refreshing) this.refreshing = this.refresh().finally(() => {
|
|
84
|
+
this.refreshing = void 0;
|
|
85
|
+
});
|
|
86
|
+
return this.refreshing;
|
|
87
|
+
}
|
|
88
|
+
async refresh() {
|
|
89
|
+
const token = await tokenRequest(this.credentials, new URLSearchParams({ grant_type: "refresh_token", refresh_token: this.refreshToken }), this.fetchImpl);
|
|
90
|
+
if (token.refresh_token && token.refresh_token !== this.refreshToken) {
|
|
91
|
+
this.refreshToken = token.refresh_token;
|
|
92
|
+
await this.credentials.onRefreshToken?.(token.refresh_token);
|
|
93
|
+
}
|
|
94
|
+
this.token = { value: token.access_token, expiresAt: Date.now() + token.expires_in * 1e3 };
|
|
95
|
+
return token.access_token;
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
// src/provider.ts
|
|
100
|
+
import { z as z3 } from "zod";
|
|
101
|
+
import {
|
|
102
|
+
AdportError as AdportError2,
|
|
103
|
+
resolveDateRange
|
|
104
|
+
} from "@adport/core";
|
|
105
|
+
|
|
106
|
+
// src/schemas.ts
|
|
107
|
+
import { z as z2 } from "zod";
|
|
108
|
+
var spotifyId = z2.uuid();
|
|
109
|
+
var businessSchema = z2.looseObject({ id: spotifyId, name: z2.string() });
|
|
110
|
+
var accountSchema = z2.looseObject({
|
|
111
|
+
id: spotifyId,
|
|
112
|
+
name: z2.string(),
|
|
113
|
+
currency_code: z2.string(),
|
|
114
|
+
status: z2.string(),
|
|
115
|
+
business_id: spotifyId.optional(),
|
|
116
|
+
test_account_type: z2.string().optional()
|
|
117
|
+
});
|
|
118
|
+
var campaignSchema = z2.looseObject({ id: spotifyId, name: z2.string(), status: z2.string() });
|
|
119
|
+
var draftSchema = campaignSchema.extend({ ad_account_id: spotifyId });
|
|
120
|
+
var budgetSchema = z2.object({ micro_amount: z2.number().int().nonnegative().safe(), type: z2.enum(["DAILY", "LIFETIME"]) });
|
|
121
|
+
var adSetSchema = z2.looseObject({
|
|
122
|
+
id: spotifyId,
|
|
123
|
+
campaign_id: spotifyId,
|
|
124
|
+
name: z2.string(),
|
|
125
|
+
budget: budgetSchema,
|
|
126
|
+
delivery: z2.enum(["ON", "OFF"])
|
|
127
|
+
});
|
|
128
|
+
var pagingSchema = z2.object({
|
|
129
|
+
page_size: z2.number().int().nonnegative(),
|
|
130
|
+
total_results: z2.number().int().nonnegative(),
|
|
131
|
+
offset: z2.number().int().nonnegative(),
|
|
132
|
+
current_page: z2.number().int().nonnegative()
|
|
133
|
+
});
|
|
134
|
+
var reportRowSchema = z2.looseObject({
|
|
135
|
+
entity_type: z2.enum(["AD_ACCOUNT", "CAMPAIGN", "AD_SET", "AD"]),
|
|
136
|
+
entity_id: spotifyId,
|
|
137
|
+
entity_name: z2.string(),
|
|
138
|
+
entity_status: z2.string(),
|
|
139
|
+
stats: z2.array(z2.object({ field_type: z2.string(), field_value: z2.number() }))
|
|
140
|
+
});
|
|
141
|
+
var reportSchema = z2.looseObject({
|
|
142
|
+
continuation_token: z2.string().nullable().optional(),
|
|
143
|
+
granularity: z2.enum(["LIFETIME", "DAY", "HOUR"]),
|
|
144
|
+
rows: z2.array(reportRowSchema)
|
|
145
|
+
});
|
|
146
|
+
var createDraftSchema = z2.object({
|
|
147
|
+
name: z2.string().trim().min(2).max(200),
|
|
148
|
+
purchase_order: z2.string().min(2).max(45).optional(),
|
|
149
|
+
delivery_goal_group: z2.enum(["AWARENESS", "WEBSITE_TRAFFIC", "APP_PROMOTION", "ENGAGEMENT_ON_SPOTIFY", "LEAD_GEN", "VIDEO_VIEWS"]),
|
|
150
|
+
status: z2.enum(["PAUSED", "ACTIVE"]).default("PAUSED")
|
|
151
|
+
});
|
|
152
|
+
var setStatusSchema = z2.object({ campaign_id: spotifyId, status: z2.enum(["PAUSED", "ACTIVE"]) });
|
|
153
|
+
var setBudgetSchema = z2.object({ ad_set_id: spotifyId, budget_micros: z2.number().int().positive().safe() });
|
|
154
|
+
var setDeliverySchema = z2.object({ ad_set_id: spotifyId, delivery: z2.enum(["OFF", "ON"]) });
|
|
155
|
+
|
|
156
|
+
// src/provider.ts
|
|
157
|
+
var LEVEL = { account: "AD_ACCOUNT", campaign: "CAMPAIGN", ad_group: "AD_SET", ad: "AD" };
|
|
158
|
+
var FIELDS = { spend: "SPEND", impressions: "IMPRESSIONS", clicks: "CLICKS", conversions: "PURCHASES", conversion_value: "REVENUE" };
|
|
159
|
+
var DERIVED = {
|
|
160
|
+
ctr: ["clicks", "impressions", 100],
|
|
161
|
+
cpc: ["spend", "clicks", 1],
|
|
162
|
+
cpm: ["spend", "impressions", 1e3],
|
|
163
|
+
cpa: ["spend", "conversions", 1],
|
|
164
|
+
roas: ["conversion_value", "spend", 1]
|
|
165
|
+
};
|
|
166
|
+
var SpotifyAdsProvider = class {
|
|
167
|
+
constructor(client) {
|
|
168
|
+
this.client = client;
|
|
169
|
+
}
|
|
170
|
+
client;
|
|
171
|
+
id = "spotify";
|
|
172
|
+
capabilities() {
|
|
173
|
+
return { serverDryRun: false };
|
|
174
|
+
}
|
|
175
|
+
standardActions() {
|
|
176
|
+
return { pauseCampaign: (accountId, campaignId) => ({ tool: "spotify_set_campaign_status", input: { account_id: accountId, campaign_id: campaignId, status: "PAUSED" } }) };
|
|
177
|
+
}
|
|
178
|
+
async listAccounts() {
|
|
179
|
+
const { businesses } = await this.client.get("businesses", z3.object({ businesses: z3.array(businessSchema) }));
|
|
180
|
+
const accounts = /* @__PURE__ */ new Map();
|
|
181
|
+
for (const business of businesses) {
|
|
182
|
+
const { ad_accounts } = await this.client.get(`businesses/${business.id}/ad_accounts`, z3.object({ ad_accounts: z3.array(accountSchema) }));
|
|
183
|
+
for (const account of ad_accounts) accounts.set(account.id, { provider: this.id, id: account.id, name: account.name, currency: account.currency_code, status: account.status });
|
|
184
|
+
}
|
|
185
|
+
return [...accounts.values()];
|
|
186
|
+
}
|
|
187
|
+
async listCampaigns(accountId) {
|
|
188
|
+
const path = `ad_accounts/${spotifyId.parse(accountId)}/campaigns`;
|
|
189
|
+
const schema = z3.object({ paging: pagingSchema, campaigns: z3.array(campaignSchema) });
|
|
190
|
+
const rows = [];
|
|
191
|
+
const seen = /* @__PURE__ */ new Set();
|
|
192
|
+
for (let page = 0, offset = 0; page < 1e3; page++) {
|
|
193
|
+
const data = await this.client.get(path, schema, new URLSearchParams({ limit: "50", offset: String(offset), sort_field: "ID", sort_direction: "ASC" }));
|
|
194
|
+
if (data.paging.offset !== offset) throw new AdportError2("PROVIDER_ERROR", "spotify: campaign pagination changed offset");
|
|
195
|
+
for (const campaign of data.campaigns) {
|
|
196
|
+
if (seen.has(campaign.id)) throw new AdportError2("PROVIDER_ERROR", "spotify: campaign pagination repeated an entity");
|
|
197
|
+
seen.add(campaign.id);
|
|
198
|
+
rows.push(campaign);
|
|
199
|
+
}
|
|
200
|
+
offset += data.campaigns.length;
|
|
201
|
+
if (offset >= data.paging.total_results) return rows;
|
|
202
|
+
if (!data.campaigns.length) break;
|
|
203
|
+
}
|
|
204
|
+
throw new AdportError2("PROVIDER_ERROR", "spotify: campaign pagination did not terminate; refusing incomplete results");
|
|
205
|
+
}
|
|
206
|
+
async getAdSet(accountId, adSetId) {
|
|
207
|
+
const data = await this.client.get(`ad_accounts/${spotifyId.parse(accountId)}/ad_sets/${spotifyId.parse(adSetId)}`, adSetSchema);
|
|
208
|
+
if (data.id !== adSetId) throw new AdportError2("PROVIDER_ERROR", "spotify: ad set response ID mismatch");
|
|
209
|
+
return data;
|
|
210
|
+
}
|
|
211
|
+
async report(query) {
|
|
212
|
+
const range = resolveDateRange(query.dateRange);
|
|
213
|
+
const start = z3.iso.date().parse(range.start), end = z3.iso.date().parse(range.end);
|
|
214
|
+
const days = (Date.parse(end) - Date.parse(start)) / 864e5;
|
|
215
|
+
if (days < 0 || days > 90) throw new AdportError2("INVALID_INPUT", "spotify: report end must be on/after start and within 90 days");
|
|
216
|
+
const limit = query.limit ?? 1e3;
|
|
217
|
+
if (!Number.isSafeInteger(limit) || limit < 1) throw new AdportError2("INVALID_INPUT", "spotify: report limit must be a positive integer");
|
|
218
|
+
const fields = /* @__PURE__ */ new Set();
|
|
219
|
+
for (const metric of query.metrics) {
|
|
220
|
+
if (metric in FIELDS) fields.add(FIELDS[metric]);
|
|
221
|
+
else if (metric in DERIVED) for (const dependency of DERIVED[metric].slice(0, 2)) fields.add(FIELDS[dependency]);
|
|
222
|
+
}
|
|
223
|
+
if (!fields.size) throw new AdportError2("INVALID_INPUT", "spotify: report requires at least one supported metric");
|
|
224
|
+
const accountIds = [...new Set(query.accountIds ?? (await this.listAccounts()).map((a) => a.id))];
|
|
225
|
+
const rows = [];
|
|
226
|
+
for (const id of accountIds) {
|
|
227
|
+
const accountId = spotifyId.parse(id);
|
|
228
|
+
let params = new URLSearchParams({ entity_type: LEVEL[query.level], report_start: `${start}T00:00:00Z`, report_end: `${end}T00:00:00Z`, granularity: "LIFETIME", limit: "50" });
|
|
229
|
+
for (const field of fields) params.append("fields", field);
|
|
230
|
+
const tokens = /* @__PURE__ */ new Set();
|
|
231
|
+
const entities = /* @__PURE__ */ new Set();
|
|
232
|
+
while (true) {
|
|
233
|
+
const data = await this.client.get(`ad_accounts/${accountId}/aggregate_reports`, reportSchema, params);
|
|
234
|
+
if (data.granularity !== "LIFETIME") throw new AdportError2("PROVIDER_ERROR", "spotify: unexpected report granularity");
|
|
235
|
+
for (const row of data.rows) {
|
|
236
|
+
if (row.entity_type !== LEVEL[query.level] || query.level === "account" && row.entity_id !== accountId || entities.has(row.entity_id)) {
|
|
237
|
+
throw new AdportError2("PROVIDER_ERROR", "spotify: incorrectly scoped or duplicate report row");
|
|
238
|
+
}
|
|
239
|
+
entities.add(row.entity_id);
|
|
240
|
+
rows.push({ provider: this.id, accountId, entity: { level: query.level, id: row.entity_id, name: row.entity_name, status: row.entity_status }, metrics: normalize(row.stats, query.metrics) });
|
|
241
|
+
if (rows.length > limit) return { rows: rows.slice(0, limit), truncated: true };
|
|
242
|
+
}
|
|
243
|
+
if (!data.continuation_token) break;
|
|
244
|
+
if (tokens.has(data.continuation_token) || tokens.size >= 1e3) throw new AdportError2("PROVIDER_ERROR", "spotify: report pagination did not terminate");
|
|
245
|
+
tokens.add(data.continuation_token);
|
|
246
|
+
params = new URLSearchParams({ continuation_token: data.continuation_token });
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
return { rows };
|
|
250
|
+
}
|
|
251
|
+
async previewWrite(op, guard) {
|
|
252
|
+
const { execute: _execute, ...preview } = await this.plan(op, guard);
|
|
253
|
+
return { ...preview, serverValidated: false };
|
|
254
|
+
}
|
|
255
|
+
async applyWrite(op, guard) {
|
|
256
|
+
return { applied: true, resourceIds: await (await this.plan(op, guard)).execute() };
|
|
257
|
+
}
|
|
258
|
+
async plan(op, guard) {
|
|
259
|
+
const accountId = spotifyId.parse(op.accountId);
|
|
260
|
+
const base = `ad_accounts/${accountId}`;
|
|
261
|
+
if (op.provider !== this.id) throw new AdportError2("INVALID_INPUT", "spotify: provider mismatch");
|
|
262
|
+
if (op.tool === "spotify_create_campaign_draft" && op.kind === "create") {
|
|
263
|
+
const input = createDraftSchema.parse(op.payload);
|
|
264
|
+
const status = guard.forcePausedCreation ? "PAUSED" : input.status;
|
|
265
|
+
const body = { ...input, status };
|
|
266
|
+
return {
|
|
267
|
+
summary: `Create Spotify campaign draft "${input.name}" (not published)`,
|
|
268
|
+
changes: [`+ ${JSON.stringify(body)}`],
|
|
269
|
+
coercions: input.status !== status ? ["status coerced to PAUSED by policy (paused_creation)"] : [],
|
|
270
|
+
budgetDeltas: [],
|
|
271
|
+
execute: async () => {
|
|
272
|
+
const result = await this.client.mutate(`${base}/drafts/campaigns`, "POST", body, draftSchema);
|
|
273
|
+
if (result.ad_account_id !== accountId || result.status !== status) throw new AdportError2("PROVIDER_ERROR", "spotify: created draft response violated account/status expectations; inspect the draft before retrying");
|
|
274
|
+
return [result.id];
|
|
275
|
+
}
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
if (op.tool === "spotify_set_campaign_status" && op.kind === "update") {
|
|
279
|
+
const input = setStatusSchema.parse(op.payload);
|
|
280
|
+
const path = `${base}/campaigns/${input.campaign_id}`;
|
|
281
|
+
const current = await this.client.get(path, campaignSchema);
|
|
282
|
+
if (current.id !== input.campaign_id) throw new AdportError2("PROVIDER_ERROR", "spotify: campaign response ID mismatch");
|
|
283
|
+
return {
|
|
284
|
+
summary: `Change Spotify campaign "${current.name}" status`,
|
|
285
|
+
changes: [`~ ${current.id} status: ${current.status} \u2192 ${input.status}`],
|
|
286
|
+
coercions: [],
|
|
287
|
+
budgetDeltas: [],
|
|
288
|
+
execute: async () => {
|
|
289
|
+
const result = await this.client.mutate(path, "PATCH", { status: input.status }, campaignSchema);
|
|
290
|
+
if (result.id !== current.id || result.status !== input.status) throw new AdportError2("PROVIDER_ERROR", "spotify: campaign update response mismatch; inspect before retrying");
|
|
291
|
+
return [result.id];
|
|
292
|
+
}
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
if (op.kind === "update" && ["spotify_set_budget", "spotify_set_ad_set_delivery"].includes(op.tool)) {
|
|
296
|
+
const input = op.tool === "spotify_set_budget" ? setBudgetSchema.parse(op.payload) : setDeliverySchema.parse(op.payload);
|
|
297
|
+
const current = await this.getAdSet(accountId, input.ad_set_id);
|
|
298
|
+
const budget = "budget_micros" in input ? { micro_amount: input.budget_micros, type: current.budget.type } : void 0;
|
|
299
|
+
const body = budget ? { budget } : { delivery: "delivery" in input ? input.delivery : current.delivery };
|
|
300
|
+
return {
|
|
301
|
+
summary: `Change Spotify ad set "${current.name}" ${budget ? "budget" : "delivery"}`,
|
|
302
|
+
changes: [budget ? `~ ${current.id} ${budget.type} budget micros: ${current.budget.micro_amount} \u2192 ${budget.micro_amount}` : `~ ${current.id} delivery: ${current.delivery} \u2192 ${body.delivery}`],
|
|
303
|
+
coercions: [],
|
|
304
|
+
budgetDeltas: budget ? [{ target: `ad set ${current.id} ${budget.type} budget`, fromMicros: current.budget.micro_amount, toMicros: budget.micro_amount }] : [],
|
|
305
|
+
execute: async () => {
|
|
306
|
+
const result = await this.client.mutate(`${base}/ad_sets/${current.id}`, "PATCH", body, adSetSchema);
|
|
307
|
+
if (result.id !== current.id || result.campaign_id !== current.campaign_id || budget && (result.budget.type !== budget.type || result.budget.micro_amount !== budget.micro_amount) || !budget && result.delivery !== body.delivery) {
|
|
308
|
+
throw new AdportError2("PROVIDER_ERROR", "spotify: ad set update response mismatch; inspect before retrying");
|
|
309
|
+
}
|
|
310
|
+
return [result.id];
|
|
311
|
+
}
|
|
312
|
+
};
|
|
313
|
+
}
|
|
314
|
+
throw new AdportError2("INVALID_INPUT", `spotify: unsupported write ${op.tool}`);
|
|
315
|
+
}
|
|
316
|
+
};
|
|
317
|
+
function normalize(stats, requested) {
|
|
318
|
+
const raw = /* @__PURE__ */ new Map();
|
|
319
|
+
for (const stat of stats) {
|
|
320
|
+
if (raw.has(stat.field_type)) throw new AdportError2("PROVIDER_ERROR", "spotify: duplicate report metric");
|
|
321
|
+
raw.set(stat.field_type, stat.field_value);
|
|
322
|
+
}
|
|
323
|
+
const mapped = {};
|
|
324
|
+
for (const [metric, field] of Object.entries(FIELDS)) {
|
|
325
|
+
const value = raw.get(field);
|
|
326
|
+
if (value !== void 0 && value >= 0) mapped[metric] = value;
|
|
327
|
+
}
|
|
328
|
+
for (const [metric, [numerator, denominator, factor]] of Object.entries(DERIVED)) {
|
|
329
|
+
if (mapped[numerator] !== void 0 && mapped[denominator] !== void 0) mapped[metric] = mapped[denominator] ? mapped[numerator] / mapped[denominator] * factor : 0;
|
|
330
|
+
}
|
|
331
|
+
return Object.fromEntries(requested.filter((metric) => mapped[metric] !== void 0).map((metric) => [metric, mapped[metric]]));
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// src/tools.ts
|
|
335
|
+
import { z as z4 } from "zod";
|
|
336
|
+
import { defineTool, guardedWriteTool } from "@adport/core";
|
|
337
|
+
function spotifyTools(provider) {
|
|
338
|
+
return [
|
|
339
|
+
defineTool({
|
|
340
|
+
name: "spotify_list_campaigns",
|
|
341
|
+
namespace: "spotify",
|
|
342
|
+
description: "List published Spotify Ads campaigns in the selected account.",
|
|
343
|
+
input: z4.object({ account_id: spotifyId }),
|
|
344
|
+
annotations: { readOnly: true },
|
|
345
|
+
handler: (input) => provider.listCampaigns(input.account_id)
|
|
346
|
+
}),
|
|
347
|
+
defineTool({
|
|
348
|
+
name: "spotify_get_ad_set",
|
|
349
|
+
namespace: "spotify",
|
|
350
|
+
description: "Read a Spotify ad set, including its budget and delivery setting.",
|
|
351
|
+
input: z4.object({ account_id: spotifyId, ad_set_id: spotifyId }),
|
|
352
|
+
annotations: { readOnly: true },
|
|
353
|
+
handler: (input) => provider.getAdSet(input.account_id, input.ad_set_id)
|
|
354
|
+
}),
|
|
355
|
+
guardedWriteTool({
|
|
356
|
+
name: "spotify_create_campaign_draft",
|
|
357
|
+
namespace: "spotify",
|
|
358
|
+
provider: "spotify",
|
|
359
|
+
kind: "create",
|
|
360
|
+
description: "Create an unpublished Spotify campaign draft, paused by policy. Does not publish or launch ads. Preview is local.",
|
|
361
|
+
payload: createDraftSchema
|
|
362
|
+
}),
|
|
363
|
+
guardedWriteTool({
|
|
364
|
+
name: "spotify_set_campaign_status",
|
|
365
|
+
namespace: "spotify",
|
|
366
|
+
provider: "spotify",
|
|
367
|
+
kind: "update",
|
|
368
|
+
description: "Pause or activate an existing Spotify Ads campaign.",
|
|
369
|
+
payload: setStatusSchema
|
|
370
|
+
}),
|
|
371
|
+
guardedWriteTool({
|
|
372
|
+
name: "spotify_set_budget",
|
|
373
|
+
namespace: "spotify",
|
|
374
|
+
provider: "spotify",
|
|
375
|
+
kind: "update",
|
|
376
|
+
description: "Change a Spotify ad-set budget in integer micros, preserving its current DAILY or LIFETIME type.",
|
|
377
|
+
payload: setBudgetSchema
|
|
378
|
+
}),
|
|
379
|
+
guardedWriteTool({
|
|
380
|
+
name: "spotify_set_ad_set_delivery",
|
|
381
|
+
namespace: "spotify",
|
|
382
|
+
provider: "spotify",
|
|
383
|
+
kind: "update",
|
|
384
|
+
description: "Turn an existing Spotify ad set delivery OFF or ON.",
|
|
385
|
+
payload: setDeliverySchema
|
|
386
|
+
})
|
|
387
|
+
];
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
// src/index.ts
|
|
391
|
+
async function resolveSpotifyCredentials(store) {
|
|
392
|
+
const data = (await store.get("spotify"))?.data;
|
|
393
|
+
if (data?.client_id && data.client_secret && data.refresh_token) return {
|
|
394
|
+
clientId: data.client_id,
|
|
395
|
+
clientSecret: data.client_secret,
|
|
396
|
+
refreshToken: data.refresh_token,
|
|
397
|
+
onRefreshToken: async (refreshToken) => {
|
|
398
|
+
const latest = await store.get("spotify");
|
|
399
|
+
if (latest) await store.set({ provider: "spotify", source: latest.source, data: { ...latest.data, refresh_token: refreshToken } });
|
|
400
|
+
}
|
|
401
|
+
};
|
|
402
|
+
if (process.env.SPOTIFY_CLIENT_ID && process.env.SPOTIFY_CLIENT_SECRET && process.env.SPOTIFY_REFRESH_TOKEN) return {
|
|
403
|
+
clientId: process.env.SPOTIFY_CLIENT_ID,
|
|
404
|
+
clientSecret: process.env.SPOTIFY_CLIENT_SECRET,
|
|
405
|
+
refreshToken: process.env.SPOTIFY_REFRESH_TOKEN
|
|
406
|
+
};
|
|
407
|
+
return void 0;
|
|
408
|
+
}
|
|
409
|
+
async function createSpotifyModule(store) {
|
|
410
|
+
const credentials = await resolveSpotifyCredentials(store);
|
|
411
|
+
if (!credentials) return void 0;
|
|
412
|
+
const provider = new SpotifyAdsProvider(new SpotifyAdsClient(credentials));
|
|
413
|
+
return { provider, tools: spotifyTools(provider) };
|
|
414
|
+
}
|
|
415
|
+
export {
|
|
416
|
+
SPOTIFY_API_BASE,
|
|
417
|
+
SPOTIFY_TOKEN_URL,
|
|
418
|
+
SpotifyAdsClient,
|
|
419
|
+
SpotifyAdsProvider,
|
|
420
|
+
accountSchema,
|
|
421
|
+
adSetSchema,
|
|
422
|
+
buildSpotifyAuthUrl,
|
|
423
|
+
campaignSchema,
|
|
424
|
+
createSpotifyModule,
|
|
425
|
+
draftSchema,
|
|
426
|
+
exchangeSpotifyCode,
|
|
427
|
+
reportSchema,
|
|
428
|
+
resolveSpotifyCredentials,
|
|
429
|
+
spotifyTools
|
|
430
|
+
};
|
|
431
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/client.ts","../src/provider.ts","../src/schemas.ts","../src/tools.ts","../src/index.ts"],"sourcesContent":["import { AdportError } from '@adport/core';\nimport { z } from 'zod';\n\nexport const SPOTIFY_API_BASE = 'https://api-partner.spotify.com/ads/v3/';\nexport const SPOTIFY_TOKEN_URL = 'https://accounts.spotify.com/api/token';\nexport interface SpotifyCredentials {\n clientId: string;\n clientSecret: string;\n refreshToken: string;\n onRefreshToken?: (refreshToken: string) => Promise<void>;\n}\nconst tokenSchema = z.object({\n access_token: z.string().min(1), expires_in: z.number().positive(),\n refresh_token: z.string().min(1).optional(),\n});\n\nexport function buildSpotifyAuthUrl(clientId: string, redirectUri: string, state: string): string {\n // Ads API access is granted to the app, not through Web API music scopes.\n return `https://accounts.spotify.com/authorize/?${new URLSearchParams({\n client_id: clientId, response_type: 'code', redirect_uri: redirectUri, state,\n })}`;\n}\n\nasync function tokenRequest(credentials: Pick<SpotifyCredentials, 'clientId' | 'clientSecret'>, body: URLSearchParams, fetchImpl: typeof fetch) {\n const response = await fetchImpl(SPOTIFY_TOKEN_URL, {\n method: 'POST', headers: {\n authorization: `Basic ${Buffer.from(`${credentials.clientId}:${credentials.clientSecret}`).toString('base64')}`,\n 'content-type': 'application/x-www-form-urlencoded',\n }, body, redirect: 'error', signal: AbortSignal.timeout(30_000),\n });\n if (!response.ok) throw new AdportError('PROVIDER_ERROR', `spotify: OAuth ${body.get('grant_type')} failed (HTTP ${response.status})`);\n const parsed = tokenSchema.safeParse(await response.json());\n if (!parsed.success) throw new AdportError('PROVIDER_ERROR', 'spotify: malformed OAuth response');\n return parsed.data;\n}\n\nexport async function exchangeSpotifyCode(input: { clientId: string; clientSecret: string; code: string; redirectUri: string }, fetchImpl: typeof fetch = fetch): Promise<string> {\n const token = await tokenRequest(input, new URLSearchParams({ grant_type: 'authorization_code', code: input.code, redirect_uri: input.redirectUri }), fetchImpl);\n if (!token.refresh_token) throw new AdportError('PROVIDER_ERROR', 'spotify: OAuth exchange did not return a refresh token');\n return token.refresh_token;\n}\n\nexport class SpotifyAdsClient {\n private token?: { value: string; expiresAt: number };\n private refreshToken: string;\n private refreshing?: Promise<string>;\n constructor(private readonly credentials: SpotifyCredentials, private readonly fetchImpl: typeof fetch = fetch) {\n this.refreshToken = credentials.refreshToken;\n }\n\n async get<T>(path: string, schema: z.ZodType<T>, params = new URLSearchParams()): Promise<T> {\n return this.request(path, 'GET', schema, undefined, params);\n }\n async mutate<T>(path: string, method: 'POST' | 'PATCH', body: unknown, schema: z.ZodType<T>): Promise<T> {\n return this.request(path, method, schema, body);\n }\n\n private async request<T>(path: string, method: 'GET' | 'POST' | 'PATCH', schema: z.ZodType<T>, body?: unknown, params = new URLSearchParams(), retry = true): Promise<T> {\n // Resource paths are built from schema-checked IDs. Reject foreign URLs,\n // absolute paths, queries and dot segments before sending any credentials.\n if (!/^[a-z_]+(?:\\/[a-zA-Z0-9_-]+)*$/.test(path)) throw new AdportError('INVALID_INPUT', 'spotify: invalid API resource path');\n const url = new URL(path, SPOTIFY_API_BASE);\n url.search = params.toString();\n const token = await this.accessToken();\n const response = await this.fetchImpl(url.href, {\n method, headers: { authorization: `Bearer ${token}`, ...(body !== undefined ? { 'content-type': 'application/json' } : {}) },\n ...(body !== undefined ? { body: JSON.stringify(body) } : {}), redirect: 'error', signal: AbortSignal.timeout(30_000),\n });\n if (response.status === 401 && method === 'GET' && retry) {\n if (this.token?.value === token) this.token = undefined;\n return this.request(path, method, schema, body, params, false);\n }\n if (!response.ok) {\n const advice = response.status === 403 ? ' Check Ads API terms/allowlisting and ad-account permissions; reauthorization alone may not help.' : '';\n throw new AdportError('PROVIDER_ERROR', `spotify: HTTP ${response.status}.${advice}`);\n }\n const parsed = schema.safeParse(await response.json());\n if (!parsed.success) throw new AdportError('PROVIDER_ERROR', 'spotify: malformed API response');\n return parsed.data;\n }\n\n private async accessToken(): Promise<string> {\n if (this.token && this.token.expiresAt > Date.now() + 60_000) return this.token.value;\n if (!this.refreshing) this.refreshing = this.refresh().finally(() => { this.refreshing = undefined; });\n return this.refreshing;\n }\n private async refresh(): Promise<string> {\n const token = await tokenRequest(this.credentials, new URLSearchParams({ grant_type: 'refresh_token', refresh_token: this.refreshToken }), this.fetchImpl);\n if (token.refresh_token && token.refresh_token !== this.refreshToken) {\n this.refreshToken = token.refresh_token;\n await this.credentials.onRefreshToken?.(token.refresh_token);\n }\n this.token = { value: token.access_token, expiresAt: Date.now() + token.expires_in * 1000 };\n return token.access_token;\n }\n}\n","import { z } from 'zod';\nimport {\n AdportError, resolveDateRange, type Account, type AdProvider, type MetricName,\n type NormalizedQuery, type Report, type ReportRow, type StandardActions,\n type WriteGuard, type WriteOperation, type WritePreview, type WriteResult,\n} from '@adport/core';\nimport { SpotifyAdsClient } from './client.js';\nimport {\n accountSchema, adSetSchema, businessSchema, campaignSchema, createDraftSchema,\n draftSchema, pagingSchema, reportSchema, setBudgetSchema, setDeliverySchema,\n setStatusSchema, spotifyId,\n} from './schemas.js';\n\ninterface Plan extends Omit<WritePreview, 'serverValidated'> { execute: () => Promise<string[]> }\nconst LEVEL = { account: 'AD_ACCOUNT', campaign: 'CAMPAIGN', ad_group: 'AD_SET', ad: 'AD' } as const;\nconst FIELDS = { spend: 'SPEND', impressions: 'IMPRESSIONS', clicks: 'CLICKS', conversions: 'PURCHASES', conversion_value: 'REVENUE' } as const;\nconst DERIVED = {\n ctr: ['clicks', 'impressions', 100], cpc: ['spend', 'clicks', 1], cpm: ['spend', 'impressions', 1000],\n cpa: ['spend', 'conversions', 1], roas: ['conversion_value', 'spend', 1],\n} as const;\n\nexport class SpotifyAdsProvider implements AdProvider {\n readonly id = 'spotify';\n constructor(private readonly client: SpotifyAdsClient) {}\n capabilities() { return { serverDryRun: false }; }\n standardActions(): StandardActions {\n return { pauseCampaign: (accountId, campaignId) => ({ tool: 'spotify_set_campaign_status', input: { account_id: accountId, campaign_id: campaignId, status: 'PAUSED' } }) };\n }\n\n async listAccounts(): Promise<Account[]> {\n const { businesses } = await this.client.get('businesses', z.object({ businesses: z.array(businessSchema) }));\n const accounts = new Map<string, Account>();\n for (const business of businesses) {\n const { ad_accounts } = await this.client.get(`businesses/${business.id}/ad_accounts`, z.object({ ad_accounts: z.array(accountSchema) }));\n for (const account of ad_accounts) accounts.set(account.id, { provider: this.id, id: account.id, name: account.name, currency: account.currency_code, status: account.status });\n }\n return [...accounts.values()];\n }\n\n async listCampaigns(accountId: string) {\n const path = `ad_accounts/${spotifyId.parse(accountId)}/campaigns`;\n const schema = z.object({ paging: pagingSchema, campaigns: z.array(campaignSchema) });\n const rows: z.infer<typeof campaignSchema>[] = [];\n const seen = new Set<string>();\n for (let page = 0, offset = 0; page < 1000; page++) {\n const data = await this.client.get(path, schema, new URLSearchParams({ limit: '50', offset: String(offset), sort_field: 'ID', sort_direction: 'ASC' }));\n if (data.paging.offset !== offset) throw new AdportError('PROVIDER_ERROR', 'spotify: campaign pagination changed offset');\n for (const campaign of data.campaigns) {\n if (seen.has(campaign.id)) throw new AdportError('PROVIDER_ERROR', 'spotify: campaign pagination repeated an entity');\n seen.add(campaign.id);\n rows.push(campaign);\n }\n offset += data.campaigns.length;\n if (offset >= data.paging.total_results) return rows;\n if (!data.campaigns.length) break;\n }\n throw new AdportError('PROVIDER_ERROR', 'spotify: campaign pagination did not terminate; refusing incomplete results');\n }\n\n async getAdSet(accountId: string, adSetId: string) {\n const data = await this.client.get(`ad_accounts/${spotifyId.parse(accountId)}/ad_sets/${spotifyId.parse(adSetId)}`, adSetSchema);\n if (data.id !== adSetId) throw new AdportError('PROVIDER_ERROR', 'spotify: ad set response ID mismatch');\n return data;\n }\n\n async report(query: NormalizedQuery): Promise<Report> {\n const range = resolveDateRange(query.dateRange);\n const start = z.iso.date().parse(range.start), end = z.iso.date().parse(range.end);\n const days = (Date.parse(end) - Date.parse(start)) / 86_400_000;\n if (days < 0 || days > 90) throw new AdportError('INVALID_INPUT', 'spotify: report end must be on/after start and within 90 days');\n const limit = query.limit ?? 1000;\n if (!Number.isSafeInteger(limit) || limit < 1) throw new AdportError('INVALID_INPUT', 'spotify: report limit must be a positive integer');\n const fields = new Set<string>();\n for (const metric of query.metrics) {\n if (metric in FIELDS) fields.add(FIELDS[metric as keyof typeof FIELDS]);\n else if (metric in DERIVED) for (const dependency of DERIVED[metric as keyof typeof DERIVED].slice(0, 2)) fields.add(FIELDS[dependency as keyof typeof FIELDS]);\n }\n if (!fields.size) throw new AdportError('INVALID_INPUT', 'spotify: report requires at least one supported metric');\n const accountIds = [...new Set(query.accountIds ?? (await this.listAccounts()).map(a => a.id))];\n const rows: ReportRow[] = [];\n for (const id of accountIds) {\n const accountId = spotifyId.parse(id);\n let params = new URLSearchParams({ entity_type: LEVEL[query.level], report_start: `${start}T00:00:00Z`, report_end: `${end}T00:00:00Z`, granularity: 'LIFETIME', limit: '50' });\n for (const field of fields) params.append('fields', field);\n const tokens = new Set<string>();\n const entities = new Set<string>();\n while (true) {\n const data = await this.client.get(`ad_accounts/${accountId}/aggregate_reports`, reportSchema, params);\n if (data.granularity !== 'LIFETIME') throw new AdportError('PROVIDER_ERROR', 'spotify: unexpected report granularity');\n for (const row of data.rows) {\n if (row.entity_type !== LEVEL[query.level] || (query.level === 'account' && row.entity_id !== accountId) || entities.has(row.entity_id)) {\n throw new AdportError('PROVIDER_ERROR', 'spotify: incorrectly scoped or duplicate report row');\n }\n entities.add(row.entity_id);\n rows.push({ provider: this.id, accountId, entity: { level: query.level, id: row.entity_id, name: row.entity_name, status: row.entity_status }, metrics: normalize(row.stats, query.metrics) });\n if (rows.length > limit) return { rows: rows.slice(0, limit), truncated: true };\n }\n if (!data.continuation_token) break;\n if (tokens.has(data.continuation_token) || tokens.size >= 1000) throw new AdportError('PROVIDER_ERROR', 'spotify: report pagination did not terminate');\n tokens.add(data.continuation_token);\n // Other parameters are ignored by Spotify when a continuation is supplied.\n params = new URLSearchParams({ continuation_token: data.continuation_token });\n }\n }\n return { rows };\n }\n\n async previewWrite(op: WriteOperation, guard: WriteGuard): Promise<WritePreview> {\n const { execute: _execute, ...preview } = await this.plan(op, guard);\n return { ...preview, serverValidated: false };\n }\n async applyWrite(op: WriteOperation, guard: WriteGuard): Promise<WriteResult> {\n return { applied: true, resourceIds: await (await this.plan(op, guard)).execute() };\n }\n\n private async plan(op: WriteOperation, guard: WriteGuard): Promise<Plan> {\n const accountId = spotifyId.parse(op.accountId);\n const base = `ad_accounts/${accountId}`;\n if (op.provider !== this.id) throw new AdportError('INVALID_INPUT', 'spotify: provider mismatch');\n if (op.tool === 'spotify_create_campaign_draft' && op.kind === 'create') {\n const input = createDraftSchema.parse(op.payload);\n const status = guard.forcePausedCreation ? 'PAUSED' : input.status;\n const body = { ...input, status };\n return {\n summary: `Create Spotify campaign draft \"${input.name}\" (not published)`, changes: [`+ ${JSON.stringify(body)}`],\n coercions: input.status !== status ? ['status coerced to PAUSED by policy (paused_creation)'] : [], budgetDeltas: [],\n execute: async () => {\n const result = await this.client.mutate(`${base}/drafts/campaigns`, 'POST', body, draftSchema);\n if (result.ad_account_id !== accountId || result.status !== status) throw new AdportError('PROVIDER_ERROR', 'spotify: created draft response violated account/status expectations; inspect the draft before retrying');\n return [result.id];\n },\n };\n }\n if (op.tool === 'spotify_set_campaign_status' && op.kind === 'update') {\n const input = setStatusSchema.parse(op.payload);\n const path = `${base}/campaigns/${input.campaign_id}`;\n const current = await this.client.get(path, campaignSchema);\n if (current.id !== input.campaign_id) throw new AdportError('PROVIDER_ERROR', 'spotify: campaign response ID mismatch');\n return {\n summary: `Change Spotify campaign \"${current.name}\" status`, changes: [`~ ${current.id} status: ${current.status} → ${input.status}`], coercions: [], budgetDeltas: [],\n execute: async () => {\n const result = await this.client.mutate(path, 'PATCH', { status: input.status }, campaignSchema);\n if (result.id !== current.id || result.status !== input.status) throw new AdportError('PROVIDER_ERROR', 'spotify: campaign update response mismatch; inspect before retrying');\n return [result.id];\n },\n };\n }\n if (op.kind === 'update' && ['spotify_set_budget', 'spotify_set_ad_set_delivery'].includes(op.tool)) {\n const input = op.tool === 'spotify_set_budget' ? setBudgetSchema.parse(op.payload) : setDeliverySchema.parse(op.payload);\n const current = await this.getAdSet(accountId, input.ad_set_id);\n const budget = 'budget_micros' in input ? { micro_amount: input.budget_micros, type: current.budget.type } : undefined;\n // Delivery must be the sole field in an ad-set PATCH. Budget changes keep\n // the existing budget type so DAILY/LIFETIME deltas stay comparable.\n const body = budget ? { budget } : { delivery: 'delivery' in input ? input.delivery : current.delivery };\n return {\n summary: `Change Spotify ad set \"${current.name}\" ${budget ? 'budget' : 'delivery'}`,\n changes: [budget ? `~ ${current.id} ${budget.type} budget micros: ${current.budget.micro_amount} → ${budget.micro_amount}` : `~ ${current.id} delivery: ${current.delivery} → ${body.delivery}`],\n coercions: [], budgetDeltas: budget ? [{ target: `ad set ${current.id} ${budget.type} budget`, fromMicros: current.budget.micro_amount, toMicros: budget.micro_amount }] : [],\n execute: async () => {\n const result = await this.client.mutate(`${base}/ad_sets/${current.id}`, 'PATCH', body, adSetSchema);\n if (result.id !== current.id || result.campaign_id !== current.campaign_id\n || (budget && (result.budget.type !== budget.type || result.budget.micro_amount !== budget.micro_amount))\n || (!budget && result.delivery !== body.delivery)) {\n throw new AdportError('PROVIDER_ERROR', 'spotify: ad set update response mismatch; inspect before retrying');\n }\n return [result.id];\n },\n };\n }\n throw new AdportError('INVALID_INPUT', `spotify: unsupported write ${op.tool}`);\n }\n}\n\nfunction normalize(stats: Array<{ field_type: string; field_value: number }>, requested: MetricName[]) {\n const raw = new Map<string, number>();\n for (const stat of stats) {\n if (raw.has(stat.field_type)) throw new AdportError('PROVIDER_ERROR', 'spotify: duplicate report metric');\n raw.set(stat.field_type, stat.field_value);\n }\n const mapped: Partial<Record<MetricName, number>> = {};\n for (const [metric, field] of Object.entries(FIELDS)) {\n const value = raw.get(field);\n // Suppressed conversion counts (-5) and missing metrics are not zero.\n if (value !== undefined && value >= 0) mapped[metric as MetricName] = value;\n }\n for (const [metric, [numerator, denominator, factor]] of Object.entries(DERIVED)) {\n if (mapped[numerator] !== undefined && mapped[denominator] !== undefined) mapped[metric as MetricName] = mapped[denominator] ? mapped[numerator]! / mapped[denominator]! * factor : 0;\n }\n return Object.fromEntries(requested.filter(metric => mapped[metric] !== undefined).map(metric => [metric, mapped[metric]]));\n}\n","import { z } from 'zod';\n\n// Spotify Ads v3 reference contracts, reviewed 2026-08-31.\n// Response objects remain forward-compatible; fields consumed for policy and\n// reporting are validated instead of interpreting malformed data as empty data.\nexport const spotifyId = z.uuid();\nexport const businessSchema = z.looseObject({ id: spotifyId, name: z.string() });\nexport const accountSchema = z.looseObject({\n id: spotifyId, name: z.string(), currency_code: z.string(), status: z.string(),\n business_id: spotifyId.optional(), test_account_type: z.string().optional(),\n});\nexport const campaignSchema = z.looseObject({ id: spotifyId, name: z.string(), status: z.string() });\nexport const draftSchema = campaignSchema.extend({ ad_account_id: spotifyId });\nexport const budgetSchema = z.object({ micro_amount: z.number().int().nonnegative().safe(), type: z.enum(['DAILY', 'LIFETIME']) });\nexport const adSetSchema = z.looseObject({\n id: spotifyId, campaign_id: spotifyId, name: z.string(), budget: budgetSchema, delivery: z.enum(['ON', 'OFF']),\n});\nexport const pagingSchema = z.object({\n page_size: z.number().int().nonnegative(), total_results: z.number().int().nonnegative(),\n offset: z.number().int().nonnegative(), current_page: z.number().int().nonnegative(),\n});\nexport const reportRowSchema = z.looseObject({\n entity_type: z.enum(['AD_ACCOUNT', 'CAMPAIGN', 'AD_SET', 'AD']),\n entity_id: spotifyId, entity_name: z.string(), entity_status: z.string(),\n stats: z.array(z.object({ field_type: z.string(), field_value: z.number() })),\n});\nexport const reportSchema = z.looseObject({\n continuation_token: z.string().nullable().optional(),\n granularity: z.enum(['LIFETIME', 'DAY', 'HOUR']), rows: z.array(reportRowSchema),\n});\nexport const createDraftSchema = z.object({\n name: z.string().trim().min(2).max(200),\n purchase_order: z.string().min(2).max(45).optional(),\n delivery_goal_group: z.enum(['AWARENESS', 'WEBSITE_TRAFFIC', 'APP_PROMOTION', 'ENGAGEMENT_ON_SPOTIFY', 'LEAD_GEN', 'VIDEO_VIEWS']),\n status: z.enum(['PAUSED', 'ACTIVE']).default('PAUSED'),\n});\nexport const setStatusSchema = z.object({ campaign_id: spotifyId, status: z.enum(['PAUSED', 'ACTIVE']) });\nexport const setBudgetSchema = z.object({ ad_set_id: spotifyId, budget_micros: z.number().int().positive().safe() });\nexport const setDeliverySchema = z.object({ ad_set_id: spotifyId, delivery: z.enum(['OFF', 'ON']) });\n","import { z } from 'zod';\nimport { defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { createDraftSchema, setBudgetSchema, setDeliverySchema, setStatusSchema, spotifyId } from './schemas.js';\nimport type { SpotifyAdsProvider } from './provider.js';\n\nexport function spotifyTools(provider: SpotifyAdsProvider): AnyToolDefinition[] {\n return [\n defineTool({ name: 'spotify_list_campaigns', namespace: 'spotify', description: 'List published Spotify Ads campaigns in the selected account.',\n input: z.object({ account_id: spotifyId }), annotations: { readOnly: true }, handler: input => provider.listCampaigns(input.account_id) }),\n defineTool({ name: 'spotify_get_ad_set', namespace: 'spotify', description: 'Read a Spotify ad set, including its budget and delivery setting.',\n input: z.object({ account_id: spotifyId, ad_set_id: spotifyId }), annotations: { readOnly: true }, handler: input => provider.getAdSet(input.account_id, input.ad_set_id) }),\n guardedWriteTool({ name: 'spotify_create_campaign_draft', namespace: 'spotify', provider: 'spotify', kind: 'create',\n description: 'Create an unpublished Spotify campaign draft, paused by policy. Does not publish or launch ads. Preview is local.', payload: createDraftSchema }),\n guardedWriteTool({ name: 'spotify_set_campaign_status', namespace: 'spotify', provider: 'spotify', kind: 'update',\n description: 'Pause or activate an existing Spotify Ads campaign.', payload: setStatusSchema }),\n guardedWriteTool({ name: 'spotify_set_budget', namespace: 'spotify', provider: 'spotify', kind: 'update',\n description: 'Change a Spotify ad-set budget in integer micros, preserving its current DAILY or LIFETIME type.', payload: setBudgetSchema }),\n guardedWriteTool({ name: 'spotify_set_ad_set_delivery', namespace: 'spotify', provider: 'spotify', kind: 'update',\n description: 'Turn an existing Spotify ad set delivery OFF or ON.', payload: setDeliverySchema }),\n ];\n}\n","import type { CredentialStore, ProviderModule } from '@adport/core';\nimport { SpotifyAdsClient, type SpotifyCredentials } from './client.js';\nimport { SpotifyAdsProvider } from './provider.js';\nimport { spotifyTools } from './tools.js';\nexport { SpotifyAdsClient, SPOTIFY_API_BASE, SPOTIFY_TOKEN_URL, buildSpotifyAuthUrl, exchangeSpotifyCode, type SpotifyCredentials } from './client.js';\nexport { SpotifyAdsProvider } from './provider.js';\nexport { spotifyTools } from './tools.js';\nexport { accountSchema, campaignSchema, draftSchema, adSetSchema, reportSchema } from './schemas.js';\n\nexport async function resolveSpotifyCredentials(store: CredentialStore): Promise<SpotifyCredentials | undefined> {\n const data = (await store.get('spotify'))?.data;\n if (data?.client_id && data.client_secret && data.refresh_token) return {\n clientId: data.client_id, clientSecret: data.client_secret, refreshToken: data.refresh_token,\n onRefreshToken: async refreshToken => {\n const latest = await store.get('spotify');\n if (latest) await store.set({ provider: 'spotify', source: latest.source, data: { ...latest.data, refresh_token: refreshToken } });\n },\n };\n if (process.env.SPOTIFY_CLIENT_ID && process.env.SPOTIFY_CLIENT_SECRET && process.env.SPOTIFY_REFRESH_TOKEN) return {\n clientId: process.env.SPOTIFY_CLIENT_ID, clientSecret: process.env.SPOTIFY_CLIENT_SECRET, refreshToken: process.env.SPOTIFY_REFRESH_TOKEN,\n };\n return undefined;\n}\n\nexport async function createSpotifyModule(store: CredentialStore): Promise<ProviderModule | undefined> {\n const credentials = await resolveSpotifyCredentials(store);\n if (!credentials) return undefined;\n const provider = new Spot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IAAe,cAAc,KAAK;AAAA,IAC/E,gBAAgB,OAAM,iBAAgB;AACpC,YAAM,SAAS,MAAM,MAAM,IAAI,SAAS;AACxC,UAAI,OAAQ,OAAM,MAAM,IAAI,EAAE,UAAU,WAAW,QAAQ,OAAO,QAAQ,MAAM,EAAE,GAAG,OAAO,MAAM,eAAe,aAAa,EAAE,CAAC;AAAA,IACnI;AAAA,EACF;AACA,MAAI,QAAQ,IAAI,qBAAqB,QAAQ,IAAI,yBAAyB,QAAQ,IAAI,sBAAuB,QAAO;AAAA,IAClH,UAAU,QAAQ,IAAI;AAAA,IAAmB,cAAc,QAAQ,IAAI;AAAA,IAAuB,cAAc,QAAQ,IAAI;AAAA,EACtH;AACA,SAAO;AACT;AAEA,eAAsB,oBAAoB,OAA6D;AACrG,QAAM,cAAc,MAAM,0BAA0B,KAAK;AACzD,MAAI,CAAC,YAAa,QAAO;AACzB,QAAM,WAAW,IAAI,mBAAmB,IAAI,iBAAiB,WAAW,CAAC;AACzE,SAAO,EAAE,UAAU,OAAO,aAAa,QAAQ,EAAE;AACnD;","names":["z","AdportError","z","z","AdportError","z","z"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@adport/provider-spotify",
|
|
3
|
+
"version": "0.6.0",
|
|
4
|
+
"description": "Spotify Ads API provider for adport",
|
|
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": "^4.4.3",
|
|
20
|
+
"@adport/core": "0.6.0"
|
|
21
|
+
},
|
|
22
|
+
"devDependencies": {
|
|
23
|
+
"@types/node": "^26.1.2",
|
|
24
|
+
"tsup": "^8.3.0",
|
|
25
|
+
"typescript": "^5.8.0",
|
|
26
|
+
"vitest": "^4.1.10"
|
|
27
|
+
},
|
|
28
|
+
"scripts": {
|
|
29
|
+
"build": "tsup src/index.ts --format esm --dts --sourcemap --clean",
|
|
30
|
+
"test": "vitest run",
|
|
31
|
+
"typecheck": "tsc --noEmit"
|
|
32
|
+
}
|
|
33
|
+
}
|