@adport/provider-pinterest 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 +101 -0
- package/dist/index.js +383 -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,101 @@
|
|
|
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 PINTEREST_API_BASE = "https://api.pinterest.com/v5/";
|
|
6
|
+
declare const PINTEREST_TOKEN_URL = "https://api.pinterest.com/v5/oauth/token";
|
|
7
|
+
interface PinterestCredentials {
|
|
8
|
+
clientId: string;
|
|
9
|
+
clientSecret: string;
|
|
10
|
+
refreshToken: string;
|
|
11
|
+
onRefreshToken?: (refreshToken: string) => Promise<void>;
|
|
12
|
+
}
|
|
13
|
+
declare function buildPinterestAuthUrl(clientId: string, redirectUri: string, state: string): string;
|
|
14
|
+
declare function exchangePinterestCode(input: {
|
|
15
|
+
clientId: string;
|
|
16
|
+
clientSecret: string;
|
|
17
|
+
code: string;
|
|
18
|
+
redirectUri: string;
|
|
19
|
+
}, fetchImpl?: typeof fetch): Promise<string>;
|
|
20
|
+
declare class PinterestAdsClient {
|
|
21
|
+
private readonly credentials;
|
|
22
|
+
private readonly fetchImpl;
|
|
23
|
+
private token?;
|
|
24
|
+
private refreshToken;
|
|
25
|
+
private refreshing?;
|
|
26
|
+
constructor(credentials: PinterestCredentials, 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 PinterestAdsProvider implements AdProvider {
|
|
35
|
+
private readonly client;
|
|
36
|
+
readonly id = "pinterest";
|
|
37
|
+
constructor(client: PinterestAdsClient);
|
|
38
|
+
capabilities(): {
|
|
39
|
+
serverDryRun: boolean;
|
|
40
|
+
};
|
|
41
|
+
standardActions(): StandardActions;
|
|
42
|
+
private collect;
|
|
43
|
+
listAccounts(): Promise<Account[]>;
|
|
44
|
+
listCampaigns(accountId: string): Promise<{
|
|
45
|
+
[x: string]: unknown;
|
|
46
|
+
id: string;
|
|
47
|
+
ad_account_id: string;
|
|
48
|
+
name?: string | null | undefined;
|
|
49
|
+
status?: "ACTIVE" | "PAUSED" | "ARCHIVED" | "DRAFT" | "DELETED_DRAFT" | undefined;
|
|
50
|
+
daily_spend_cap?: number | null | undefined;
|
|
51
|
+
lifetime_spend_cap?: number | null | undefined;
|
|
52
|
+
is_campaign_budget_optimization?: boolean | null | undefined;
|
|
53
|
+
is_flexible_daily_budgets?: boolean | null | undefined;
|
|
54
|
+
}[]>;
|
|
55
|
+
private listEntities;
|
|
56
|
+
getCampaign(accountId: string, campaignId: string): Promise<{
|
|
57
|
+
[x: string]: unknown;
|
|
58
|
+
id: string;
|
|
59
|
+
ad_account_id: string;
|
|
60
|
+
name?: string | null | undefined;
|
|
61
|
+
status?: "ACTIVE" | "PAUSED" | "ARCHIVED" | "DRAFT" | "DELETED_DRAFT" | undefined;
|
|
62
|
+
daily_spend_cap?: number | null | undefined;
|
|
63
|
+
lifetime_spend_cap?: number | null | undefined;
|
|
64
|
+
is_campaign_budget_optimization?: boolean | null | undefined;
|
|
65
|
+
is_flexible_daily_budgets?: boolean | null | undefined;
|
|
66
|
+
}>;
|
|
67
|
+
report(query: NormalizedQuery): Promise<Report>;
|
|
68
|
+
previewWrite(op: WriteOperation, guard: WriteGuard): Promise<WritePreview>;
|
|
69
|
+
applyWrite(op: WriteOperation, guard: WriteGuard): Promise<WriteResult>;
|
|
70
|
+
private write;
|
|
71
|
+
private plan;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
declare function pinterestTools(provider: PinterestAdsProvider): AnyToolDefinition[];
|
|
75
|
+
|
|
76
|
+
declare const accountSchema: z.ZodObject<{
|
|
77
|
+
id: z.ZodString;
|
|
78
|
+
name: z.ZodOptional<z.ZodString>;
|
|
79
|
+
currency: z.ZodOptional<z.ZodString>;
|
|
80
|
+
}, z.core.$loose>;
|
|
81
|
+
declare const campaignSchema: z.ZodObject<{
|
|
82
|
+
id: z.ZodString;
|
|
83
|
+
ad_account_id: z.ZodString;
|
|
84
|
+
name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
85
|
+
status: z.ZodOptional<z.ZodEnum<{
|
|
86
|
+
ACTIVE: "ACTIVE";
|
|
87
|
+
PAUSED: "PAUSED";
|
|
88
|
+
ARCHIVED: "ARCHIVED";
|
|
89
|
+
DRAFT: "DRAFT";
|
|
90
|
+
DELETED_DRAFT: "DELETED_DRAFT";
|
|
91
|
+
}>>;
|
|
92
|
+
daily_spend_cap: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
93
|
+
lifetime_spend_cap: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
94
|
+
is_campaign_budget_optimization: z.ZodOptional<z.ZodNullable<z.ZodBoolean>>;
|
|
95
|
+
is_flexible_daily_budgets: z.ZodOptional<z.ZodNullable<z.ZodBoolean>>;
|
|
96
|
+
}, z.core.$loose>;
|
|
97
|
+
|
|
98
|
+
declare function resolvePinterestCredentials(store: CredentialStore): Promise<PinterestCredentials | undefined>;
|
|
99
|
+
declare function createPinterestModule(store: CredentialStore): Promise<ProviderModule | undefined>;
|
|
100
|
+
|
|
101
|
+
export { PINTEREST_API_BASE, PINTEREST_TOKEN_URL, PinterestAdsClient, PinterestAdsProvider, type PinterestCredentials, accountSchema, buildPinterestAuthUrl, campaignSchema, createPinterestModule, exchangePinterestCode, pinterestTools, resolvePinterestCredentials };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,383 @@
|
|
|
1
|
+
// src/client.ts
|
|
2
|
+
import { AdportError } from "@adport/core";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
var PINTEREST_API_BASE = "https://api.pinterest.com/v5/";
|
|
5
|
+
var PINTEREST_TOKEN_URL = `${PINTEREST_API_BASE}oauth/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 buildPinterestAuthUrl(clientId, redirectUri, state) {
|
|
12
|
+
return `https://www.pinterest.com/oauth/?${new URLSearchParams({
|
|
13
|
+
client_id: clientId,
|
|
14
|
+
response_type: "code",
|
|
15
|
+
redirect_uri: redirectUri,
|
|
16
|
+
state,
|
|
17
|
+
scope: "ads:read,ads:write"
|
|
18
|
+
})}`;
|
|
19
|
+
}
|
|
20
|
+
async function tokenRequest(credentials, body, fetchImpl) {
|
|
21
|
+
const response = await fetchImpl(PINTEREST_TOKEN_URL, {
|
|
22
|
+
method: "POST",
|
|
23
|
+
headers: {
|
|
24
|
+
authorization: `Basic ${Buffer.from(`${credentials.clientId}:${credentials.clientSecret}`).toString("base64")}`,
|
|
25
|
+
"content-type": "application/x-www-form-urlencoded"
|
|
26
|
+
},
|
|
27
|
+
body,
|
|
28
|
+
redirect: "error",
|
|
29
|
+
signal: AbortSignal.timeout(3e4)
|
|
30
|
+
});
|
|
31
|
+
if (!response.ok) throw new AdportError("PROVIDER_ERROR", `pinterest: OAuth ${body.get("grant_type")} failed (HTTP ${response.status})`);
|
|
32
|
+
const parsed = tokenSchema.safeParse(await response.json());
|
|
33
|
+
if (!parsed.success) throw new AdportError("PROVIDER_ERROR", "pinterest: malformed OAuth response");
|
|
34
|
+
return parsed.data;
|
|
35
|
+
}
|
|
36
|
+
async function exchangePinterestCode(input, fetchImpl = fetch) {
|
|
37
|
+
const token = await tokenRequest(input, new URLSearchParams({
|
|
38
|
+
grant_type: "authorization_code",
|
|
39
|
+
code: input.code,
|
|
40
|
+
redirect_uri: input.redirectUri,
|
|
41
|
+
continuous_refresh: "true"
|
|
42
|
+
}), fetchImpl);
|
|
43
|
+
if (!token.refresh_token) throw new AdportError("PROVIDER_ERROR", "pinterest: OAuth exchange did not return a refresh token");
|
|
44
|
+
return token.refresh_token;
|
|
45
|
+
}
|
|
46
|
+
var PinterestAdsClient = class {
|
|
47
|
+
constructor(credentials, fetchImpl = fetch) {
|
|
48
|
+
this.credentials = credentials;
|
|
49
|
+
this.fetchImpl = fetchImpl;
|
|
50
|
+
this.refreshToken = credentials.refreshToken;
|
|
51
|
+
}
|
|
52
|
+
credentials;
|
|
53
|
+
fetchImpl;
|
|
54
|
+
token;
|
|
55
|
+
refreshToken;
|
|
56
|
+
refreshing;
|
|
57
|
+
async get(path, schema, params = new URLSearchParams()) {
|
|
58
|
+
return this.request(path, "GET", schema, void 0, params);
|
|
59
|
+
}
|
|
60
|
+
async mutate(path, method, body, schema) {
|
|
61
|
+
return this.request(path, method, schema, body);
|
|
62
|
+
}
|
|
63
|
+
async request(path, method, schema, body, params = new URLSearchParams(), retry = true) {
|
|
64
|
+
if (!/^[a-z_]+(?:\/[a-zA-Z0-9_-]+)*$/.test(path)) throw new AdportError("INVALID_INPUT", "pinterest: invalid API resource path");
|
|
65
|
+
const url = new URL(path, PINTEREST_API_BASE);
|
|
66
|
+
url.search = params.toString();
|
|
67
|
+
const token = await this.accessToken();
|
|
68
|
+
const response = await this.fetchImpl(url.href, {
|
|
69
|
+
method,
|
|
70
|
+
headers: { authorization: `Bearer ${token}`, ...body !== void 0 ? { "content-type": "application/json" } : {} },
|
|
71
|
+
...body !== void 0 ? { body: JSON.stringify(body) } : {},
|
|
72
|
+
redirect: "error",
|
|
73
|
+
signal: AbortSignal.timeout(3e4)
|
|
74
|
+
});
|
|
75
|
+
if (response.status === 401 && method === "GET" && retry) {
|
|
76
|
+
if (this.token?.value === token) this.token = void 0;
|
|
77
|
+
return this.request(path, method, schema, body, params, false);
|
|
78
|
+
}
|
|
79
|
+
if (!response.ok) {
|
|
80
|
+
const advice = response.status === 403 ? " Check app Trial/Standard access, ads scopes and ad-account permissions; reauthorization alone may not help." : "";
|
|
81
|
+
throw new AdportError("PROVIDER_ERROR", `pinterest: HTTP ${response.status}.${advice}`);
|
|
82
|
+
}
|
|
83
|
+
const parsed = schema.safeParse(await response.json());
|
|
84
|
+
if (!parsed.success) throw new AdportError("PROVIDER_ERROR", "pinterest: malformed API response");
|
|
85
|
+
return parsed.data;
|
|
86
|
+
}
|
|
87
|
+
async accessToken() {
|
|
88
|
+
if (this.token && this.token.expiresAt > Date.now() + 6e4) return this.token.value;
|
|
89
|
+
if (!this.refreshing) this.refreshing = this.refresh().finally(() => {
|
|
90
|
+
this.refreshing = void 0;
|
|
91
|
+
});
|
|
92
|
+
return this.refreshing;
|
|
93
|
+
}
|
|
94
|
+
async refresh() {
|
|
95
|
+
const token = await tokenRequest(this.credentials, new URLSearchParams({ grant_type: "refresh_token", refresh_token: this.refreshToken }), this.fetchImpl);
|
|
96
|
+
if (token.refresh_token && token.refresh_token !== this.refreshToken) {
|
|
97
|
+
this.refreshToken = token.refresh_token;
|
|
98
|
+
await this.credentials.onRefreshToken?.(token.refresh_token);
|
|
99
|
+
}
|
|
100
|
+
this.token = { value: token.access_token, expiresAt: Date.now() + token.expires_in * 1e3 };
|
|
101
|
+
return token.access_token;
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
// src/provider.ts
|
|
106
|
+
import { z as z3 } from "zod";
|
|
107
|
+
import {
|
|
108
|
+
AdportError as AdportError2,
|
|
109
|
+
resolveDateRange
|
|
110
|
+
} from "@adport/core";
|
|
111
|
+
|
|
112
|
+
// src/schemas.ts
|
|
113
|
+
import { z as z2 } from "zod";
|
|
114
|
+
var pinterestId = z2.string().regex(/^\d+$/).max(18);
|
|
115
|
+
var entityStatus = z2.enum(["ACTIVE", "PAUSED", "ARCHIVED", "DRAFT", "DELETED_DRAFT"]);
|
|
116
|
+
var micros = z2.number().int().nonnegative().safe();
|
|
117
|
+
var accountSchema = z2.looseObject({ id: pinterestId, name: z2.string().optional(), currency: z2.string().optional() });
|
|
118
|
+
var entitySchema = z2.looseObject({ id: pinterestId, ad_account_id: pinterestId, name: z2.string().nullable().optional(), status: entityStatus.optional() });
|
|
119
|
+
var campaignSchema = entitySchema.extend({
|
|
120
|
+
daily_spend_cap: micros.nullable().optional(),
|
|
121
|
+
lifetime_spend_cap: micros.nullable().optional(),
|
|
122
|
+
is_campaign_budget_optimization: z2.boolean().nullable().optional(),
|
|
123
|
+
is_flexible_daily_budgets: z2.boolean().nullable().optional()
|
|
124
|
+
});
|
|
125
|
+
var batchResponseSchema = z2.object({ items: z2.array(z2.object({
|
|
126
|
+
data: campaignSchema.partial().optional(),
|
|
127
|
+
exceptions: z2.array(z2.unknown()).optional()
|
|
128
|
+
})) });
|
|
129
|
+
var createCampaignSchema = z2.object({
|
|
130
|
+
name: z2.string().trim().min(1).max(255),
|
|
131
|
+
objective_type: z2.enum(["AWARENESS", "CONSIDERATION", "WEB_CONVERSION", "CATALOG_SALES", "VIDEO_COMPLETION", "APP_INSTALL", "SALES", "LEADS", "CTV_CONSIDERATION"]),
|
|
132
|
+
status: z2.enum(["PAUSED", "ACTIVE"]).default("PAUSED"),
|
|
133
|
+
budget_type: z2.enum(["DAILY", "LIFETIME"]).default("DAILY"),
|
|
134
|
+
budget_micros: micros.positive(),
|
|
135
|
+
start_time: z2.number().int().positive().safe().optional(),
|
|
136
|
+
end_time: z2.number().int().positive().safe().optional(),
|
|
137
|
+
app_id: z2.string().min(1).optional(),
|
|
138
|
+
app_platform: z2.enum(["IOS", "ANDROID"]).optional()
|
|
139
|
+
}).superRefine((value, ctx) => {
|
|
140
|
+
if (value.budget_type === "LIFETIME" && !value.end_time) ctx.addIssue({ code: "custom", path: ["end_time"], message: "Lifetime campaign budgets require an end time." });
|
|
141
|
+
if (value.start_time && value.end_time && value.end_time <= value.start_time) ctx.addIssue({ code: "custom", path: ["end_time"], message: "End time must be after start time." });
|
|
142
|
+
if (value.objective_type === "APP_INSTALL" && (!value.app_id || !value.app_platform)) ctx.addIssue({ code: "custom", path: ["app_id"], message: "APP_INSTALL requires app_id and app_platform and Pinterest beta access." });
|
|
143
|
+
});
|
|
144
|
+
var setStatusSchema = z2.object({ campaign_id: pinterestId, status: z2.enum(["PAUSED", "ACTIVE"]) });
|
|
145
|
+
var setBudgetSchema = z2.object({ campaign_id: pinterestId, budget_micros: micros.positive() });
|
|
146
|
+
|
|
147
|
+
// src/provider.ts
|
|
148
|
+
var LEVEL = {
|
|
149
|
+
account: { path: "", id: "AD_ACCOUNT_ID", filter: "" },
|
|
150
|
+
campaign: { path: "campaigns", id: "CAMPAIGN_ID", filter: "campaign_ids" },
|
|
151
|
+
ad_group: { path: "ad_groups", id: "AD_GROUP_ID", filter: "ad_group_ids" },
|
|
152
|
+
ad: { path: "ads", id: "AD_ID", filter: "ad_ids" }
|
|
153
|
+
};
|
|
154
|
+
var FIELDS = { spend: "SPEND_IN_MICRO_DOLLAR", impressions: "PAID_IMPRESSION", clicks: "OUTBOUND_CLICK_1", conversions: "TOTAL_CHECKOUT", conversion_value: "TOTAL_CHECKOUT_VALUE_IN_MICRO_DOLLAR" };
|
|
155
|
+
var DERIVED = {
|
|
156
|
+
ctr: ["clicks", "impressions", 100],
|
|
157
|
+
cpc: ["spend", "clicks", 1],
|
|
158
|
+
cpm: ["spend", "impressions", 1e3],
|
|
159
|
+
cpa: ["spend", "conversions", 1],
|
|
160
|
+
roas: ["conversion_value", "spend", 1]
|
|
161
|
+
};
|
|
162
|
+
var PinterestAdsProvider = class {
|
|
163
|
+
constructor(client) {
|
|
164
|
+
this.client = client;
|
|
165
|
+
}
|
|
166
|
+
client;
|
|
167
|
+
id = "pinterest";
|
|
168
|
+
capabilities() {
|
|
169
|
+
return { serverDryRun: false };
|
|
170
|
+
}
|
|
171
|
+
standardActions() {
|
|
172
|
+
return { pauseCampaign: (accountId, campaignId) => ({ tool: "pinterest_set_campaign_status", input: { account_id: accountId, campaign_id: campaignId, status: "PAUSED" } }) };
|
|
173
|
+
}
|
|
174
|
+
async collect(path, schema, params = new URLSearchParams()) {
|
|
175
|
+
const result = [], bookmarks = /* @__PURE__ */ new Set(), entities = /* @__PURE__ */ new Set();
|
|
176
|
+
const query = new URLSearchParams(params);
|
|
177
|
+
query.set("page_size", "250");
|
|
178
|
+
const pageSchema = z3.object({ items: z3.array(schema), bookmark: z3.string().nullable().optional() });
|
|
179
|
+
while (true) {
|
|
180
|
+
const page = await this.client.get(path, pageSchema, query);
|
|
181
|
+
for (const item of page.items) {
|
|
182
|
+
if (entities.has(item.id)) throw new AdportError2("PROVIDER_ERROR", "pinterest: pagination repeated an entity");
|
|
183
|
+
entities.add(item.id);
|
|
184
|
+
result.push(item);
|
|
185
|
+
}
|
|
186
|
+
if (!page.bookmark) return result;
|
|
187
|
+
if (bookmarks.has(page.bookmark) || bookmarks.size >= 1e3) throw new AdportError2("PROVIDER_ERROR", "pinterest: pagination did not terminate");
|
|
188
|
+
bookmarks.add(page.bookmark);
|
|
189
|
+
query.set("bookmark", page.bookmark);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
async listAccounts() {
|
|
193
|
+
return (await this.collect("ad_accounts", accountSchema)).map((a) => ({ provider: this.id, id: a.id, name: a.name ?? a.id, ...a.currency ? { currency: a.currency } : {} }));
|
|
194
|
+
}
|
|
195
|
+
async listCampaigns(accountId) {
|
|
196
|
+
return this.listEntities(accountId, "campaigns", campaignSchema);
|
|
197
|
+
}
|
|
198
|
+
async listEntities(accountId, collection, schema) {
|
|
199
|
+
const params = new URLSearchParams();
|
|
200
|
+
for (const status of entityStatus.options) params.append("entity_statuses", status);
|
|
201
|
+
const rows = await this.collect(`ad_accounts/${pinterestId.parse(accountId)}/${collection}`, schema, params);
|
|
202
|
+
if (rows.some((row) => row.ad_account_id !== accountId)) throw new AdportError2("PROVIDER_ERROR", "pinterest: entity account mismatch");
|
|
203
|
+
return rows;
|
|
204
|
+
}
|
|
205
|
+
async getCampaign(accountId, campaignId) {
|
|
206
|
+
const result = await this.client.get(`ad_accounts/${pinterestId.parse(accountId)}/campaigns/${pinterestId.parse(campaignId)}`, campaignSchema);
|
|
207
|
+
if (result.id !== campaignId || result.ad_account_id !== accountId) throw new AdportError2("PROVIDER_ERROR", "pinterest: campaign account/ID mismatch");
|
|
208
|
+
return result;
|
|
209
|
+
}
|
|
210
|
+
async report(query) {
|
|
211
|
+
const range = resolveDateRange(query.dateRange);
|
|
212
|
+
const start = z3.iso.date().parse(range.start), end = z3.iso.date().parse(range.end);
|
|
213
|
+
const days = (Date.parse(end) - Date.parse(start)) / 864e5;
|
|
214
|
+
if (days < 0 || days > 90) throw new AdportError2("INVALID_INPUT", "pinterest: report end must be on/after start and within 90 days");
|
|
215
|
+
const limit = query.limit ?? 1e3;
|
|
216
|
+
if (!Number.isSafeInteger(limit) || limit < 1) throw new AdportError2("INVALID_INPUT", "pinterest: report limit must be a positive integer");
|
|
217
|
+
const level = LEVEL[query.level], fields = /* @__PURE__ */ new Set();
|
|
218
|
+
for (const metric of query.metrics) {
|
|
219
|
+
if (metric in FIELDS) fields.add(FIELDS[metric]);
|
|
220
|
+
else if (metric in DERIVED) for (const dependency of DERIVED[metric].slice(0, 2)) fields.add(FIELDS[dependency]);
|
|
221
|
+
}
|
|
222
|
+
if (!fields.size) throw new AdportError2("INVALID_INPUT", "pinterest: report requires at least one supported metric");
|
|
223
|
+
const rows = [];
|
|
224
|
+
for (const id of [...new Set(query.accountIds ?? (await this.listAccounts()).map((a) => a.id))]) {
|
|
225
|
+
const accountId = pinterestId.parse(id), base = `ad_accounts/${accountId}`;
|
|
226
|
+
const entities = query.level === "account" ? [await this.client.get(base, accountSchema)] : await this.listEntities(accountId, level.path, entitySchema);
|
|
227
|
+
if (query.level === "account" && entities.some((e) => e.id !== accountId)) throw new AdportError2("PROVIDER_ERROR", "pinterest: account ID mismatch");
|
|
228
|
+
const lookup = new Map(entities.map((e) => [e.id, e]));
|
|
229
|
+
const seen = /* @__PURE__ */ new Set();
|
|
230
|
+
for (let offset = 0; offset < entities.length; offset += 250) {
|
|
231
|
+
const batch = entities.slice(offset, offset + 250), allowed = new Set(batch.map((e) => e.id));
|
|
232
|
+
const params = new URLSearchParams({
|
|
233
|
+
start_date: start,
|
|
234
|
+
end_date: end,
|
|
235
|
+
granularity: "TOTAL",
|
|
236
|
+
columns: [level.id, ...fields].join(","),
|
|
237
|
+
click_window_days: "30",
|
|
238
|
+
view_window_days: "1",
|
|
239
|
+
conversion_report_time: "TIME_OF_AD_ACTION"
|
|
240
|
+
});
|
|
241
|
+
if (level.filter) for (const entity of batch) params.append(level.filter, entity.id);
|
|
242
|
+
const data = await this.client.get(`${base}/${level.path ? `${level.path}/` : ""}analytics`, z3.array(z3.record(z3.string(), z3.unknown())), params);
|
|
243
|
+
for (const row of data) {
|
|
244
|
+
const entityId = pinterestId.parse(row[level.id]);
|
|
245
|
+
if (!allowed.has(entityId) || seen.has(entityId)) throw new AdportError2("PROVIDER_ERROR", "pinterest: incorrectly scoped or duplicate report row");
|
|
246
|
+
seen.add(entityId);
|
|
247
|
+
const entity = lookup.get(entityId);
|
|
248
|
+
rows.push({ provider: this.id, accountId, entity: { level: query.level, id: entityId, name: entity.name ?? entityId, ...typeof entity.status === "string" ? { status: entity.status } : {} }, metrics: normalize(row, query.metrics) });
|
|
249
|
+
if (rows.length > limit) return { rows: rows.slice(0, limit), truncated: true };
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
return { rows };
|
|
254
|
+
}
|
|
255
|
+
async previewWrite(op, guard) {
|
|
256
|
+
const { execute: _execute, ...preview } = await this.plan(op, guard);
|
|
257
|
+
return { ...preview, serverValidated: false };
|
|
258
|
+
}
|
|
259
|
+
async applyWrite(op, guard) {
|
|
260
|
+
return { applied: true, resourceIds: await (await this.plan(op, guard)).execute() };
|
|
261
|
+
}
|
|
262
|
+
async write(accountId, method, body) {
|
|
263
|
+
const result = await this.client.mutate(`ad_accounts/${accountId}/campaigns`, method, [body], batchResponseSchema);
|
|
264
|
+
const item = result.items[0];
|
|
265
|
+
if (result.items.length !== 1 || !item?.data || item.exceptions?.length) throw new AdportError2("PROVIDER_ERROR", "pinterest: campaign batch item failed; inspect account before retrying");
|
|
266
|
+
const parsed = campaignSchema.safeParse(item.data);
|
|
267
|
+
if (!parsed.success) throw new AdportError2("PROVIDER_ERROR", "pinterest: campaign batch returned incomplete data; inspect account before retrying");
|
|
268
|
+
const data = parsed.data;
|
|
269
|
+
if (data.ad_account_id !== accountId || body.id && data.id !== body.id || Object.entries(body).some(([key, value]) => ["status", "daily_spend_cap", "lifetime_spend_cap"].includes(key) && data[key] !== value)) {
|
|
270
|
+
throw new AdportError2("PROVIDER_ERROR", "pinterest: campaign write response mismatch; inspect before retrying");
|
|
271
|
+
}
|
|
272
|
+
return [data.id];
|
|
273
|
+
}
|
|
274
|
+
async plan(op, guard) {
|
|
275
|
+
const accountId = pinterestId.parse(op.accountId);
|
|
276
|
+
if (op.provider !== this.id) throw new AdportError2("INVALID_INPUT", "pinterest: provider mismatch");
|
|
277
|
+
if (op.tool === "pinterest_create_campaign" && op.kind === "create") {
|
|
278
|
+
const input = createCampaignSchema.parse(op.payload);
|
|
279
|
+
const { budget_type, budget_micros, ...rest } = input;
|
|
280
|
+
const status = guard.forcePausedCreation ? "PAUSED" : input.status;
|
|
281
|
+
const cap = budget_type === "DAILY" ? "daily_spend_cap" : "lifetime_spend_cap";
|
|
282
|
+
const body = { ...rest, status, [cap]: budget_micros, is_campaign_budget_optimization: true, is_flexible_daily_budgets: false };
|
|
283
|
+
return {
|
|
284
|
+
summary: `Create Pinterest campaign "${input.name}"`,
|
|
285
|
+
changes: [`+ ${JSON.stringify(body)}`],
|
|
286
|
+
coercions: status !== input.status ? ["status coerced to PAUSED by policy (paused_creation)"] : [],
|
|
287
|
+
budgetDeltas: [{ target: `new campaign ${budget_type} budget`, toMicros: budget_micros }],
|
|
288
|
+
execute: () => this.write(accountId, "POST", body)
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
if (op.kind === "update" && ["pinterest_set_campaign_status", "pinterest_set_budget"].includes(op.tool)) {
|
|
292
|
+
const input = op.tool === "pinterest_set_budget" ? setBudgetSchema.parse(op.payload) : setStatusSchema.parse(op.payload);
|
|
293
|
+
const current = await this.getCampaign(accountId, input.campaign_id);
|
|
294
|
+
if ("budget_micros" in input) {
|
|
295
|
+
const daily = current.daily_spend_cap ?? 0, lifetime = current.lifetime_spend_cap ?? 0;
|
|
296
|
+
if (!current.is_campaign_budget_optimization || daily > 0 === lifetime > 0) throw new AdportError2("INVALID_INPUT", "pinterest: campaign budget update requires CBO with exactly one existing daily/lifetime cap");
|
|
297
|
+
if (current.is_flexible_daily_budgets) throw new AdportError2("INVALID_INPUT", "pinterest: flexible daily budgets may exceed the daily amount; update this campaign in Ads Manager");
|
|
298
|
+
const cap = daily > 0 ? "daily_spend_cap" : "lifetime_spend_cap", from = daily || lifetime;
|
|
299
|
+
return {
|
|
300
|
+
summary: `Change Pinterest campaign "${current.name ?? current.id}" budget`,
|
|
301
|
+
changes: [`~ ${current.id} ${cap}: ${from} \u2192 ${input.budget_micros} micros`],
|
|
302
|
+
coercions: [],
|
|
303
|
+
budgetDeltas: [{ target: `campaign ${current.id} ${cap}`, fromMicros: from, toMicros: input.budget_micros }],
|
|
304
|
+
execute: () => this.write(accountId, "PATCH", { id: current.id, [cap]: input.budget_micros })
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
return {
|
|
308
|
+
summary: `Change Pinterest campaign "${current.name ?? current.id}" status`,
|
|
309
|
+
changes: [`~ ${current.id} status: ${current.status ?? "unknown"} \u2192 ${input.status}`],
|
|
310
|
+
coercions: [],
|
|
311
|
+
budgetDeltas: [],
|
|
312
|
+
execute: () => this.write(accountId, "PATCH", { id: current.id, status: input.status })
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
throw new AdportError2("INVALID_INPUT", `pinterest: unsupported write ${op.tool}`);
|
|
316
|
+
}
|
|
317
|
+
};
|
|
318
|
+
function normalize(row, requested) {
|
|
319
|
+
const mapped = {};
|
|
320
|
+
for (const [metric, field] of Object.entries(FIELDS)) {
|
|
321
|
+
const value = row[field];
|
|
322
|
+
if (value === null || value === void 0) continue;
|
|
323
|
+
const number = typeof value === "number" ? value : typeof value === "string" && /^\d+(?:\.\d+)?$/.test(value) ? Number(value) : NaN;
|
|
324
|
+
if (!Number.isFinite(number) || number < 0) throw new AdportError2("PROVIDER_ERROR", `pinterest: malformed ${field} metric`);
|
|
325
|
+
mapped[metric] = number / (metric === "spend" || metric === "conversion_value" ? 1e6 : 1);
|
|
326
|
+
}
|
|
327
|
+
for (const [metric, [numerator, denominator, factor]] of Object.entries(DERIVED)) {
|
|
328
|
+
if (mapped[numerator] !== void 0 && mapped[denominator] !== void 0) mapped[metric] = mapped[denominator] ? mapped[numerator] / mapped[denominator] * factor : 0;
|
|
329
|
+
}
|
|
330
|
+
return Object.fromEntries(requested.filter((metric) => mapped[metric] !== void 0).map((metric) => [metric, mapped[metric]]));
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// src/tools.ts
|
|
334
|
+
import { z as z4 } from "zod";
|
|
335
|
+
import { defineTool, guardedWriteTool } from "@adport/core";
|
|
336
|
+
function pinterestTools(provider) {
|
|
337
|
+
return [
|
|
338
|
+
defineTool({ name: "pinterest_list_campaigns", namespace: "pinterest", description: "List Pinterest campaigns, including archived and draft entities.", input: z4.object({ account_id: pinterestId }), annotations: { readOnly: true }, handler: (input) => provider.listCampaigns(input.account_id) }),
|
|
339
|
+
guardedWriteTool({ name: "pinterest_create_campaign", namespace: "pinterest", provider: "pinterest", kind: "create", description: "Create a Pinterest CBO campaign, paused by policy. Budgets are account-currency micros; lifetime budgets require an end time. Preview is local.", payload: createCampaignSchema }),
|
|
340
|
+
guardedWriteTool({ name: "pinterest_set_campaign_status", namespace: "pinterest", provider: "pinterest", kind: "update", description: "Pause or activate an existing Pinterest campaign.", payload: setStatusSchema }),
|
|
341
|
+
guardedWriteTool({ name: "pinterest_set_budget", namespace: "pinterest", provider: "pinterest", kind: "update", description: "Change an existing Pinterest CBO campaign budget in micros, preserving its daily/lifetime type.", payload: setBudgetSchema })
|
|
342
|
+
];
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
// src/index.ts
|
|
346
|
+
async function resolvePinterestCredentials(store) {
|
|
347
|
+
const data = (await store.get("pinterest"))?.data;
|
|
348
|
+
if (data?.client_id && data.client_secret && data.refresh_token) return {
|
|
349
|
+
clientId: data.client_id,
|
|
350
|
+
clientSecret: data.client_secret,
|
|
351
|
+
refreshToken: data.refresh_token,
|
|
352
|
+
onRefreshToken: async (refreshToken) => {
|
|
353
|
+
const latest = await store.get("pinterest");
|
|
354
|
+
if (latest) await store.set({ provider: "pinterest", source: latest.source, data: { ...latest.data, refresh_token: refreshToken } });
|
|
355
|
+
}
|
|
356
|
+
};
|
|
357
|
+
if (process.env.PINTEREST_CLIENT_ID && process.env.PINTEREST_CLIENT_SECRET && process.env.PINTEREST_REFRESH_TOKEN) return {
|
|
358
|
+
clientId: process.env.PINTEREST_CLIENT_ID,
|
|
359
|
+
clientSecret: process.env.PINTEREST_CLIENT_SECRET,
|
|
360
|
+
refreshToken: process.env.PINTEREST_REFRESH_TOKEN
|
|
361
|
+
};
|
|
362
|
+
return void 0;
|
|
363
|
+
}
|
|
364
|
+
async function createPinterestModule(store) {
|
|
365
|
+
const credentials = await resolvePinterestCredentials(store);
|
|
366
|
+
if (!credentials) return void 0;
|
|
367
|
+
const provider = new PinterestAdsProvider(new PinterestAdsClient(credentials));
|
|
368
|
+
return { provider, tools: pinterestTools(provider) };
|
|
369
|
+
}
|
|
370
|
+
export {
|
|
371
|
+
PINTEREST_API_BASE,
|
|
372
|
+
PINTEREST_TOKEN_URL,
|
|
373
|
+
PinterestAdsClient,
|
|
374
|
+
PinterestAdsProvider,
|
|
375
|
+
accountSchema,
|
|
376
|
+
buildPinterestAuthUrl,
|
|
377
|
+
campaignSchema,
|
|
378
|
+
createPinterestModule,
|
|
379
|
+
exchangePinterestCode,
|
|
380
|
+
pinterestTools,
|
|
381
|
+
resolvePinterestCredentials
|
|
382
|
+
};
|
|
383
|
+
//# 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 PINTEREST_API_BASE = 'https://api.pinterest.com/v5/';\nexport const PINTEREST_TOKEN_URL = `${PINTEREST_API_BASE}oauth/token`;\nexport interface PinterestCredentials {\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 buildPinterestAuthUrl(clientId: string, redirectUri: string, state: string): string {\n return `https://www.pinterest.com/oauth/?${new URLSearchParams({\n client_id: clientId, response_type: 'code', redirect_uri: redirectUri, state, scope: 'ads:read,ads:write',\n })}`;\n}\n\nasync function tokenRequest(credentials: Pick<PinterestCredentials, 'clientId' | 'clientSecret'>, body: URLSearchParams, fetchImpl: typeof fetch) {\n const response = await fetchImpl(PINTEREST_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', `pinterest: 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', 'pinterest: malformed OAuth response');\n return parsed.data;\n}\n\nexport async function exchangePinterestCode(input: { clientId: string; clientSecret: string; code: string; redirectUri: string }, fetchImpl: typeof fetch = fetch): Promise<string> {\n const token = await tokenRequest(input, new URLSearchParams({\n grant_type: 'authorization_code', code: input.code, redirect_uri: input.redirectUri, continuous_refresh: 'true',\n }), fetchImpl);\n if (!token.refresh_token) throw new AdportError('PROVIDER_ERROR', 'pinterest: OAuth exchange did not return a refresh token');\n return token.refresh_token;\n}\n\nexport class PinterestAdsClient {\n private token?: { value: string; expiresAt: number };\n private refreshToken: string;\n private refreshing?: Promise<string>;\n constructor(private readonly credentials: PinterestCredentials, private readonly fetchImpl: typeof fetch = fetch) {\n this.refreshToken = credentials.refreshToken;\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 private async request<T>(path: string, method: 'GET' | 'POST' | 'PATCH', schema: z.ZodType<T>, body?: unknown, params = new URLSearchParams(), retry = true): Promise<T> {\n if (!/^[a-z_]+(?:\\/[a-zA-Z0-9_-]+)*$/.test(path)) throw new AdportError('INVALID_INPUT', 'pinterest: invalid API resource path');\n const url = new URL(path, PINTEREST_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 app Trial/Standard access, ads scopes and ad-account permissions; reauthorization alone may not help.' : '';\n throw new AdportError('PROVIDER_ERROR', `pinterest: HTTP ${response.status}.${advice}`);\n }\n const parsed = schema.safeParse(await response.json());\n if (!parsed.success) throw new AdportError('PROVIDER_ERROR', 'pinterest: malformed API response');\n return parsed.data;\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 { PinterestAdsClient } from './client.js';\nimport { accountSchema, batchResponseSchema, campaignSchema, createCampaignSchema, entitySchema, entityStatus, pinterestId, setBudgetSchema, setStatusSchema } from './schemas.js';\n\ninterface Plan extends Omit<WritePreview, 'serverValidated'> { execute: () => Promise<string[]> }\nconst LEVEL = {\n account: { path: '', id: 'AD_ACCOUNT_ID', filter: '' },\n campaign: { path: 'campaigns', id: 'CAMPAIGN_ID', filter: 'campaign_ids' },\n ad_group: { path: 'ad_groups', id: 'AD_GROUP_ID', filter: 'ad_group_ids' },\n ad: { path: 'ads', id: 'AD_ID', filter: 'ad_ids' },\n} as const;\nconst FIELDS = { spend: 'SPEND_IN_MICRO_DOLLAR', impressions: 'PAID_IMPRESSION', clicks: 'OUTBOUND_CLICK_1', conversions: 'TOTAL_CHECKOUT', conversion_value: 'TOTAL_CHECKOUT_VALUE_IN_MICRO_DOLLAR' } 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 PinterestAdsProvider implements AdProvider {\n readonly id = 'pinterest';\n constructor(private readonly client: PinterestAdsClient) {}\n capabilities() { return { serverDryRun: false }; }\n standardActions(): StandardActions {\n return { pauseCampaign: (accountId, campaignId) => ({ tool: 'pinterest_set_campaign_status', input: { account_id: accountId, campaign_id: campaignId, status: 'PAUSED' } }) };\n }\n private async collect<T extends { id: string }>(path: string, schema: z.ZodType<T>, params = new URLSearchParams()): Promise<T[]> {\n const result: T[] = [], bookmarks = new Set<string>(), entities = new Set<string>();\n const query = new URLSearchParams(params);\n query.set('page_size', '250');\n const pageSchema = z.object({ items: z.array(schema), bookmark: z.string().nullable().optional() });\n while (true) {\n const page = await this.client.get(path, pageSchema, query);\n for (const item of page.items) {\n if (entities.has(item.id)) throw new AdportError('PROVIDER_ERROR', 'pinterest: pagination repeated an entity');\n entities.add(item.id); result.push(item);\n }\n if (!page.bookmark) return result;\n if (bookmarks.has(page.bookmark) || bookmarks.size >= 1000) throw new AdportError('PROVIDER_ERROR', 'pinterest: pagination did not terminate');\n bookmarks.add(page.bookmark); query.set('bookmark', page.bookmark);\n }\n }\n async listAccounts(): Promise<Account[]> {\n return (await this.collect('ad_accounts', accountSchema)).map(a => ({ provider: this.id, id: a.id, name: a.name ?? a.id, ...(a.currency ? { currency: a.currency } : {}) }));\n }\n async listCampaigns(accountId: string) {\n return this.listEntities(accountId, 'campaigns', campaignSchema);\n }\n private async listEntities<T extends z.infer<typeof entitySchema>>(accountId: string, collection: string, schema: z.ZodType<T>) {\n const params = new URLSearchParams();\n // Include archived entities so historical reporting isn't silently filtered\n // to the API's ACTIVE/PAUSED default. Arrays use OpenAPI form/explode.\n for (const status of entityStatus.options) params.append('entity_statuses', status);\n const rows = await this.collect(`ad_accounts/${pinterestId.parse(accountId)}/${collection}`, schema, params);\n if (rows.some(row => row.ad_account_id !== accountId)) throw new AdportError('PROVIDER_ERROR', 'pinterest: entity account mismatch');\n return rows;\n }\n async getCampaign(accountId: string, campaignId: string) {\n const result = await this.client.get(`ad_accounts/${pinterestId.parse(accountId)}/campaigns/${pinterestId.parse(campaignId)}`, campaignSchema);\n if (result.id !== campaignId || result.ad_account_id !== accountId) throw new AdportError('PROVIDER_ERROR', 'pinterest: campaign account/ID mismatch');\n return result;\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', 'pinterest: 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', 'pinterest: report limit must be a positive integer');\n const level = LEVEL[query.level], 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', 'pinterest: report requires at least one supported metric');\n const rows: ReportRow[] = [];\n for (const id of [...new Set(query.accountIds ?? (await this.listAccounts()).map(a => a.id))]) {\n const accountId = pinterestId.parse(id), base = `ad_accounts/${accountId}`;\n const entities = query.level === 'account'\n ? [await this.client.get(base, accountSchema)]\n : await this.listEntities(accountId, level.path, entitySchema);\n if (query.level === 'account' && entities.some(e => e.id !== accountId)) throw new AdportError('PROVIDER_ERROR', 'pinterest: account ID mismatch');\n const lookup = new Map(entities.map(e => [e.id, e]));\n const seen = new Set<string>();\n for (let offset = 0; offset < entities.length; offset += 250) {\n const batch = entities.slice(offset, offset + 250), allowed = new Set(batch.map(e => e.id));\n const params = new URLSearchParams({\n start_date: start, end_date: end, granularity: 'TOTAL', columns: [level.id, ...fields].join(','),\n click_window_days: '30', view_window_days: '1', conversion_report_time: 'TIME_OF_AD_ACTION',\n });\n if (level.filter) for (const entity of batch) params.append(level.filter, entity.id);\n const data = await this.client.get(`${base}/${level.path ? `${level.path}/` : ''}analytics`, z.array(z.record(z.string(), z.unknown())), params);\n for (const row of data) {\n const entityId = pinterestId.parse(row[level.id]);\n if (!allowed.has(entityId) || seen.has(entityId)) throw new AdportError('PROVIDER_ERROR', 'pinterest: incorrectly scoped or duplicate report row');\n seen.add(entityId);\n const entity = lookup.get(entityId)!;\n rows.push({ provider: this.id, accountId, entity: { level: query.level, id: entityId, name: entity.name ?? entityId, ...(typeof entity.status === 'string' ? { status: entity.status } : {}) }, metrics: normalize(row, query.metrics) });\n if (rows.length > limit) return { rows: rows.slice(0, limit), truncated: true };\n }\n }\n }\n return { rows };\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 private async write(accountId: string, method: 'POST' | 'PATCH', body: Record<string, unknown>) {\n const result = await this.client.mutate(`ad_accounts/${accountId}/campaigns`, method, [body], batchResponseSchema);\n const item = result.items[0];\n if (result.items.length !== 1 || !item?.data || item.exceptions?.length) throw new AdportError('PROVIDER_ERROR', 'pinterest: campaign batch item failed; inspect account before retrying');\n const parsed = campaignSchema.safeParse(item.data);\n if (!parsed.success) throw new AdportError('PROVIDER_ERROR', 'pinterest: campaign batch returned incomplete data; inspect account before retrying');\n const data = parsed.data;\n if (data.ad_account_id !== accountId || (body.id && data.id !== body.id)\n || Object.entries(body).some(([key, value]) => ['status', 'daily_spend_cap', 'lifetime_spend_cap'].includes(key) && data[key] !== value)) {\n throw new AdportError('PROVIDER_ERROR', 'pinterest: campaign write response mismatch; inspect before retrying');\n }\n return [data.id];\n }\n private async plan(op: WriteOperation, guard: WriteGuard): Promise<Plan> {\n const accountId = pinterestId.parse(op.accountId);\n if (op.provider !== this.id) throw new AdportError('INVALID_INPUT', 'pinterest: provider mismatch');\n if (op.tool === 'pinterest_create_campaign' && op.kind === 'create') {\n const input = createCampaignSchema.parse(op.payload);\n const { budget_type, budget_micros, ...rest } = input;\n const status = guard.forcePausedCreation ? 'PAUSED' : input.status;\n const cap = budget_type === 'DAILY' ? 'daily_spend_cap' : 'lifetime_spend_cap';\n const body = { ...rest, status, [cap]: budget_micros, is_campaign_budget_optimization: true, is_flexible_daily_budgets: false };\n return {\n summary: `Create Pinterest campaign \"${input.name}\"`, changes: [`+ ${JSON.stringify(body)}`],\n coercions: status !== input.status ? ['status coerced to PAUSED by policy (paused_creation)'] : [],\n budgetDeltas: [{ target: `new campaign ${budget_type} budget`, toMicros: budget_micros }],\n execute: () => this.write(accountId, 'POST', body),\n };\n }\n if (op.kind === 'update' && ['pinterest_set_campaign_status', 'pinterest_set_budget'].includes(op.tool)) {\n const input = op.tool === 'pinterest_set_budget' ? setBudgetSchema.parse(op.payload) : setStatusSchema.parse(op.payload);\n const current = await this.getCampaign(accountId, input.campaign_id);\n if ('budget_micros' in input) {\n const daily = current.daily_spend_cap ?? 0, lifetime = current.lifetime_spend_cap ?? 0;\n if (!current.is_campaign_budget_optimization || (daily > 0) === (lifetime > 0)) throw new AdportError('INVALID_INPUT', 'pinterest: campaign budget update requires CBO with exactly one existing daily/lifetime cap');\n if (current.is_flexible_daily_budgets) throw new AdportError('INVALID_INPUT', 'pinterest: flexible daily budgets may exceed the daily amount; update this campaign in Ads Manager');\n const cap = daily > 0 ? 'daily_spend_cap' : 'lifetime_spend_cap', from = daily || lifetime;\n return {\n summary: `Change Pinterest campaign \"${current.name ?? current.id}\" budget`, changes: [`~ ${current.id} ${cap}: ${from} → ${input.budget_micros} micros`], coercions: [],\n budgetDeltas: [{ target: `campaign ${current.id} ${cap}`, fromMicros: from, toMicros: input.budget_micros }],\n execute: () => this.write(accountId, 'PATCH', { id: current.id, [cap]: input.budget_micros }),\n };\n }\n return {\n summary: `Change Pinterest campaign \"${current.name ?? current.id}\" status`, changes: [`~ ${current.id} status: ${current.status ?? 'unknown'} → ${input.status}`], coercions: [], budgetDeltas: [],\n execute: () => this.write(accountId, 'PATCH', { id: current.id, status: input.status }),\n };\n }\n throw new AdportError('INVALID_INPUT', `pinterest: unsupported write ${op.tool}`);\n }\n}\n\nfunction normalize(row: Record<string, unknown>, requested: MetricName[]) {\n const mapped: Partial<Record<MetricName, number>> = {};\n for (const [metric, field] of Object.entries(FIELDS)) {\n const value = row[field];\n if (value === null || value === undefined) continue;\n const number = typeof value === 'number' ? value : typeof value === 'string' && /^\\d+(?:\\.\\d+)?$/.test(value) ? Number(value) : NaN;\n if (!Number.isFinite(number) || number < 0) throw new AdportError('PROVIDER_ERROR', `pinterest: malformed ${field} metric`);\n // MICRO_DOLLAR is Pinterest's historical field name; units are always\n // micros of the advertiser's account currency, not necessarily USD.\n mapped[metric as MetricName] = number / (metric === 'spend' || metric === 'conversion_value' ? 1_000_000 : 1);\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// Pinterest's official OpenAPI 5.28.0, reviewed 2026-08-31.\nexport const pinterestId = z.string().regex(/^\\d+$/).max(18);\nexport const entityStatus = z.enum(['ACTIVE', 'PAUSED', 'ARCHIVED', 'DRAFT', 'DELETED_DRAFT']);\nconst micros = z.number().int().nonnegative().safe();\nexport const accountSchema = z.looseObject({ id: pinterestId, name: z.string().optional(), currency: z.string().optional() });\nexport const entitySchema = z.looseObject({ id: pinterestId, ad_account_id: pinterestId, name: z.string().nullable().optional(), status: entityStatus.optional() });\nexport const campaignSchema = entitySchema.extend({\n daily_spend_cap: micros.nullable().optional(), lifetime_spend_cap: micros.nullable().optional(),\n is_campaign_budget_optimization: z.boolean().nullable().optional(),\n is_flexible_daily_budgets: z.boolean().nullable().optional(),\n});\nexport const batchResponseSchema = z.object({ items: z.array(z.object({\n data: campaignSchema.partial().optional(), exceptions: z.array(z.unknown()).optional(),\n})) });\nexport const createCampaignSchema = z.object({\n name: z.string().trim().min(1).max(255),\n objective_type: z.enum(['AWARENESS', 'CONSIDERATION', 'WEB_CONVERSION', 'CATALOG_SALES', 'VIDEO_COMPLETION', 'APP_INSTALL', 'SALES', 'LEADS', 'CTV_CONSIDERATION']),\n status: z.enum(['PAUSED', 'ACTIVE']).default('PAUSED'),\n budget_type: z.enum(['DAILY', 'LIFETIME']).default('DAILY'),\n budget_micros: micros.positive(),\n start_time: z.number().int().positive().safe().optional(),\n end_time: z.number().int().positive().safe().optional(),\n app_id: z.string().min(1).optional(), app_platform: z.enum(['IOS', 'ANDROID']).optional(),\n}).superRefine((value, ctx) => {\n if (value.budget_type === 'LIFETIME' && !value.end_time) ctx.addIssue({ code: 'custom', path: ['end_time'], message: 'Lifetime campaign budgets require an end time.' });\n if (value.start_time && value.end_time && value.end_time <= value.start_time) ctx.addIssue({ code: 'custom', path: ['end_time'], message: 'End time must be after start time.' });\n if (value.objective_type === 'APP_INSTALL' && (!value.app_id || !value.app_platform)) ctx.addIssue({ code: 'custom', path: ['app_id'], message: 'APP_INSTALL requires app_id and app_platform and Pinterest beta access.' });\n});\nexport const setStatusSchema = z.object({ campaign_id: pinterestId, status: z.enum(['PAUSED', 'ACTIVE']) });\nexport const setBudgetSchema = z.object({ campaign_id: pinterestId, budget_micros: micros.positive() });\n","import { z } from 'zod';\nimport { defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { createCampaignSchema, pinterestId, setBudgetSchema, setStatusSchema } from './schemas.js';\nimport type { PinterestAdsProvider } from './provider.js';\n\nexport function pinterestTools(provider: PinterestAdsProvider): AnyToolDefinition[] {\n return [\n defineTool({ name: 'pinterest_list_campaigns', namespace: 'pinterest', description: 'List Pinterest campaigns, including archived and draft entities.', input: z.object({ account_id: pinterestId }), annotations: { readOnly: true }, handler: input => provider.listCampaigns(input.account_id) }),\n guardedWriteTool({ name: 'pinterest_create_campaign', namespace: 'pinterest', provider: 'pinterest', kind: 'create', description: 'Create a Pinterest CBO campaign, paused by policy. Budgets are account-currency micros; lifetime budgets require an end time. Preview is local.', payload: createCampaignSchema }),\n guardedWriteTool({ name: 'pinterest_set_campaign_status', namespace: 'pinterest', provider: 'pinterest', kind: 'update', description: 'Pause or activate an existing Pinterest campaign.', payload: setStatusSchema }),\n guardedWriteTool({ name: 'pinterest_set_budget', namespace: 'pinterest', provider: 'pinterest', kind: 'update', description: 'Change an existing Pinterest CBO campaign budget in micros, preserving its daily/lifetime type.', payload: setBudgetSchema }),\n ];\n}\n","import type { CredentialStore, ProviderModule } from '@adport/core';\nimport { PinterestAdsClient, type PinterestCredentials } from './client.js';\nimport { PinterestAdsProvider } from './provider.js';\nimport { pinterestTools } from './tools.js';\nexport { PinterestAdsClient, PINTEREST_API_BASE, PINTEREST_TOKEN_URL, buildPinterestAuthUrl, exchangePinterestCode, type PinterestCredentials } from './client.js';\nexport { PinterestAdsProvider } from './provider.js';\nexport { pinterestTools } from './tools.js';\nexport { accountSchema, campaignSchema } from './schemas.js';\n\nexport async function resolvePinterestCredentials(store: CredentialStore): Promise<PinterestCredentials | undefined> {\n const data = (await store.get('pinterest'))?.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('pinterest');\n if (latest) await store.set({ provider: 'pinterest', source: latest.source, data: { ...latest.data, refresh_token: refreshToken } });\n },\n };\n if (process.env.PINTEREST_CLIENT_ID && process.env.PINTEREST_CLIENT_SECRET && process.env.PINTEREST_REFRESH_TOKEN) return {\n clientId: process.env.PINTEREST_CLIENT_ID, clientSecret: process.env.PINTEREST_CLIENT_SECRET, refreshToken: process.env.PINTEREST_REFRESH_TOKEN,\n };\n return undefined;\n}\nexport async function createPinterestModule(store: CredentialStore): Promise<ProviderModule | undefined> {\n const credentials = await resolvePinterestCredentials(store);\n if (!credentials) return undefined;\n const provider = new PinterestAdsProvider(new PinterestAdsClient(credentials));\n return { provider, tools: pinterestTools(provider) };\n}\n"],"mappings":";AAAA,SAAS,mBAAmB;AAC5B,SAAS,SAAS;AAEX,IAAM,qBAAqB;AAC3B,IAAM,sBAAsB,GAAG,kBAAkB;AAOxD,IAAM,cAAc,EAAE,OAAO;AAAA,EAC3B,cAAc,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EAAG,YAAY,EAAE,OAAO,EAAE,SAAS;AAAA,EACjE,eAAe,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS;AAC5C,CAAC;AAEM,SAAS,sBAAsB,UAAkB,aAAqB,OAAuB;AAClG,SAAO,oCAAoC,IAAI,gBAAgB;AAAA,IAC7D,WAAW;AAAA,IAAU,eAAe;AAAA,IAAQ,cAAc;AAAA,IAAa;AAAA,IAAO,OAAO;AAAA,EACvF,CAAC,CAAC;AACJ;AAEA,eAAe,aAAa,aAAsE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IAAI,uBAAuB,QAAQ,IAAI,2BAA2B,QAAQ,IAAI,wBAAyB,QAAO;AAAA,IACxH,UAAU,QAAQ,IAAI;AAAA,IAAqB,cAAc,QAAQ,IAAI;AAAA,IAAyB,cAAc,QAAQ,IAAI;AAAA,EAC1H;AACA,SAAO;AACT;AACA,eAAsB,sBAAsB,OAA6D;AACvG,QAAM,cAAc,MAAM,4BAA4B,KAAK;AAC3D,MAAI,CAAC,YAAa,QAAO;AACzB,QAAM,WAAW,IAAI,qBAAqB,IAAI,mBAAmB,WAAW,CAAC;AAC7E,SAAO,EAAE,UAAU,OAAO,eAAe,QAAQ,EAAE;AACrD;","names":["z","AdportError","z","z","AdportError","z","z"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@adport/provider-pinterest",
|
|
3
|
+
"version": "0.6.0",
|
|
4
|
+
"description": "Pinterest 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
|
+
}
|