@adport/provider-microsoft 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Yannick Westermann
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,102 @@
1
+ import { AdProvider, ProviderCapabilities, StandardActions, Account, NormalizedQuery, Report, WriteOperation, WriteGuard, WritePreview, WriteResult, AnyToolDefinition, CredentialStore, ProviderModule } from '@adport/core';
2
+
3
+ interface MicrosoftCredentials {
4
+ developerToken: string;
5
+ clientId: string;
6
+ refreshToken: string;
7
+ /** Only for confidential (web) apps; native/CLI public clients have no secret. */
8
+ clientSecret?: string;
9
+ sandbox?: boolean;
10
+ }
11
+ declare const MSADS_SCOPE = "https://ads.microsoft.com/msads.manage offline_access";
12
+ /** Published universal sandbox developer token (anyone may use it in sandbox). */
13
+ declare const SANDBOX_DEVELOPER_TOKEN = "BBD37VB98";
14
+ type MicrosoftService = 'campaign' | 'customer' | 'reporting';
15
+ interface RequestScope {
16
+ /** Manager account (customer) id header. */
17
+ customerId?: string;
18
+ /** Ad account id header. */
19
+ customerAccountId?: string;
20
+ }
21
+ /**
22
+ * Microsoft Advertising REST v13 client. Public-client refresh tokens rotate —
23
+ * onRefreshTokenRotated lets the credential store persist the replacement.
24
+ */
25
+ declare class MicrosoftAdsClient {
26
+ private readonly credentials;
27
+ private readonly onRefreshTokenRotated?;
28
+ private readonly fetchImpl;
29
+ private accessToken?;
30
+ private refreshToken;
31
+ readonly sandbox: boolean;
32
+ constructor(credentials: MicrosoftCredentials, onRefreshTokenRotated?: ((token: string) => Promise<void>) | undefined, fetchImpl?: typeof fetch);
33
+ getAccessToken(): Promise<string>;
34
+ request<T>(service: MicrosoftService, method: 'GET' | 'POST' | 'PUT', path: string, body: unknown, scope?: RequestScope): Promise<T>;
35
+ /** Plain authorized download (report files); returns raw bytes. */
36
+ download(url: string): Promise<Uint8Array>;
37
+ }
38
+ interface BatchErrorItem {
39
+ Code?: number;
40
+ ErrorCode?: string;
41
+ Message?: string;
42
+ FieldPath?: string;
43
+ Index?: number;
44
+ Details?: string;
45
+ Detail?: string;
46
+ }
47
+ /**
48
+ * REST errors are serialized fault objects: ApiFaultDetail
49
+ * {OperationErrors, BatchErrors}, AdApiFaultDetail {Errors}, plus TrackingId.
50
+ */
51
+ declare function formatMicrosoftError(status: number, raw: string): string;
52
+ declare function formatPartialErrors(partialErrors: BatchErrorItem[] | undefined): string | undefined;
53
+
54
+ /** DailyBudget is a double in whole account-currency units. */
55
+ declare const UNITS_TO_MICROS = 1000000;
56
+ interface MicrosoftCampaign {
57
+ Id: number | string;
58
+ Name: string;
59
+ Status: string;
60
+ DailyBudget?: number;
61
+ BudgetType?: string;
62
+ BudgetId?: number | string | null;
63
+ TimeZone?: string;
64
+ CampaignType?: string;
65
+ }
66
+ declare class MicrosoftAdsProvider implements AdProvider {
67
+ private readonly client;
68
+ private readonly options;
69
+ readonly id = "microsoft";
70
+ /** accountId → parent customer id, learned from SearchAccounts. */
71
+ private customerIds;
72
+ constructor(client: MicrosoftAdsClient, options?: {
73
+ pollIntervalMs?: number;
74
+ pollMaxAttempts?: number;
75
+ });
76
+ capabilities(): ProviderCapabilities;
77
+ standardActions(): StandardActions;
78
+ listAccounts(): Promise<Account[]>;
79
+ private scopeFor;
80
+ listCampaigns(accountId: string): Promise<MicrosoftCampaign[]>;
81
+ report(query: NormalizedQuery): Promise<Report>;
82
+ private campaignReport;
83
+ private parseReport;
84
+ previewWrite(op: WriteOperation, guard: WriteGuard): Promise<WritePreview>;
85
+ applyWrite(op: WriteOperation, guard: WriteGuard): Promise<WriteResult>;
86
+ private plan;
87
+ private planCreateCampaign;
88
+ private lookupCampaign;
89
+ private updateCampaign;
90
+ private planSetStatus;
91
+ private planSetBudget;
92
+ }
93
+
94
+ declare function microsoftTools(provider: MicrosoftAdsProvider): AnyToolDefinition[];
95
+
96
+ /** Minimal RFC-4180-ish CSV parser (quotes, escaped quotes, CRLF). */
97
+ declare function parseCsv(text: string): string[][];
98
+
99
+ declare function resolveMicrosoftCredentials(store: CredentialStore): Promise<MicrosoftCredentials | undefined>;
100
+ declare function createMicrosoftModule(store: CredentialStore): Promise<ProviderModule | undefined>;
101
+
102
+ export { MSADS_SCOPE, MicrosoftAdsClient, MicrosoftAdsProvider, type MicrosoftCredentials, SANDBOX_DEVELOPER_TOKEN, UNITS_TO_MICROS, createMicrosoftModule, formatMicrosoftError, formatPartialErrors, microsoftTools, parseCsv, resolveMicrosoftCredentials };
package/dist/index.js ADDED
@@ -0,0 +1,558 @@
1
+ // src/client.ts
2
+ import { AdportError } from "@adport/core";
3
+ var TOKEN_URL = "https://login.microsoftonline.com/common/oauth2/v2.0/token";
4
+ var MSADS_SCOPE = "https://ads.microsoft.com/msads.manage offline_access";
5
+ var SANDBOX_DEVELOPER_TOKEN = "BBD37VB98";
6
+ function hosts(sandbox) {
7
+ const infix = sandbox ? ".sandbox" : "";
8
+ return {
9
+ campaign: `https://campaign.api${infix}.bingads.microsoft.com/CampaignManagement/v13`,
10
+ customer: `https://clientcenter.api${infix}.bingads.microsoft.com/CustomerManagement/v13`,
11
+ reporting: `https://reporting.api${infix}.bingads.microsoft.com/Reporting/v13`
12
+ };
13
+ }
14
+ var MicrosoftAdsClient = class {
15
+ constructor(credentials, onRefreshTokenRotated, fetchImpl = fetch) {
16
+ this.credentials = credentials;
17
+ this.onRefreshTokenRotated = onRefreshTokenRotated;
18
+ this.fetchImpl = fetchImpl;
19
+ this.refreshToken = credentials.refreshToken;
20
+ this.sandbox = credentials.sandbox ?? false;
21
+ }
22
+ credentials;
23
+ onRefreshTokenRotated;
24
+ fetchImpl;
25
+ accessToken;
26
+ refreshToken;
27
+ sandbox;
28
+ async getAccessToken() {
29
+ if (this.accessToken && this.accessToken.expiresAt > Date.now()) {
30
+ return this.accessToken.token;
31
+ }
32
+ const body = new URLSearchParams({
33
+ client_id: this.credentials.clientId,
34
+ scope: "https://ads.microsoft.com/msads.manage",
35
+ refresh_token: this.refreshToken,
36
+ grant_type: "refresh_token"
37
+ });
38
+ if (this.credentials.clientSecret) body.set("client_secret", this.credentials.clientSecret);
39
+ const response = await this.fetchImpl(TOKEN_URL, {
40
+ method: "POST",
41
+ headers: { "content-type": "application/x-www-form-urlencoded" },
42
+ body
43
+ });
44
+ const raw = await response.text();
45
+ if (!response.ok) {
46
+ throw new AdportError(
47
+ "PROVIDER_ERROR",
48
+ `Microsoft OAuth refresh failed (${response.status}). Public-client refresh tokens expire after ~90 days \u2014 re-run \`adport connect microsoft\`.`,
49
+ safeJson(raw)
50
+ );
51
+ }
52
+ const data = JSON.parse(raw);
53
+ this.accessToken = { token: data.access_token, expiresAt: Date.now() + (data.expires_in - 60) * 1e3 };
54
+ if (data.refresh_token && data.refresh_token !== this.refreshToken) {
55
+ this.refreshToken = data.refresh_token;
56
+ await this.onRefreshTokenRotated?.(data.refresh_token);
57
+ }
58
+ return this.accessToken.token;
59
+ }
60
+ async request(service, method, path, body, scope = {}) {
61
+ const token = await this.getAccessToken();
62
+ const headers = {
63
+ authorization: `Bearer ${token}`,
64
+ DeveloperToken: this.sandbox ? SANDBOX_DEVELOPER_TOKEN : this.credentials.developerToken,
65
+ "content-type": "application/json"
66
+ };
67
+ if (scope.customerId) headers.CustomerId = scope.customerId;
68
+ if (scope.customerAccountId) headers.CustomerAccountId = scope.customerAccountId;
69
+ const response = await this.fetchImpl(`${hosts(this.sandbox)[service]}/${path.replace(/^\//, "")}`, {
70
+ method,
71
+ headers,
72
+ body: body === void 0 ? void 0 : JSON.stringify(body)
73
+ });
74
+ const raw = await response.text();
75
+ if (!response.ok) {
76
+ throw new AdportError("PROVIDER_ERROR", formatMicrosoftError(response.status, raw), safeJson(raw));
77
+ }
78
+ return raw ? JSON.parse(raw) : {};
79
+ }
80
+ /** Plain authorized download (report files); returns raw bytes. */
81
+ async download(url) {
82
+ const response = await this.fetchImpl(url, {});
83
+ if (!response.ok) {
84
+ throw new AdportError("PROVIDER_ERROR", `Microsoft report download failed (HTTP ${response.status})`);
85
+ }
86
+ return new Uint8Array(await response.arrayBuffer());
87
+ }
88
+ };
89
+ function safeJson(raw) {
90
+ try {
91
+ return JSON.parse(raw);
92
+ } catch {
93
+ return raw;
94
+ }
95
+ }
96
+ function formatMicrosoftError(status, raw) {
97
+ const parsed = safeJson(raw);
98
+ if (!parsed || typeof parsed !== "object" || !parsed.OperationErrors && !parsed.Errors && !parsed.BatchErrors) {
99
+ return `Microsoft Advertising API error (HTTP ${status})`;
100
+ }
101
+ const items = [...parsed.OperationErrors ?? [], ...parsed.BatchErrors ?? [], ...parsed.Errors ?? []];
102
+ const lines = items.map((e) => {
103
+ const where = e.Index !== void 0 ? ` [item ${e.Index}${e.FieldPath ? ` ${e.FieldPath}` : ""}]` : "";
104
+ return `${e.Code ?? "?"} ${e.ErrorCode ?? ""}: ${e.Message ?? e.Details ?? e.Detail ?? ""}${where}`;
105
+ });
106
+ let message = `Microsoft Advertising API error (HTTP ${status}, ${parsed.Type ?? "fault"}):
107
+ ${lines.join("\n ")}`;
108
+ if (items.some((e) => e.Code === 105)) {
109
+ message += "\n Code 105 InvalidCredentials: check the developer token matches the environment (sandbox vs production).";
110
+ }
111
+ if (items.some((e) => e.Code === 117)) {
112
+ message += "\n Code 117 CallRateExceeded: wait 60s before retrying.";
113
+ }
114
+ if (parsed.TrackingId) message += ` [TrackingId: ${parsed.TrackingId}]`;
115
+ return message;
116
+ }
117
+ function formatPartialErrors(partialErrors) {
118
+ if (!partialErrors || partialErrors.length === 0) return void 0;
119
+ return partialErrors.map((e) => `item ${e.Index ?? "?"}: ${e.Code ?? ""} ${e.ErrorCode ?? ""} ${e.Message ?? ""}${e.FieldPath ? ` (${e.FieldPath})` : ""}`).join("; ");
120
+ }
121
+
122
+ // src/provider.ts
123
+ import {
124
+ AdportError as AdportError2,
125
+ resolveDateRange
126
+ } from "@adport/core";
127
+ import { unzipSync } from "fflate";
128
+
129
+ // src/csv.ts
130
+ function parseCsv(text) {
131
+ const rows = [];
132
+ let row = [];
133
+ let field = "";
134
+ let inQuotes = false;
135
+ for (let i = 0; i < text.length; i++) {
136
+ const char = text[i];
137
+ if (inQuotes) {
138
+ if (char === '"') {
139
+ if (text[i + 1] === '"') {
140
+ field += '"';
141
+ i++;
142
+ } else {
143
+ inQuotes = false;
144
+ }
145
+ } else {
146
+ field += char;
147
+ }
148
+ continue;
149
+ }
150
+ if (char === '"') {
151
+ inQuotes = true;
152
+ } else if (char === ",") {
153
+ row.push(field);
154
+ field = "";
155
+ } else if (char === "\n" || char === "\r") {
156
+ if (char === "\r" && text[i + 1] === "\n") i++;
157
+ row.push(field);
158
+ field = "";
159
+ if (row.length > 1 || row[0] !== "") rows.push(row);
160
+ row = [];
161
+ } else {
162
+ field += char;
163
+ }
164
+ }
165
+ if (field !== "" || row.length > 0) {
166
+ row.push(field);
167
+ if (row.length > 1 || row[0] !== "") rows.push(row);
168
+ }
169
+ return rows;
170
+ }
171
+
172
+ // src/provider.ts
173
+ var UNITS_TO_MICROS = 1e6;
174
+ var MicrosoftAdsProvider = class {
175
+ constructor(client, options = {}) {
176
+ this.client = client;
177
+ this.options = options;
178
+ }
179
+ client;
180
+ options;
181
+ id = "microsoft";
182
+ /** accountId → parent customer id, learned from SearchAccounts. */
183
+ customerIds = /* @__PURE__ */ new Map();
184
+ capabilities() {
185
+ return { serverDryRun: false };
186
+ }
187
+ standardActions() {
188
+ return {
189
+ pauseCampaign: (accountId, campaignId) => ({
190
+ tool: "microsoft_set_campaign_status",
191
+ input: { account_id: accountId, campaign_id: campaignId, status: "Paused" }
192
+ })
193
+ };
194
+ }
195
+ async listAccounts() {
196
+ const user = await this.client.request(
197
+ "customer",
198
+ "POST",
199
+ "User/Query",
200
+ { UserId: null }
201
+ );
202
+ const userId = user.User?.Id;
203
+ if (userId === void 0) {
204
+ throw new AdportError2("PROVIDER_ERROR", "microsoft: GetUser returned no user id");
205
+ }
206
+ const search = await this.client.request("customer", "POST", "Accounts/Search", {
207
+ Predicates: [{ Field: "UserId", Operator: "Equals", Value: String(userId) }],
208
+ PageInfo: { Index: 0, Size: 100 }
209
+ });
210
+ const accounts = search.Accounts ?? [];
211
+ for (const account of accounts) {
212
+ if (account.ParentCustomerId !== void 0) {
213
+ this.customerIds.set(String(account.Id), String(account.ParentCustomerId));
214
+ }
215
+ }
216
+ return accounts.map((a) => ({
217
+ provider: this.id,
218
+ id: String(a.Id),
219
+ name: a.Name ?? a.Number ?? String(a.Id),
220
+ currency: a.CurrencyCode,
221
+ status: a.AccountLifeCycleStatus
222
+ }));
223
+ }
224
+ async scopeFor(accountId) {
225
+ if (!this.customerIds.has(accountId)) await this.listAccounts();
226
+ return { customerId: this.customerIds.get(accountId), customerAccountId: accountId };
227
+ }
228
+ async listCampaigns(accountId) {
229
+ const scope = await this.scopeFor(accountId);
230
+ const data = await this.client.request(
231
+ "campaign",
232
+ "POST",
233
+ "Campaigns/QueryByAccountId",
234
+ { AccountId: accountId, ReturnAdditionalFields: null },
235
+ scope
236
+ );
237
+ return data.Campaigns ?? [];
238
+ }
239
+ async report(query) {
240
+ if (query.level !== "campaign" && query.level !== "account") {
241
+ throw new AdportError2("INVALID_INPUT", "microsoft: report supports campaign and account levels in v0");
242
+ }
243
+ const range = resolveDateRange(query.dateRange);
244
+ const accountIds = query.accountIds ?? (await this.listAccounts()).map((a) => a.id);
245
+ const rows = [];
246
+ for (const accountId of accountIds) {
247
+ rows.push(...await this.campaignReport(accountId, range.start, range.end, query));
248
+ }
249
+ return { rows };
250
+ }
251
+ async campaignReport(accountId, start, end, query) {
252
+ const scope = await this.scopeFor(accountId);
253
+ const toDate = (iso) => {
254
+ const [year, month, day] = iso.split("-").map(Number);
255
+ return { Day: day, Month: month, Year: year };
256
+ };
257
+ const submit = await this.client.request(
258
+ "reporting",
259
+ "POST",
260
+ "GenerateReport/Submit",
261
+ {
262
+ ReportRequest: {
263
+ Type: "CampaignPerformanceReportRequest",
264
+ Format: "Csv",
265
+ FormatVersion: "2.0",
266
+ ReportName: "adport campaign report",
267
+ ExcludeReportHeader: true,
268
+ ExcludeReportFooter: true,
269
+ ExcludeColumnHeaders: false,
270
+ ReturnOnlyCompleteData: false,
271
+ Aggregation: "Summary",
272
+ Columns: ["CampaignId", "CampaignName", "CampaignStatus", "Spend", "Impressions", "Clicks", "Conversions", "Revenue"],
273
+ Scope: { AccountIds: [accountId] },
274
+ Time: { CustomDateRangeStart: toDate(start), CustomDateRangeEnd: toDate(end) }
275
+ }
276
+ },
277
+ scope
278
+ );
279
+ if (!submit.ReportRequestId) {
280
+ throw new AdportError2("PROVIDER_ERROR", "microsoft: SubmitGenerateReport returned no ReportRequestId");
281
+ }
282
+ const maxAttempts = this.options.pollMaxAttempts ?? 30;
283
+ const interval = this.options.pollIntervalMs ?? 5e3;
284
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
285
+ const poll = await this.client.request("reporting", "POST", "GenerateReport/Poll", { ReportRequestId: submit.ReportRequestId }, scope);
286
+ const status = poll.ReportRequestStatus?.Status;
287
+ if (status === "Error") {
288
+ throw new AdportError2("PROVIDER_ERROR", "microsoft: report generation failed (Status: Error)");
289
+ }
290
+ if (status === "Success") {
291
+ const url = poll.ReportRequestStatus?.ReportDownloadUrl;
292
+ if (!url) return [];
293
+ return this.parseReport(await this.client.download(url), accountId, query);
294
+ }
295
+ await new Promise((resolve) => setTimeout(resolve, interval));
296
+ }
297
+ throw new AdportError2("PROVIDER_ERROR", `microsoft: report not ready after ${maxAttempts} polls`);
298
+ }
299
+ parseReport(zipBytes, accountId, query) {
300
+ const files = unzipSync(zipBytes);
301
+ const first = Object.values(files)[0];
302
+ if (!first) return [];
303
+ const rows = parseCsv(new TextDecoder().decode(first));
304
+ if (rows.length < 2) return [];
305
+ const header = rows[0];
306
+ const index = (name) => header.indexOf(name);
307
+ const out = [];
308
+ for (const row of rows.slice(1)) {
309
+ const value = (name) => {
310
+ const i = index(name);
311
+ return i >= 0 ? row[i] ?? "" : "";
312
+ };
313
+ const spend = Number(value("Spend") || 0);
314
+ const impressions = Number(value("Impressions") || 0);
315
+ const clicks = Number(value("Clicks") || 0);
316
+ const conversions = Number(value("Conversions") || 0);
317
+ const revenue = Number(value("Revenue") || 0);
318
+ const all = {
319
+ spend: round2(spend),
320
+ impressions,
321
+ clicks,
322
+ conversions,
323
+ conversion_value: round2(revenue),
324
+ ctr: impressions > 0 ? round2(clicks / impressions * 100) : 0,
325
+ cpc: clicks > 0 ? round2(spend / clicks) : 0,
326
+ cpm: impressions > 0 ? round2(spend / impressions * 1e3) : 0,
327
+ cpa: conversions > 0 ? round2(spend / conversions) : 0,
328
+ roas: spend > 0 ? round2(revenue / spend) : 0
329
+ };
330
+ out.push({
331
+ provider: this.id,
332
+ accountId,
333
+ entity: {
334
+ level: "campaign",
335
+ id: value("CampaignId"),
336
+ name: value("CampaignName"),
337
+ status: value("CampaignStatus") || void 0
338
+ },
339
+ metrics: Object.fromEntries(query.metrics.map((m) => [m, all[m]]))
340
+ });
341
+ }
342
+ return out;
343
+ }
344
+ async previewWrite(op, guard) {
345
+ const plan = await this.plan(op, guard);
346
+ return {
347
+ summary: plan.summary,
348
+ changes: plan.changes,
349
+ coercions: plan.coercions,
350
+ budgetDeltas: plan.budgetDeltas,
351
+ serverValidated: false
352
+ };
353
+ }
354
+ async applyWrite(op, guard) {
355
+ const plan = await this.plan(op, guard);
356
+ const resourceIds = await plan.execute();
357
+ return { applied: true, resourceIds };
358
+ }
359
+ async plan(op, guard) {
360
+ const payload = op.payload;
361
+ switch (op.tool) {
362
+ case "microsoft_create_campaign":
363
+ return this.planCreateCampaign(op.accountId, payload, guard);
364
+ case "microsoft_set_campaign_status":
365
+ return this.planSetStatus(op.accountId, payload);
366
+ case "microsoft_set_budget":
367
+ return this.planSetBudget(op.accountId, payload);
368
+ default:
369
+ throw new AdportError2("PROVIDER_ERROR", `microsoft: unsupported write tool ${op.tool}`);
370
+ }
371
+ }
372
+ async planCreateCampaign(accountId, payload, guard) {
373
+ const coercions = [];
374
+ let status = payload.status ?? "Paused";
375
+ if (guard.forcePausedCreation && status === "Active") {
376
+ status = "Paused";
377
+ coercions.push("status coerced to Paused by policy (paused_creation)");
378
+ }
379
+ const campaign = {
380
+ Name: payload.name,
381
+ CampaignType: "Search",
382
+ DailyBudget: payload.daily_budget,
383
+ BudgetType: "DailyBudgetStandard",
384
+ TimeZone: payload.time_zone ?? "PacificTimeUSCanadaTijuana",
385
+ Status: status
386
+ };
387
+ return {
388
+ summary: `Create Microsoft Advertising campaign "${payload.name}" (${status}), daily budget ${payload.daily_budget}`,
389
+ changes: [`+ campaign "${payload.name}" type=Search daily_budget=${payload.daily_budget} status=${status}`],
390
+ coercions,
391
+ budgetDeltas: [
392
+ { target: `new campaign "${payload.name}" daily budget`, toMicros: payload.daily_budget * UNITS_TO_MICROS }
393
+ ],
394
+ execute: async () => {
395
+ const scope = await this.scopeFor(accountId);
396
+ const result = await this.client.request("campaign", "POST", "Campaigns", { AccountId: accountId, Campaigns: [campaign] }, scope);
397
+ const partial = formatPartialErrors(result.PartialErrors);
398
+ if (partial) throw new AdportError2("PROVIDER_ERROR", `microsoft: AddCampaigns partial errors \u2014 ${partial}`);
399
+ return (result.CampaignIds ?? []).filter((id) => id !== null).map(String);
400
+ }
401
+ };
402
+ }
403
+ async lookupCampaign(accountId, campaignId) {
404
+ const campaigns = await this.listCampaigns(accountId);
405
+ const campaign = campaigns.find((c) => String(c.Id) === campaignId);
406
+ if (!campaign) {
407
+ throw new AdportError2("PROVIDER_ERROR", `microsoft: campaign ${campaignId} not found in account ${accountId}`);
408
+ }
409
+ return campaign;
410
+ }
411
+ async updateCampaign(accountId, fields) {
412
+ const scope = await this.scopeFor(accountId);
413
+ const result = await this.client.request("campaign", "PUT", "Campaigns", { AccountId: accountId, Campaigns: [fields] }, scope);
414
+ const partial = formatPartialErrors(result.PartialErrors);
415
+ if (partial) throw new AdportError2("PROVIDER_ERROR", `microsoft: UpdateCampaigns partial errors \u2014 ${partial}`);
416
+ }
417
+ async planSetStatus(accountId, payload) {
418
+ const current = await this.lookupCampaign(accountId, payload.campaign_id);
419
+ return {
420
+ summary: `Set Microsoft campaign "${current.Name}" status ${current.Status} \u2192 ${payload.status}`,
421
+ changes: [`~ campaign ${payload.campaign_id} Status ${current.Status} \u2192 ${payload.status}`],
422
+ coercions: [],
423
+ budgetDeltas: [],
424
+ execute: async () => {
425
+ await this.updateCampaign(accountId, { Id: current.Id, Status: payload.status });
426
+ return [payload.campaign_id];
427
+ }
428
+ };
429
+ }
430
+ async planSetBudget(accountId, payload) {
431
+ const current = await this.lookupCampaign(accountId, payload.campaign_id);
432
+ if (current.BudgetId && Number(current.BudgetId) > 0) {
433
+ throw new AdportError2(
434
+ "PROVIDER_ERROR",
435
+ `microsoft: campaign "${current.Name}" uses a SHARED budget (BudgetId ${current.BudgetId}) \u2014 its DailyBudget cannot be changed per-campaign (CampaignServiceCannotUpdateSharedBudget).`
436
+ );
437
+ }
438
+ return {
439
+ summary: `Change Microsoft campaign "${current.Name}" daily budget ${current.DailyBudget ?? "(unset)"} \u2192 ${payload.daily_budget}`,
440
+ changes: [`~ campaign ${payload.campaign_id} DailyBudget ${current.DailyBudget ?? "(unset)"} \u2192 ${payload.daily_budget}`],
441
+ coercions: [],
442
+ budgetDeltas: [
443
+ {
444
+ target: `campaign "${current.Name}" daily budget`,
445
+ ...current.DailyBudget !== void 0 ? { fromMicros: current.DailyBudget * UNITS_TO_MICROS } : {},
446
+ toMicros: payload.daily_budget * UNITS_TO_MICROS
447
+ }
448
+ ],
449
+ execute: async () => {
450
+ await this.updateCampaign(accountId, { Id: current.Id, DailyBudget: payload.daily_budget });
451
+ return [payload.campaign_id];
452
+ }
453
+ };
454
+ }
455
+ };
456
+ function round2(n) {
457
+ return Math.round(n * 100) / 100;
458
+ }
459
+
460
+ // src/tools.ts
461
+ import { defineTool, guardedWriteTool } from "@adport/core";
462
+ import { z } from "zod";
463
+ var statusSchema = z.enum(["Active", "Paused"]);
464
+ function microsoftTools(provider) {
465
+ return [
466
+ defineTool({
467
+ name: "microsoft_campaigns",
468
+ namespace: "microsoft",
469
+ description: "List Microsoft Advertising campaigns (Id, Name, Status Active/Paused/BudgetPaused, DailyBudget in account currency, BudgetId when shared).",
470
+ input: z.object({ account_id: z.string().describe("Ad account id") }),
471
+ annotations: { readOnly: true },
472
+ async handler(input) {
473
+ const campaigns = await provider.listCampaigns(input.account_id);
474
+ return { campaigns };
475
+ }
476
+ }),
477
+ guardedWriteTool({
478
+ name: "microsoft_create_campaign",
479
+ namespace: "microsoft",
480
+ description: "Create a Microsoft Advertising Search campaign. daily_budget is a float in account currency. The API's own default status is Paused. No server dry-run \u2014 previews are client-side diffs.",
481
+ provider: "microsoft",
482
+ kind: "create",
483
+ payload: z.object({
484
+ name: z.string().min(1).max(128),
485
+ daily_budget: z.number().positive(),
486
+ time_zone: z.string().optional().describe("Bing Ads time zone name, default PacificTimeUSCanadaTijuana"),
487
+ status: statusSchema.optional()
488
+ })
489
+ }),
490
+ guardedWriteTool({
491
+ name: "microsoft_set_campaign_status",
492
+ namespace: "microsoft",
493
+ description: "Activate or pause a Microsoft Advertising campaign.",
494
+ provider: "microsoft",
495
+ kind: "update",
496
+ payload: z.object({ campaign_id: z.string(), status: statusSchema })
497
+ }),
498
+ guardedWriteTool({
499
+ name: "microsoft_set_budget",
500
+ namespace: "microsoft",
501
+ description: "Change a Microsoft campaign's DailyBudget (float, account currency). Fails clearly for shared budgets.",
502
+ provider: "microsoft",
503
+ kind: "update",
504
+ payload: z.object({ campaign_id: z.string(), daily_budget: z.number().positive() })
505
+ })
506
+ ];
507
+ }
508
+
509
+ // src/index.ts
510
+ async function resolveMicrosoftCredentials(store) {
511
+ const record = await store.get("microsoft");
512
+ if (record?.data.developer_token && record.data.client_id && record.data.refresh_token) {
513
+ return {
514
+ developerToken: record.data.developer_token,
515
+ clientId: record.data.client_id,
516
+ refreshToken: record.data.refresh_token,
517
+ clientSecret: record.data.client_secret || void 0,
518
+ sandbox: record.data.sandbox === "true"
519
+ };
520
+ }
521
+ const env = process.env;
522
+ if (env.MICROSOFT_ADS_DEVELOPER_TOKEN && env.MICROSOFT_ADS_CLIENT_ID && env.MICROSOFT_ADS_REFRESH_TOKEN) {
523
+ return {
524
+ developerToken: env.MICROSOFT_ADS_DEVELOPER_TOKEN,
525
+ clientId: env.MICROSOFT_ADS_CLIENT_ID,
526
+ refreshToken: env.MICROSOFT_ADS_REFRESH_TOKEN,
527
+ clientSecret: env.MICROSOFT_ADS_CLIENT_SECRET || void 0,
528
+ sandbox: env.MICROSOFT_ADS_SANDBOX === "true"
529
+ };
530
+ }
531
+ return void 0;
532
+ }
533
+ async function createMicrosoftModule(store) {
534
+ const credentials = await resolveMicrosoftCredentials(store);
535
+ if (!credentials) return void 0;
536
+ const client = new MicrosoftAdsClient(credentials, async (rotated) => {
537
+ const record = await store.get("microsoft");
538
+ if (record) {
539
+ await store.set({ ...record, data: { ...record.data, refresh_token: rotated } });
540
+ }
541
+ });
542
+ const provider = new MicrosoftAdsProvider(client);
543
+ return { provider, tools: microsoftTools(provider) };
544
+ }
545
+ export {
546
+ MSADS_SCOPE,
547
+ MicrosoftAdsClient,
548
+ MicrosoftAdsProvider,
549
+ SANDBOX_DEVELOPER_TOKEN,
550
+ UNITS_TO_MICROS,
551
+ createMicrosoftModule,
552
+ formatMicrosoftError,
553
+ formatPartialErrors,
554
+ microsoftTools,
555
+ parseCsv,
556
+ resolveMicrosoftCredentials
557
+ };
558
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/client.ts","../src/provider.ts","../src/csv.ts","../src/tools.ts","../src/index.ts"],"sourcesContent":["import { AdportError } from '@adport/core';\n\nexport interface MicrosoftCredentials {\n developerToken: string;\n clientId: string;\n refreshToken: string;\n /** Only for confidential (web) apps; native/CLI public clients have no secret. */\n clientSecret?: string;\n sandbox?: boolean;\n}\n\nconst TOKEN_URL = 'https://login.microsoftonline.com/common/oauth2/v2.0/token';\nexport const MSADS_SCOPE = 'https://ads.microsoft.com/msads.manage offline_access';\n/** Published universal sandbox developer token (anyone may use it in sandbox). */\nexport const SANDBOX_DEVELOPER_TOKEN = 'BBD37VB98';\n\nfunction hosts(sandbox: boolean) {\n const infix = sandbox ? '.sandbox' : '';\n return {\n campaign: `https://campaign.api${infix}.bingads.microsoft.com/CampaignManagement/v13`,\n customer: `https://clientcenter.api${infix}.bingads.microsoft.com/CustomerManagement/v13`,\n reporting: `https://reporting.api${infix}.bingads.microsoft.com/Reporting/v13`,\n };\n}\n\nexport type MicrosoftService = 'campaign' | 'customer' | 'reporting';\n\nexport interface RequestScope {\n /** Manager account (customer) id header. */\n customerId?: string;\n /** Ad account id header. */\n customerAccountId?: string;\n}\n\n/**\n * Microsoft Advertising REST v13 client. Public-client refresh tokens rotate —\n * onRefreshTokenRotated lets the credential store persist the replacement.\n */\nexport class MicrosoftAdsClient {\n private accessToken?: { token: string; expiresAt: number };\n private refreshToken: string;\n readonly sandbox: boolean;\n\n constructor(\n private readonly credentials: MicrosoftCredentials,\n private readonly onRefreshTokenRotated?: (token: string) => Promise<void>,\n private readonly fetchImpl: typeof fetch = fetch,\n ) {\n this.refreshToken = credentials.refreshToken;\n this.sandbox = credentials.sandbox ?? false;\n }\n\n async getAccessToken(): Promise<string> {\n if (this.accessToken && this.accessToken.expiresAt > Date.now()) {\n return this.accessToken.token;\n }\n const body = new URLSearchParams({\n client_id: this.credentials.clientId,\n scope: 'https://ads.microsoft.com/msads.manage',\n refresh_token: this.refreshToken,\n grant_type: 'refresh_token',\n });\n if (this.credentials.clientSecret) body.set('client_secret', this.credentials.clientSecret);\n const response = await this.fetchImpl(TOKEN_URL, {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body,\n });\n const raw = await response.text();\n if (!response.ok) {\n throw new AdportError(\n 'PROVIDER_ERROR',\n `Microsoft OAuth refresh failed (${response.status}). Public-client refresh tokens expire after ~90 days — re-run \\`adport connect microsoft\\`.`,\n safeJson(raw),\n );\n }\n const data = JSON.parse(raw) as { access_token: string; expires_in: number; refresh_token?: string };\n this.accessToken = { token: data.access_token, expiresAt: Date.now() + (data.expires_in - 60) * 1000 };\n if (data.refresh_token && data.refresh_token !== this.refreshToken) {\n this.refreshToken = data.refresh_token;\n await this.onRefreshTokenRotated?.(data.refresh_token);\n }\n return this.accessToken.token;\n }\n\n async request<T>(\n service: MicrosoftService,\n method: 'GET' | 'POST' | 'PUT',\n path: string,\n body: unknown,\n scope: RequestScope = {},\n ): Promise<T> {\n const token = await this.getAccessToken();\n const headers: Record<string, string> = {\n authorization: `Bearer ${token}`,\n DeveloperToken: this.sandbox ? SANDBOX_DEVELOPER_TOKEN : this.credentials.developerToken,\n 'content-type': 'application/json',\n };\n if (scope.customerId) headers.CustomerId = scope.customerId;\n if (scope.customerAccountId) headers.CustomerAccountId = scope.customerAccountId;\n const response = await this.fetchImpl(`${hosts(this.sandbox)[service]}/${path.replace(/^\\//, '')}`, {\n method,\n headers,\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n const raw = await response.text();\n if (!response.ok) {\n throw new AdportError('PROVIDER_ERROR', formatMicrosoftError(response.status, raw), safeJson(raw));\n }\n return (raw ? JSON.parse(raw) : {}) as T;\n }\n\n /** Plain authorized download (report files); returns raw bytes. */\n async download(url: string): Promise<Uint8Array> {\n const response = await this.fetchImpl(url, {});\n if (!response.ok) {\n throw new AdportError('PROVIDER_ERROR', `Microsoft report download failed (HTTP ${response.status})`);\n }\n return new Uint8Array(await response.arrayBuffer());\n }\n}\n\nfunction safeJson(raw: string): unknown {\n try {\n return JSON.parse(raw);\n } catch {\n return raw;\n }\n}\n\ninterface BatchErrorItem {\n Code?: number;\n ErrorCode?: string;\n Message?: string;\n FieldPath?: string;\n Index?: number;\n Details?: string;\n Detail?: string;\n}\n\n/**\n * REST errors are serialized fault objects: ApiFaultDetail\n * {OperationErrors, BatchErrors}, AdApiFaultDetail {Errors}, plus TrackingId.\n */\nexport function formatMicrosoftError(status: number, raw: string): string {\n const parsed = safeJson(raw) as {\n TrackingId?: string;\n Type?: string;\n OperationErrors?: BatchErrorItem[];\n BatchErrors?: BatchErrorItem[];\n Errors?: BatchErrorItem[];\n };\n if (!parsed || typeof parsed !== 'object' || (!parsed.OperationErrors && !parsed.Errors && !parsed.BatchErrors)) {\n return `Microsoft Advertising API error (HTTP ${status})`;\n }\n const items = [...(parsed.OperationErrors ?? []), ...(parsed.BatchErrors ?? []), ...(parsed.Errors ?? [])];\n const lines = items.map((e) => {\n const where = e.Index !== undefined ? ` [item ${e.Index}${e.FieldPath ? ` ${e.FieldPath}` : ''}]` : '';\n return `${e.Code ?? '?'} ${e.ErrorCode ?? ''}: ${e.Message ?? e.Details ?? e.Detail ?? ''}${where}`;\n });\n let message = `Microsoft Advertising API error (HTTP ${status}, ${parsed.Type ?? 'fault'}):\\n ${lines.join('\\n ')}`;\n if (items.some((e) => e.Code === 105)) {\n message += '\\n Code 105 InvalidCredentials: check the developer token matches the environment (sandbox vs production).';\n }\n if (items.some((e) => e.Code === 117)) {\n message += '\\n Code 117 CallRateExceeded: wait 60s before retrying.';\n }\n if (parsed.TrackingId) message += ` [TrackingId: ${parsed.TrackingId}]`;\n return message;\n}\n\nexport function formatPartialErrors(partialErrors: BatchErrorItem[] | undefined): string | undefined {\n if (!partialErrors || partialErrors.length === 0) return undefined;\n return partialErrors\n .map((e) => `item ${e.Index ?? '?'}: ${e.Code ?? ''} ${e.ErrorCode ?? ''} ${e.Message ?? ''}${e.FieldPath ? ` (${e.FieldPath})` : ''}`)\n .join('; ');\n}\n","import {\n AdportError,\n resolveDateRange,\n type Account,\n type AdProvider,\n type MetricName,\n type NormalizedQuery,\n type ProviderCapabilities,\n type Report,\n type ReportRow,\n type StandardActions,\n type WriteGuard,\n type WriteOperation,\n type WritePreview,\n type WriteResult,\n} from '@adport/core';\nimport { unzipSync } from 'fflate';\nimport { formatPartialErrors, MicrosoftAdsClient } from './client.js';\nimport { parseCsv } from './csv.js';\n\n/** DailyBudget is a double in whole account-currency units. */\nexport const UNITS_TO_MICROS = 1_000_000;\n\ninterface MicrosoftCampaign {\n Id: number | string;\n Name: string;\n Status: string;\n DailyBudget?: number;\n BudgetType?: string;\n BudgetId?: number | string | null;\n TimeZone?: string;\n CampaignType?: string;\n}\n\ninterface WritePlan {\n summary: string;\n changes: string[];\n coercions: string[];\n budgetDeltas: WritePreview['budgetDeltas'];\n execute: () => Promise<string[]>;\n}\n\nexport class MicrosoftAdsProvider implements AdProvider {\n readonly id = 'microsoft';\n /** accountId → parent customer id, learned from SearchAccounts. */\n private customerIds = new Map<string, string>();\n\n constructor(\n private readonly client: MicrosoftAdsClient,\n private readonly options: { pollIntervalMs?: number; pollMaxAttempts?: number } = {},\n ) {}\n\n capabilities(): ProviderCapabilities {\n return { serverDryRun: false };\n }\n\n standardActions(): StandardActions {\n return {\n pauseCampaign: (accountId, campaignId) => ({\n tool: 'microsoft_set_campaign_status',\n input: { account_id: accountId, campaign_id: campaignId, status: 'Paused' },\n }),\n };\n }\n\n async listAccounts(): Promise<Account[]> {\n const user = await this.client.request<{ User?: { Id?: number | string } }>(\n 'customer',\n 'POST',\n 'User/Query',\n { UserId: null },\n );\n const userId = user.User?.Id;\n if (userId === undefined) {\n throw new AdportError('PROVIDER_ERROR', 'microsoft: GetUser returned no user id');\n }\n const search = await this.client.request<{\n Accounts?: Array<{\n Id: number | string;\n Name?: string;\n Number?: string;\n CurrencyCode?: string;\n AccountLifeCycleStatus?: string;\n ParentCustomerId?: number | string;\n }>;\n }>('customer', 'POST', 'Accounts/Search', {\n Predicates: [{ Field: 'UserId', Operator: 'Equals', Value: String(userId) }],\n PageInfo: { Index: 0, Size: 100 },\n });\n const accounts = search.Accounts ?? [];\n for (const account of accounts) {\n if (account.ParentCustomerId !== undefined) {\n this.customerIds.set(String(account.Id), String(account.ParentCustomerId));\n }\n }\n return accounts.map((a) => ({\n provider: this.id,\n id: String(a.Id),\n name: a.Name ?? a.Number ?? String(a.Id),\n currency: a.CurrencyCode,\n status: a.AccountLifeCycleStatus,\n }));\n }\n\n private async scopeFor(accountId: string) {\n if (!this.customerIds.has(accountId)) await this.listAccounts();\n return { customerId: this.customerIds.get(accountId), customerAccountId: accountId };\n }\n\n async listCampaigns(accountId: string): Promise<MicrosoftCampaign[]> {\n const scope = await this.scopeFor(accountId);\n const data = await this.client.request<{ Campaigns?: MicrosoftCampaign[] | null }>(\n 'campaign',\n 'POST',\n 'Campaigns/QueryByAccountId',\n { AccountId: accountId, ReturnAdditionalFields: null },\n scope,\n );\n return data.Campaigns ?? [];\n }\n\n async report(query: NormalizedQuery): Promise<Report> {\n if (query.level !== 'campaign' && query.level !== 'account') {\n throw new AdportError('INVALID_INPUT', 'microsoft: report supports campaign and account levels in v0');\n }\n const range = resolveDateRange(query.dateRange);\n const accountIds = query.accountIds ?? (await this.listAccounts()).map((a) => a.id);\n const rows: ReportRow[] = [];\n for (const accountId of accountIds) {\n rows.push(...(await this.campaignReport(accountId, range.start, range.end, query)));\n }\n return { rows };\n }\n\n private async campaignReport(\n accountId: string,\n start: string,\n end: string,\n query: NormalizedQuery,\n ): Promise<ReportRow[]> {\n const scope = await this.scopeFor(accountId);\n const toDate = (iso: string) => {\n const [year, month, day] = iso.split('-').map(Number);\n return { Day: day, Month: month, Year: year };\n };\n // Async flow: Submit → Poll until Success → download zipped CSV.\n const submit = await this.client.request<{ ReportRequestId?: string }>(\n 'reporting',\n 'POST',\n 'GenerateReport/Submit',\n {\n ReportRequest: {\n Type: 'CampaignPerformanceReportRequest',\n Format: 'Csv',\n FormatVersion: '2.0',\n ReportName: 'adport campaign report',\n ExcludeReportHeader: true,\n ExcludeReportFooter: true,\n ExcludeColumnHeaders: false,\n ReturnOnlyCompleteData: false,\n Aggregation: 'Summary',\n Columns: ['CampaignId', 'CampaignName', 'CampaignStatus', 'Spend', 'Impressions', 'Clicks', 'Conversions', 'Revenue'],\n Scope: { AccountIds: [accountId] },\n Time: { CustomDateRangeStart: toDate(start), CustomDateRangeEnd: toDate(end) },\n },\n },\n scope,\n );\n if (!submit.ReportRequestId) {\n throw new AdportError('PROVIDER_ERROR', 'microsoft: SubmitGenerateReport returned no ReportRequestId');\n }\n\n const maxAttempts = this.options.pollMaxAttempts ?? 30;\n const interval = this.options.pollIntervalMs ?? 5_000;\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n const poll = await this.client.request<{\n ReportRequestStatus?: { Status?: string; ReportDownloadUrl?: string | null };\n }>('reporting', 'POST', 'GenerateReport/Poll', { ReportRequestId: submit.ReportRequestId }, scope);\n const status = poll.ReportRequestStatus?.Status;\n if (status === 'Error') {\n throw new AdportError('PROVIDER_ERROR', 'microsoft: report generation failed (Status: Error)');\n }\n if (status === 'Success') {\n const url = poll.ReportRequestStatus?.ReportDownloadUrl;\n if (!url) return []; // Success with null URL = no data for the range.\n return this.parseReport(await this.client.download(url), accountId, query);\n }\n await new Promise((resolve) => setTimeout(resolve, interval));\n }\n throw new AdportError('PROVIDER_ERROR', `microsoft: report not ready after ${maxAttempts} polls`);\n }\n\n private parseReport(zipBytes: Uint8Array, accountId: string, query: NormalizedQuery): ReportRow[] {\n const files = unzipSync(zipBytes);\n const first = Object.values(files)[0];\n if (!first) return [];\n const rows = parseCsv(new TextDecoder().decode(first));\n if (rows.length < 2) return [];\n const header = rows[0]!;\n const index = (name: string) => header.indexOf(name);\n const out: ReportRow[] = [];\n for (const row of rows.slice(1)) {\n const value = (name: string) => {\n const i = index(name);\n return i >= 0 ? (row[i] ?? '') : '';\n };\n const spend = Number(value('Spend') || 0);\n const impressions = Number(value('Impressions') || 0);\n const clicks = Number(value('Clicks') || 0);\n const conversions = Number(value('Conversions') || 0);\n const revenue = Number(value('Revenue') || 0);\n const all: Record<MetricName, number> = {\n spend: round2(spend),\n impressions,\n clicks,\n conversions,\n conversion_value: round2(revenue),\n ctr: impressions > 0 ? round2((clicks / impressions) * 100) : 0,\n cpc: clicks > 0 ? round2(spend / clicks) : 0,\n cpm: impressions > 0 ? round2((spend / impressions) * 1000) : 0,\n cpa: conversions > 0 ? round2(spend / conversions) : 0,\n roas: spend > 0 ? round2(revenue / spend) : 0,\n };\n out.push({\n provider: this.id,\n accountId,\n entity: {\n level: 'campaign',\n id: value('CampaignId'),\n name: value('CampaignName'),\n status: value('CampaignStatus') || undefined,\n },\n metrics: Object.fromEntries(query.metrics.map((m) => [m, all[m]])),\n });\n }\n return out;\n }\n\n async previewWrite(op: WriteOperation, guard: WriteGuard): Promise<WritePreview> {\n const plan = await this.plan(op, guard);\n return {\n summary: plan.summary,\n changes: plan.changes,\n coercions: plan.coercions,\n budgetDeltas: plan.budgetDeltas,\n serverValidated: false,\n };\n }\n\n async applyWrite(op: WriteOperation, guard: WriteGuard): Promise<WriteResult> {\n const plan = await this.plan(op, guard);\n const resourceIds = await plan.execute();\n return { applied: true, resourceIds };\n }\n\n private async plan(op: WriteOperation, guard: WriteGuard): Promise<WritePlan> {\n const payload = op.payload as never;\n switch (op.tool) {\n case 'microsoft_create_campaign':\n return this.planCreateCampaign(op.accountId, payload, guard);\n case 'microsoft_set_campaign_status':\n return this.planSetStatus(op.accountId, payload);\n case 'microsoft_set_budget':\n return this.planSetBudget(op.accountId, payload);\n default:\n throw new AdportError('PROVIDER_ERROR', `microsoft: unsupported write tool ${op.tool}`);\n }\n }\n\n private async planCreateCampaign(\n accountId: string,\n payload: { name: string; daily_budget: number; time_zone?: string; status?: string },\n guard: WriteGuard,\n ): Promise<WritePlan> {\n const coercions: string[] = [];\n // The API's own default status on Add is Paused; we only coerce an explicit Active.\n let status = payload.status ?? 'Paused';\n if (guard.forcePausedCreation && status === 'Active') {\n status = 'Paused';\n coercions.push('status coerced to Paused by policy (paused_creation)');\n }\n const campaign = {\n Name: payload.name,\n CampaignType: 'Search',\n DailyBudget: payload.daily_budget,\n BudgetType: 'DailyBudgetStandard',\n TimeZone: payload.time_zone ?? 'PacificTimeUSCanadaTijuana',\n Status: status,\n };\n return {\n summary: `Create Microsoft Advertising campaign \"${payload.name}\" (${status}), daily budget ${payload.daily_budget}`,\n changes: [`+ campaign \"${payload.name}\" type=Search daily_budget=${payload.daily_budget} status=${status}`],\n coercions,\n budgetDeltas: [\n { target: `new campaign \"${payload.name}\" daily budget`, toMicros: payload.daily_budget * UNITS_TO_MICROS },\n ],\n execute: async () => {\n const scope = await this.scopeFor(accountId);\n const result = await this.client.request<{\n CampaignIds?: Array<number | string | null>;\n PartialErrors?: Array<{ Index?: number; Code?: number; ErrorCode?: string; Message?: string; FieldPath?: string }>;\n }>('campaign', 'POST', 'Campaigns', { AccountId: accountId, Campaigns: [campaign] }, scope);\n const partial = formatPartialErrors(result.PartialErrors);\n if (partial) throw new AdportError('PROVIDER_ERROR', `microsoft: AddCampaigns partial errors — ${partial}`);\n return (result.CampaignIds ?? []).filter((id): id is number | string => id !== null).map(String);\n },\n };\n }\n\n private async lookupCampaign(accountId: string, campaignId: string): Promise<MicrosoftCampaign> {\n const campaigns = await this.listCampaigns(accountId);\n const campaign = campaigns.find((c) => String(c.Id) === campaignId);\n if (!campaign) {\n throw new AdportError('PROVIDER_ERROR', `microsoft: campaign ${campaignId} not found in account ${accountId}`);\n }\n return campaign;\n }\n\n private async updateCampaign(\n accountId: string,\n fields: Record<string, unknown> & { Id: number | string },\n ): Promise<void> {\n const scope = await this.scopeFor(accountId);\n // UpdateCampaigns is PUT; omitted fields stay unchanged.\n const result = await this.client.request<{\n PartialErrors?: Array<{ Index?: number; Code?: number; ErrorCode?: string; Message?: string }>;\n }>('campaign', 'PUT', 'Campaigns', { AccountId: accountId, Campaigns: [fields] }, scope);\n const partial = formatPartialErrors(result.PartialErrors);\n if (partial) throw new AdportError('PROVIDER_ERROR', `microsoft: UpdateCampaigns partial errors — ${partial}`);\n }\n\n private async planSetStatus(\n accountId: string,\n payload: { campaign_id: string; status: 'Active' | 'Paused' },\n ): Promise<WritePlan> {\n const current = await this.lookupCampaign(accountId, payload.campaign_id);\n return {\n summary: `Set Microsoft campaign \"${current.Name}\" status ${current.Status} → ${payload.status}`,\n changes: [`~ campaign ${payload.campaign_id} Status ${current.Status} → ${payload.status}`],\n coercions: [],\n budgetDeltas: [],\n execute: async () => {\n await this.updateCampaign(accountId, { Id: current.Id, Status: payload.status });\n return [payload.campaign_id];\n },\n };\n }\n\n private async planSetBudget(\n accountId: string,\n payload: { campaign_id: string; daily_budget: number },\n ): Promise<WritePlan> {\n const current = await this.lookupCampaign(accountId, payload.campaign_id);\n if (current.BudgetId && Number(current.BudgetId) > 0) {\n throw new AdportError(\n 'PROVIDER_ERROR',\n `microsoft: campaign \"${current.Name}\" uses a SHARED budget (BudgetId ${current.BudgetId}) — ` +\n 'its DailyBudget cannot be changed per-campaign (CampaignServiceCannotUpdateSharedBudget).',\n );\n }\n return {\n summary: `Change Microsoft campaign \"${current.Name}\" daily budget ${current.DailyBudget ?? '(unset)'} → ${payload.daily_budget}`,\n changes: [`~ campaign ${payload.campaign_id} DailyBudget ${current.DailyBudget ?? '(unset)'} → ${payload.daily_budget}`],\n coercions: [],\n budgetDeltas: [\n {\n target: `campaign \"${current.Name}\" daily budget`,\n ...(current.DailyBudget !== undefined ? { fromMicros: current.DailyBudget * UNITS_TO_MICROS } : {}),\n toMicros: payload.daily_budget * UNITS_TO_MICROS,\n },\n ],\n execute: async () => {\n await this.updateCampaign(accountId, { Id: current.Id, DailyBudget: payload.daily_budget });\n return [payload.campaign_id];\n },\n };\n }\n}\n\nfunction round2(n: number): number {\n return Math.round(n * 100) / 100;\n}\n","/** Minimal RFC-4180-ish CSV parser (quotes, escaped quotes, CRLF). */\nexport function parseCsv(text: string): string[][] {\n const rows: string[][] = [];\n let row: string[] = [];\n let field = '';\n let inQuotes = false;\n for (let i = 0; i < text.length; i++) {\n const char = text[i]!;\n if (inQuotes) {\n if (char === '\"') {\n if (text[i + 1] === '\"') {\n field += '\"';\n i++;\n } else {\n inQuotes = false;\n }\n } else {\n field += char;\n }\n continue;\n }\n if (char === '\"') {\n inQuotes = true;\n } else if (char === ',') {\n row.push(field);\n field = '';\n } else if (char === '\\n' || char === '\\r') {\n if (char === '\\r' && text[i + 1] === '\\n') i++;\n row.push(field);\n field = '';\n if (row.length > 1 || row[0] !== '') rows.push(row);\n row = [];\n } else {\n field += char;\n }\n }\n if (field !== '' || row.length > 0) {\n row.push(field);\n if (row.length > 1 || row[0] !== '') rows.push(row);\n }\n return rows;\n}\n","import { defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport type { MicrosoftAdsProvider } from './provider.js';\n\nconst statusSchema = z.enum(['Active', 'Paused']);\n\nexport function microsoftTools(provider: MicrosoftAdsProvider): AnyToolDefinition[] {\n return [\n defineTool({\n name: 'microsoft_campaigns',\n namespace: 'microsoft',\n description:\n 'List Microsoft Advertising campaigns (Id, Name, Status Active/Paused/BudgetPaused, DailyBudget in account currency, BudgetId when shared).',\n input: z.object({ account_id: z.string().describe('Ad account id') }),\n annotations: { readOnly: true },\n async handler(input) {\n const campaigns = await provider.listCampaigns(input.account_id);\n return { campaigns };\n },\n }),\n guardedWriteTool({\n name: 'microsoft_create_campaign',\n namespace: 'microsoft',\n description:\n 'Create a Microsoft Advertising Search campaign. daily_budget is a float in account currency. ' +\n \"The API's own default status is Paused. No server dry-run — previews are client-side diffs.\",\n provider: 'microsoft',\n kind: 'create',\n payload: z.object({\n name: z.string().min(1).max(128),\n daily_budget: z.number().positive(),\n time_zone: z.string().optional().describe('Bing Ads time zone name, default PacificTimeUSCanadaTijuana'),\n status: statusSchema.optional(),\n }),\n }),\n guardedWriteTool({\n name: 'microsoft_set_campaign_status',\n namespace: 'microsoft',\n description: 'Activate or pause a Microsoft Advertising campaign.',\n provider: 'microsoft',\n kind: 'update',\n payload: z.object({ campaign_id: z.string(), status: statusSchema }),\n }),\n guardedWriteTool({\n name: 'microsoft_set_budget',\n namespace: 'microsoft',\n description:\n \"Change a Microsoft campaign's DailyBudget (float, account currency). Fails clearly for shared budgets.\",\n provider: 'microsoft',\n kind: 'update',\n payload: z.object({ campaign_id: z.string(), daily_budget: z.number().positive() }),\n }),\n ];\n}\n","import type { CredentialStore, ProviderModule } from '@adport/core';\nimport { MicrosoftAdsClient, type MicrosoftCredentials } from './client.js';\nimport { MicrosoftAdsProvider } from './provider.js';\nimport { microsoftTools } from './tools.js';\n\nexport {\n MicrosoftAdsClient,\n MSADS_SCOPE,\n SANDBOX_DEVELOPER_TOKEN,\n formatMicrosoftError,\n formatPartialErrors,\n type MicrosoftCredentials,\n} from './client.js';\nexport { MicrosoftAdsProvider, UNITS_TO_MICROS } from './provider.js';\nexport { microsoftTools } from './tools.js';\nexport { parseCsv } from './csv.js';\n\nexport async function resolveMicrosoftCredentials(store: CredentialStore): Promise<MicrosoftCredentials | undefined> {\n const record = await store.get('microsoft');\n if (record?.data.developer_token && record.data.client_id && record.data.refresh_token) {\n return {\n developerToken: record.data.developer_token,\n clientId: record.data.client_id,\n refreshToken: record.data.refresh_token,\n clientSecret: record.data.client_secret || undefined,\n sandbox: record.data.sandbox === 'true',\n };\n }\n const env = process.env;\n if (env.MICROSOFT_ADS_DEVELOPER_TOKEN && env.MICROSOFT_ADS_CLIENT_ID && env.MICROSOFT_ADS_REFRESH_TOKEN) {\n return {\n developerToken: env.MICROSOFT_ADS_DEVELOPER_TOKEN,\n clientId: env.MICROSOFT_ADS_CLIENT_ID,\n refreshToken: env.MICROSOFT_ADS_REFRESH_TOKEN,\n clientSecret: env.MICROSOFT_ADS_CLIENT_SECRET || undefined,\n sandbox: env.MICROSOFT_ADS_SANDBOX === 'true',\n };\n }\n return undefined;\n}\n\nexport async function createMicrosoftModule(store: CredentialStore): Promise<ProviderModule | undefined> {\n const credentials = await resolveMicrosoftCredentials(store);\n if (!credentials) return undefined;\n const client = new MicrosoftAdsClient(credentials, async (rotated) => {\n // Public-client refresh tokens rotate; persist the replacement immediately.\n const record = await store.get('microsoft');\n if (record) {\n await store.set({ ...record, data: { ...record.data, refresh_token: rotated } });\n }\n });\n const provider = new MicrosoftAdsProvider(client);\n return { provider,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AM,IAAI,WAAW;AAC1C,QAAI,QAAQ;AACV,YAAM,MAAM,IAAI,EAAE,GAAG,QAAQ,MAAM,EAAE,GAAG,OAAO,MAAM,eAAe,QAAQ,EAAE,CAAC;AAAA,IACjF;AAAA,EACF,CAAC;AACD,QAAM,WAAW,IAAI,qBAAqB,MAAM;AAChD,SAAO,EAAE,UAAU,OAAO,eAAe,QAAQ,EAAE;AACrD;","names":["AdportError","AdportError"]}
package/package.json ADDED
@@ -0,0 +1,35 @@
1
+ {
2
+ "name": "@adport/provider-microsoft",
3
+ "version": "0.1.0",
4
+ "description": "Microsoft Advertising (Bing Ads) provider for adport — REST API v13 with sandbox support",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist"
17
+ ],
18
+ "dependencies": {
19
+ "fflate": "^0.8.2",
20
+ "zod": "^3.25.0",
21
+ "@adport/core": "0.1.0"
22
+ },
23
+ "devDependencies": {
24
+ "@types/node": "^22.10.0",
25
+ "tsup": "^8.3.0",
26
+ "typescript": "^5.8.0",
27
+ "vitest": "^3.0.0"
28
+ },
29
+ "scripts": {
30
+ "build": "tsup src/index.ts --format esm --dts --sourcemap --clean",
31
+ "test": "vitest run",
32
+ "typecheck": "tsc --noEmit",
33
+ "clean": "rm -rf dist"
34
+ }
35
+ }