@adport/provider-analytics 0.0.0-stage → 0.10.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/README.md +18 -2
- package/dist/index.d.ts +125 -0
- package/dist/index.js +246 -0
- package/dist/index.js.map +1 -0
- package/package.json +45 -3
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/README.md
CHANGED
|
@@ -1,3 +1,19 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @adport/provider-analytics
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Read-only Google Analytics 4 and Google Search Console integrations for Adport.
|
|
4
|
+
Tool schemas are defined once in `@adport/core` and shared by MCP and the CLI.
|
|
5
|
+
|
|
6
|
+
- GA4: property settings, available dimensions/metrics, historical reports and realtime activity.
|
|
7
|
+
- Search Console: organic search performance, property permissions, submitted sitemap status and URL index inspection.
|
|
8
|
+
|
|
9
|
+
There are no configuration, sitemap submission or indexing mutation tools. Native reporting POST requests are read-only queries. Reports preserve provider units, GA4 decimal strings, time zones, pagination and privacy/sampling notices.
|
|
10
|
+
|
|
11
|
+
## Self-hosted connections
|
|
12
|
+
|
|
13
|
+
Enable Google Analytics Data API and Google Analytics Admin API for GA4, or Google Search Console API for Search Console, in your own Google Cloud project. Create an OAuth Desktop client and configure its secret securely as `GA4_CLIENT_SECRET` or `GSC_CLIENT_SECRET`. Run `adport connect ga4` or `adport connect gsc` and enter the matching client ID. The consent flow requests only `analytics.readonly` or `webmasters.readonly`.
|
|
14
|
+
|
|
15
|
+
For noninteractive startup, configure complete `GA4_CLIENT_ID`, `GA4_CLIENT_SECRET`, `GA4_REFRESH_TOKEN` or `GSC_CLIENT_ID`, `GSC_CLIENT_SECRET`, `GSC_REFRESH_TOKEN` triplets. Never commit credentials. A complete stored connection takes precedence over environment credentials.
|
|
16
|
+
|
|
17
|
+
Use `accounts_list` with provider `ga4` or `gsc`, then the corresponding `ga4_*` / `gsc_*` tools. Cloud projects can access only properties explicitly selected by their owner. Analytics properties do not consume advertising account capacity.
|
|
18
|
+
|
|
19
|
+
GA4 metadata describes registered custom dimensions and metrics. Realtime reporting supports a smaller set of fields. Search Console returns top rows and may omit anonymized queries; CTR is a fraction and position is an average. URL inspection reads Google's indexed view and does not request reindexing.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { AdProvider, Account, NormalizedQuery, Report, WriteOperation, WritePreview, WriteResult, Ga4ReportInput, Ga4RealtimeInput, GscReportInput, CredentialStore, ProviderModule } from '@adport/core';
|
|
2
|
+
export { GA4_SCOPES, GSC_SCOPES, ga4Tools, gscTools } from '@adport/core';
|
|
3
|
+
|
|
4
|
+
interface AnalyticsCredentials {
|
|
5
|
+
clientId: string;
|
|
6
|
+
clientSecret: string;
|
|
7
|
+
refreshToken: string;
|
|
8
|
+
}
|
|
9
|
+
type Resource = Record<string, unknown>;
|
|
10
|
+
declare const services: {
|
|
11
|
+
readonly admin: {
|
|
12
|
+
readonly origin: "https://analyticsadmin.googleapis.com/v1beta/";
|
|
13
|
+
readonly get: RegExp;
|
|
14
|
+
readonly post: RegExp;
|
|
15
|
+
};
|
|
16
|
+
readonly data: {
|
|
17
|
+
readonly origin: "https://analyticsdata.googleapis.com/v1beta/";
|
|
18
|
+
readonly get: RegExp;
|
|
19
|
+
readonly post: RegExp;
|
|
20
|
+
};
|
|
21
|
+
readonly search: {
|
|
22
|
+
readonly origin: "https://www.googleapis.com/webmasters/v3/";
|
|
23
|
+
readonly get: RegExp;
|
|
24
|
+
readonly post: RegExp;
|
|
25
|
+
};
|
|
26
|
+
readonly inspection: {
|
|
27
|
+
readonly origin: "https://searchconsole.googleapis.com/v1/";
|
|
28
|
+
readonly get: RegExp;
|
|
29
|
+
readonly post: RegExp;
|
|
30
|
+
};
|
|
31
|
+
};
|
|
32
|
+
/** Only documented read endpoints are reachable, including POST-based reporting queries. */
|
|
33
|
+
declare class AnalyticsClient {
|
|
34
|
+
private readonly credentials;
|
|
35
|
+
private readonly fetchImpl;
|
|
36
|
+
private token?;
|
|
37
|
+
constructor(credentials: AnalyticsCredentials, fetchImpl?: typeof fetch);
|
|
38
|
+
request(service: keyof typeof services, path: string, body?: unknown, query?: Record<string, string>): Promise<Resource>;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
declare abstract class ReadOnlyAnalytics implements AdProvider {
|
|
42
|
+
abstract readonly id: string;
|
|
43
|
+
abstract listAccounts(): Promise<Account[]>;
|
|
44
|
+
capabilities(): {
|
|
45
|
+
serverDryRun: boolean;
|
|
46
|
+
reporting: boolean;
|
|
47
|
+
};
|
|
48
|
+
report(_query: NormalizedQuery): Promise<Report>;
|
|
49
|
+
previewWrite(_op: WriteOperation): Promise<WritePreview>;
|
|
50
|
+
applyWrite(_op: WriteOperation): Promise<WriteResult>;
|
|
51
|
+
}
|
|
52
|
+
declare class Ga4Provider extends ReadOnlyAnalytics {
|
|
53
|
+
private readonly client;
|
|
54
|
+
readonly id = "ga4";
|
|
55
|
+
constructor(client: AnalyticsClient);
|
|
56
|
+
listAccounts(): Promise<Account[]>;
|
|
57
|
+
property(accountId: string): Promise<Resource>;
|
|
58
|
+
metadata(accountId: string): Promise<Resource>;
|
|
59
|
+
analyticsReport(input: Ga4ReportInput | Ga4RealtimeInput, realtime?: boolean): Promise<{
|
|
60
|
+
notes: string[];
|
|
61
|
+
property_quota: unknown;
|
|
62
|
+
next_offset?: number | undefined;
|
|
63
|
+
truncated?: boolean | undefined;
|
|
64
|
+
provider: string;
|
|
65
|
+
account_id: string;
|
|
66
|
+
report_type: string;
|
|
67
|
+
rows: {
|
|
68
|
+
dimensions: {
|
|
69
|
+
[k: string]: string;
|
|
70
|
+
};
|
|
71
|
+
metrics: {
|
|
72
|
+
[k: string]: string;
|
|
73
|
+
};
|
|
74
|
+
}[];
|
|
75
|
+
metric_headers: {
|
|
76
|
+
name: string;
|
|
77
|
+
type: string;
|
|
78
|
+
}[];
|
|
79
|
+
metadata: Resource | undefined;
|
|
80
|
+
row_count: number;
|
|
81
|
+
offset: number;
|
|
82
|
+
limit: number;
|
|
83
|
+
}>;
|
|
84
|
+
}
|
|
85
|
+
declare class SearchConsoleProvider extends ReadOnlyAnalytics {
|
|
86
|
+
private readonly client;
|
|
87
|
+
readonly id = "gsc";
|
|
88
|
+
constructor(client: AnalyticsClient);
|
|
89
|
+
private path;
|
|
90
|
+
listAccounts(): Promise<Account[]>;
|
|
91
|
+
site(accountId: string): Promise<Resource>;
|
|
92
|
+
sitemaps(accountId: string): Promise<Resource>;
|
|
93
|
+
inspectUrl(accountId: string, inspectionUrl: string): Promise<Resource>;
|
|
94
|
+
searchAnalytics(input: GscReportInput): Promise<{
|
|
95
|
+
aggregation_type: unknown;
|
|
96
|
+
date_range: {
|
|
97
|
+
start: string;
|
|
98
|
+
end: string;
|
|
99
|
+
timezone: string;
|
|
100
|
+
};
|
|
101
|
+
notes: string[];
|
|
102
|
+
next_start_row?: number | undefined;
|
|
103
|
+
truncated?: boolean | undefined;
|
|
104
|
+
provider: string;
|
|
105
|
+
account_id: string;
|
|
106
|
+
rows: {
|
|
107
|
+
dimensions: {
|
|
108
|
+
[k: string]: string;
|
|
109
|
+
};
|
|
110
|
+
metrics: {
|
|
111
|
+
clicks: number;
|
|
112
|
+
impressions: number;
|
|
113
|
+
ctr: number;
|
|
114
|
+
position: number;
|
|
115
|
+
};
|
|
116
|
+
}[];
|
|
117
|
+
start_row: number;
|
|
118
|
+
limit: number;
|
|
119
|
+
}>;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
declare function createGa4Module(store: CredentialStore): Promise<ProviderModule | undefined>;
|
|
123
|
+
declare function createGscModule(store: CredentialStore): Promise<ProviderModule | undefined>;
|
|
124
|
+
|
|
125
|
+
export { AnalyticsClient, type AnalyticsCredentials, Ga4Provider, SearchConsoleProvider, createGa4Module, createGscModule };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import { ga4Tools, gscTools } from "@adport/core";
|
|
3
|
+
|
|
4
|
+
// src/client.ts
|
|
5
|
+
import { AdportError } from "@adport/core";
|
|
6
|
+
var services = {
|
|
7
|
+
admin: { origin: "https://analyticsadmin.googleapis.com/v1beta/", get: /^(?:accountSummaries|properties\/\d+)$/, post: /^$/ },
|
|
8
|
+
data: { origin: "https://analyticsdata.googleapis.com/v1beta/", get: /^properties\/\d+\/metadata$/, post: /^properties\/\d+:(?:runReport|runRealtimeReport)$/ },
|
|
9
|
+
search: { origin: "https://www.googleapis.com/webmasters/v3/", get: /^sites(?:\/[^/]+(?:\/sitemaps)?)?$/, post: /^sites\/[^/]+\/searchAnalytics\/query$/ },
|
|
10
|
+
inspection: { origin: "https://searchconsole.googleapis.com/v1/", get: /^$/, post: /^urlInspection\/index:inspect$/ }
|
|
11
|
+
};
|
|
12
|
+
var AnalyticsClient = class {
|
|
13
|
+
constructor(credentials2, fetchImpl = fetch) {
|
|
14
|
+
this.credentials = credentials2;
|
|
15
|
+
this.fetchImpl = fetchImpl;
|
|
16
|
+
}
|
|
17
|
+
credentials;
|
|
18
|
+
fetchImpl;
|
|
19
|
+
token;
|
|
20
|
+
async request(service, path, body, query = {}) {
|
|
21
|
+
const api = services[service];
|
|
22
|
+
if (!(body === void 0 ? api.get : api.post).test(path) || !path) throw new AdportError("INVALID_INPUT", "Unsupported analytics read endpoint.");
|
|
23
|
+
if (!this.token || this.token.until <= Date.now()) {
|
|
24
|
+
const response2 = await this.fetchImpl("https://oauth2.googleapis.com/token", {
|
|
25
|
+
method: "POST",
|
|
26
|
+
redirect: "error",
|
|
27
|
+
signal: AbortSignal.timeout(3e4),
|
|
28
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
29
|
+
body: new URLSearchParams({
|
|
30
|
+
client_id: this.credentials.clientId,
|
|
31
|
+
client_secret: this.credentials.clientSecret,
|
|
32
|
+
refresh_token: this.credentials.refreshToken,
|
|
33
|
+
grant_type: "refresh_token"
|
|
34
|
+
})
|
|
35
|
+
});
|
|
36
|
+
const token = await response2.json().catch(() => ({}));
|
|
37
|
+
if (!response2.ok || typeof token.access_token !== "string" || !token.access_token) throw new AdportError("NOT_CONNECTED", "Google analytics authorization expired or was revoked. Reconnect this analytics source.");
|
|
38
|
+
this.token = { value: token.access_token, until: Date.now() + Math.max(0, Number(token.expires_in ?? 3600) - 60) * 1e3 };
|
|
39
|
+
}
|
|
40
|
+
const params = new URLSearchParams(query);
|
|
41
|
+
const response = await this.fetchImpl(`${api.origin}${path}${params.size ? `?${params}` : ""}`, {
|
|
42
|
+
method: body === void 0 ? "GET" : "POST",
|
|
43
|
+
redirect: "error",
|
|
44
|
+
signal: AbortSignal.timeout(3e4),
|
|
45
|
+
headers: { authorization: `Bearer ${this.token.value}`, "content-type": "application/json" },
|
|
46
|
+
...body === void 0 ? {} : { body: JSON.stringify(body) }
|
|
47
|
+
});
|
|
48
|
+
const result = await response.json().catch(() => ({}));
|
|
49
|
+
if (response.status === 401) throw new AdportError("NOT_CONNECTED", "Google analytics authorization is no longer valid. Reconnect this analytics source.");
|
|
50
|
+
if (!response.ok) throw new AdportError("PROVIDER_ERROR", `Google analytics read failed (HTTP ${response.status}). Check API enablement, property access and requested fields.`, { status: response.status });
|
|
51
|
+
return result;
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
// src/provider.ts
|
|
56
|
+
import {
|
|
57
|
+
AdportError as AdportError2,
|
|
58
|
+
ga4ReportSchema,
|
|
59
|
+
ga4RealtimeSchema,
|
|
60
|
+
gscReportSchema,
|
|
61
|
+
searchConsoleSite
|
|
62
|
+
} from "@adport/core";
|
|
63
|
+
function propertyId(value) {
|
|
64
|
+
if (!/^\d+$/.test(value)) throw new AdportError2("INVALID_INPUT", "GA4 property IDs must be numeric.");
|
|
65
|
+
return value;
|
|
66
|
+
}
|
|
67
|
+
var ReadOnlyAnalytics = class {
|
|
68
|
+
capabilities() {
|
|
69
|
+
return { serverDryRun: false, reporting: false };
|
|
70
|
+
}
|
|
71
|
+
async report(_query) {
|
|
72
|
+
throw new AdportError2("INVALID_INPUT", `Use the ${this.id} reporting tools for analytics-specific dimensions and metrics.`);
|
|
73
|
+
}
|
|
74
|
+
async previewWrite(_op) {
|
|
75
|
+
throw new AdportError2("POLICY_VIOLATION", "This analytics integration is read-only.");
|
|
76
|
+
}
|
|
77
|
+
async applyWrite(_op) {
|
|
78
|
+
throw new AdportError2("POLICY_VIOLATION", "This analytics integration is read-only.");
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
var Ga4Provider = class extends ReadOnlyAnalytics {
|
|
82
|
+
constructor(client) {
|
|
83
|
+
super();
|
|
84
|
+
this.client = client;
|
|
85
|
+
}
|
|
86
|
+
client;
|
|
87
|
+
id = "ga4";
|
|
88
|
+
async listAccounts() {
|
|
89
|
+
const accounts = /* @__PURE__ */ new Map(), seen = /* @__PURE__ */ new Set();
|
|
90
|
+
let pageToken;
|
|
91
|
+
do {
|
|
92
|
+
const result = await this.client.request("admin", "accountSummaries", void 0, { pageSize: "200", ...pageToken ? { pageToken } : {} });
|
|
93
|
+
for (const account of result.accountSummaries ?? []) {
|
|
94
|
+
for (const property of account.propertySummaries ?? []) {
|
|
95
|
+
const id = propertyId(property.property.replace(/^properties\//, ""));
|
|
96
|
+
accounts.set(id, { provider: this.id, id, name: [property.displayName ?? id, account.displayName].filter(Boolean).join(" \u2014 ") });
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
pageToken = result.nextPageToken;
|
|
100
|
+
if (pageToken && seen.has(pageToken)) throw new AdportError2("PROVIDER_ERROR", "GA4 repeated a property pagination token.");
|
|
101
|
+
if (pageToken) seen.add(pageToken);
|
|
102
|
+
} while (pageToken);
|
|
103
|
+
return [...accounts.values()];
|
|
104
|
+
}
|
|
105
|
+
property(accountId) {
|
|
106
|
+
return this.client.request("admin", `properties/${propertyId(accountId)}`);
|
|
107
|
+
}
|
|
108
|
+
metadata(accountId) {
|
|
109
|
+
return this.client.request("data", `properties/${propertyId(accountId)}/metadata`);
|
|
110
|
+
}
|
|
111
|
+
async analyticsReport(input, realtime = false) {
|
|
112
|
+
const i = realtime ? ga4RealtimeSchema.parse(input) : ga4ReportSchema.parse(input);
|
|
113
|
+
const offset = realtime ? 0 : i.offset;
|
|
114
|
+
const filters = i.dimension_filters.map((filter) => ({ filter: {
|
|
115
|
+
fieldName: filter.field,
|
|
116
|
+
stringFilter: { matchType: filter.match, value: filter.value, caseSensitive: filter.case_sensitive }
|
|
117
|
+
} }));
|
|
118
|
+
const body = {
|
|
119
|
+
dimensions: i.dimensions.map((name) => ({ name })),
|
|
120
|
+
metrics: i.metrics.map((name) => ({ name })),
|
|
121
|
+
...!realtime ? { dateRanges: [{ startDate: i.start_date, endDate: i.end_date }] } : {},
|
|
122
|
+
...filters.length ? { dimensionFilter: filters.length === 1 ? filters[0] : { [i.filter_mode === "and" ? "andGroup" : "orGroup"]: { expressions: filters } } } : {},
|
|
123
|
+
limit: String(i.limit),
|
|
124
|
+
...!realtime ? { offset: String(offset) } : {},
|
|
125
|
+
returnPropertyQuota: true
|
|
126
|
+
};
|
|
127
|
+
const result = await this.client.request("data", `properties/${propertyId(i.account_id)}:${realtime ? "runRealtimeReport" : "runReport"}`, body);
|
|
128
|
+
const dimensions = result.dimensionHeaders ?? [];
|
|
129
|
+
const metrics = result.metricHeaders ?? [];
|
|
130
|
+
const rows = (result.rows ?? []).map((row) => ({
|
|
131
|
+
dimensions: Object.fromEntries(dimensions.map((d, index) => [d.name, row.dimensionValues?.[index]?.value ?? ""])),
|
|
132
|
+
metrics: Object.fromEntries(metrics.map((m, index) => [m.name, row.metricValues?.[index]?.value ?? ""]))
|
|
133
|
+
}));
|
|
134
|
+
const rowCount = Number(result.rowCount ?? rows.length), metadata = result.metadata;
|
|
135
|
+
return {
|
|
136
|
+
provider: this.id,
|
|
137
|
+
account_id: i.account_id,
|
|
138
|
+
report_type: realtime ? "realtime" : "historical",
|
|
139
|
+
rows,
|
|
140
|
+
metric_headers: metrics,
|
|
141
|
+
metadata,
|
|
142
|
+
row_count: rowCount,
|
|
143
|
+
offset,
|
|
144
|
+
limit: i.limit,
|
|
145
|
+
...!realtime && offset + rows.length < rowCount && rows.length ? { next_offset: offset + rows.length, truncated: true } : {},
|
|
146
|
+
notes: [
|
|
147
|
+
realtime ? "Realtime dimensions and metrics differ from historical reporting." : "Dates use the GA4 property reporting time zone.",
|
|
148
|
+
...metadata?.subjectToThresholding ? ["Privacy thresholds may omit data."] : [],
|
|
149
|
+
...Array.isArray(metadata?.samplingMetadatas) && metadata.samplingMetadatas.length ? ["This report contains sampled data."] : []
|
|
150
|
+
],
|
|
151
|
+
property_quota: result.propertyQuota
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
var SearchConsoleProvider = class extends ReadOnlyAnalytics {
|
|
156
|
+
constructor(client) {
|
|
157
|
+
super();
|
|
158
|
+
this.client = client;
|
|
159
|
+
}
|
|
160
|
+
client;
|
|
161
|
+
id = "gsc";
|
|
162
|
+
path(accountId) {
|
|
163
|
+
return `sites/${encodeURIComponent(searchConsoleSite.parse(accountId))}`;
|
|
164
|
+
}
|
|
165
|
+
async listAccounts() {
|
|
166
|
+
const result = await this.client.request("search", "sites");
|
|
167
|
+
return (result.siteEntry ?? []).filter((site) => site.permissionLevel !== "siteUnverifiedUser").map((site) => ({ provider: this.id, id: searchConsoleSite.parse(site.siteUrl), name: site.siteUrl, status: site.permissionLevel }));
|
|
168
|
+
}
|
|
169
|
+
site(accountId) {
|
|
170
|
+
return this.client.request("search", this.path(accountId));
|
|
171
|
+
}
|
|
172
|
+
sitemaps(accountId) {
|
|
173
|
+
return this.client.request("search", `${this.path(accountId)}/sitemaps`);
|
|
174
|
+
}
|
|
175
|
+
inspectUrl(accountId, inspectionUrl) {
|
|
176
|
+
return this.client.request("inspection", "urlInspection/index:inspect", { siteUrl: searchConsoleSite.parse(accountId), inspectionUrl, languageCode: "en-US" });
|
|
177
|
+
}
|
|
178
|
+
async searchAnalytics(input) {
|
|
179
|
+
const i = gscReportSchema.parse(input);
|
|
180
|
+
const result = await this.client.request("search", `${this.path(i.account_id)}/searchAnalytics/query`, {
|
|
181
|
+
startDate: i.start_date,
|
|
182
|
+
endDate: i.end_date,
|
|
183
|
+
dimensions: i.dimensions,
|
|
184
|
+
type: i.type,
|
|
185
|
+
...i.filters.length ? { dimensionFilterGroups: [{ groupType: "and", filters: i.filters }] } : {},
|
|
186
|
+
aggregationType: i.aggregation_type,
|
|
187
|
+
rowLimit: i.limit,
|
|
188
|
+
startRow: i.start_row
|
|
189
|
+
});
|
|
190
|
+
const rows = (result.rows ?? []).map((row) => ({
|
|
191
|
+
dimensions: Object.fromEntries(i.dimensions.map((name, index) => [name, row.keys?.[index] ?? ""])),
|
|
192
|
+
metrics: { clicks: row.clicks, impressions: row.impressions, ctr: row.ctr, position: row.position }
|
|
193
|
+
}));
|
|
194
|
+
return {
|
|
195
|
+
provider: this.id,
|
|
196
|
+
account_id: i.account_id,
|
|
197
|
+
rows,
|
|
198
|
+
start_row: i.start_row,
|
|
199
|
+
limit: i.limit,
|
|
200
|
+
...rows.length === i.limit ? { next_start_row: i.start_row + rows.length, truncated: true } : {},
|
|
201
|
+
aggregation_type: result.responseAggregationType,
|
|
202
|
+
date_range: { start: i.start_date, end: i.end_date, timezone: "America/Los_Angeles" },
|
|
203
|
+
notes: ["Organic Google Search data. The API returns top rows; privacy filtering and API limits can omit queries. CTR is a fraction; position is an average, not a total."]
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
// src/index.ts
|
|
209
|
+
import { ga4Tools as ga4Tools2, gscTools as gscTools2, GA4_SCOPES, GSC_SCOPES } from "@adport/core";
|
|
210
|
+
async function credentials(provider, store) {
|
|
211
|
+
const data = (await store.get(provider))?.data;
|
|
212
|
+
if (data?.client_id && data.client_secret && data.refresh_token) return {
|
|
213
|
+
clientId: data.client_id,
|
|
214
|
+
clientSecret: data.client_secret,
|
|
215
|
+
refreshToken: data.refresh_token
|
|
216
|
+
};
|
|
217
|
+
const prefix = provider.toUpperCase();
|
|
218
|
+
const clientId = process.env[`${prefix}_CLIENT_ID`];
|
|
219
|
+
const clientSecret = process.env[`${prefix}_CLIENT_SECRET`];
|
|
220
|
+
const refreshToken = process.env[`${prefix}_REFRESH_TOKEN`];
|
|
221
|
+
return clientId && clientSecret && refreshToken ? { clientId, clientSecret, refreshToken } : void 0;
|
|
222
|
+
}
|
|
223
|
+
async function createGa4Module(store) {
|
|
224
|
+
const value = await credentials("ga4", store);
|
|
225
|
+
if (!value) return void 0;
|
|
226
|
+
const provider = new Ga4Provider(new AnalyticsClient(value));
|
|
227
|
+
return { provider, tools: ga4Tools(provider) };
|
|
228
|
+
}
|
|
229
|
+
async function createGscModule(store) {
|
|
230
|
+
const value = await credentials("gsc", store);
|
|
231
|
+
if (!value) return void 0;
|
|
232
|
+
const provider = new SearchConsoleProvider(new AnalyticsClient(value));
|
|
233
|
+
return { provider, tools: gscTools(provider) };
|
|
234
|
+
}
|
|
235
|
+
export {
|
|
236
|
+
AnalyticsClient,
|
|
237
|
+
GA4_SCOPES,
|
|
238
|
+
GSC_SCOPES,
|
|
239
|
+
Ga4Provider,
|
|
240
|
+
SearchConsoleProvider,
|
|
241
|
+
createGa4Module,
|
|
242
|
+
createGscModule,
|
|
243
|
+
ga4Tools2 as ga4Tools,
|
|
244
|
+
gscTools2 as gscTools
|
|
245
|
+
};
|
|
246
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/client.ts","../src/provider.ts"],"sourcesContent":["import { ga4Tools, gscTools, type CredentialStore, type ProviderModule } from '@adport/core';\nimport { AnalyticsClient, type AnalyticsCredentials } from './client.js';\nimport { Ga4Provider, SearchConsoleProvider } from './provider.js';\nexport { AnalyticsClient, type AnalyticsCredentials } from './client.js';\nexport { Ga4Provider, SearchConsoleProvider } from './provider.js';\nexport { ga4Tools, gscTools, GA4_SCOPES, GSC_SCOPES } from '@adport/core';\n\nasync function credentials(provider: 'ga4' | 'gsc', store: CredentialStore): Promise<AnalyticsCredentials | undefined> {\n const data = (await store.get(provider))?.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 };\n const prefix = provider.toUpperCase();\n const clientId = process.env[`${prefix}_CLIENT_ID`];\n const clientSecret = process.env[`${prefix}_CLIENT_SECRET`];\n const refreshToken = process.env[`${prefix}_REFRESH_TOKEN`];\n return clientId && clientSecret && refreshToken ? { clientId, clientSecret, refreshToken } : undefined;\n}\nexport async function createGa4Module(store: CredentialStore): Promise<ProviderModule | undefined> {\n const value = await credentials('ga4', store); if (!value) return undefined;\n const provider = new Ga4Provider(new AnalyticsClient(value)); return { provider, tools: ga4Tools(provider) };\n}\nexport async function createGscModule(store: CredentialStore): Promise<ProviderModule | undefined> {\n const value = await credentials('gsc', store); if (!value) return undefined;\n const provider = new SearchConsoleProvider(new AnalyticsClient(value)); return { provider, tools: gscTools(provider) };\n}\n","import { AdportError } from '@adport/core';\n\nexport interface AnalyticsCredentials { clientId: string; clientSecret: string; refreshToken: string }\nexport type Resource = Record<string, unknown>;\nconst services = {\n admin: { origin: 'https://analyticsadmin.googleapis.com/v1beta/', get: /^(?:accountSummaries|properties\\/\\d+)$/, post: /^$/ },\n data: { origin: 'https://analyticsdata.googleapis.com/v1beta/', get: /^properties\\/\\d+\\/metadata$/, post: /^properties\\/\\d+:(?:runReport|runRealtimeReport)$/ },\n search: { origin: 'https://www.googleapis.com/webmasters/v3/', get: /^sites(?:\\/[^/]+(?:\\/sitemaps)?)?$/, post: /^sites\\/[^/]+\\/searchAnalytics\\/query$/ },\n inspection: { origin: 'https://searchconsole.googleapis.com/v1/', get: /^$/, post: /^urlInspection\\/index:inspect$/ },\n} as const;\n\n/** Only documented read endpoints are reachable, including POST-based reporting queries. */\nexport class AnalyticsClient {\n private token?: { value: string; until: number };\n constructor(private readonly credentials: AnalyticsCredentials, private readonly fetchImpl: typeof fetch = fetch) {}\n async request(service: keyof typeof services, path: string, body?: unknown, query: Record<string, string> = {}): Promise<Resource> {\n const api = services[service];\n if (!(body === undefined ? api.get : api.post).test(path) || !path) throw new AdportError('INVALID_INPUT', 'Unsupported analytics read endpoint.');\n if (!this.token || this.token.until <= Date.now()) {\n const response = await this.fetchImpl('https://oauth2.googleapis.com/token', {\n method: 'POST', redirect: 'error', signal: AbortSignal.timeout(30_000),\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({ client_id: this.credentials.clientId, client_secret: this.credentials.clientSecret,\n refresh_token: this.credentials.refreshToken, grant_type: 'refresh_token' }),\n });\n const token = await response.json().catch(() => ({})) as { access_token?: string; expires_in?: number };\n if (!response.ok || typeof token.access_token !== 'string' || !token.access_token) throw new AdportError('NOT_CONNECTED', 'Google analytics authorization expired or was revoked. Reconnect this analytics source.');\n this.token = { value: token.access_token, until: Date.now() + Math.max(0, Number(token.expires_in ?? 3600) - 60) * 1000 };\n }\n const params = new URLSearchParams(query);\n const response = await this.fetchImpl(`${api.origin}${path}${params.size ? `?${params}` : ''}`, {\n method: body === undefined ? 'GET' : 'POST', redirect: 'error', signal: AbortSignal.timeout(30_000),\n headers: { authorization: `Bearer ${this.token.value}`, 'content-type': 'application/json' },\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n });\n const result = await response.json().catch(() => ({})) as Resource;\n if (response.status === 401) throw new AdportError('NOT_CONNECTED', 'Google analytics authorization is no longer valid. Reconnect this analytics source.');\n if (!response.ok) throw new AdportError('PROVIDER_ERROR', `Google analytics read failed (HTTP ${response.status}). Check API enablement, property access and requested fields.`, { status: response.status });\n return result;\n }\n}\n","import { AdportError, ga4ReportSchema, ga4RealtimeSchema, gscReportSchema, searchConsoleSite,\n type AdProvider, type Account, type NormalizedQuery, type Report, type WriteOperation,\n type WritePreview, type WriteResult, type Ga4ReportInput, type Ga4RealtimeInput, type GscReportInput } from '@adport/core';\nimport { AnalyticsClient, type Resource } from './client.js';\n\nfunction propertyId(value: string): string {\n if (!/^\\d+$/.test(value)) throw new AdportError('INVALID_INPUT', 'GA4 property IDs must be numeric.');\n return value;\n}\nabstract class ReadOnlyAnalytics implements AdProvider {\n abstract readonly id: string;\n abstract listAccounts(): Promise<Account[]>;\n capabilities() { return { serverDryRun: false, reporting: false }; }\n async report(_query: NormalizedQuery): Promise<Report> { throw new AdportError('INVALID_INPUT', `Use the ${this.id} reporting tools for analytics-specific dimensions and metrics.`); }\n async previewWrite(_op: WriteOperation): Promise<WritePreview> { throw new AdportError('POLICY_VIOLATION', 'This analytics integration is read-only.'); }\n async applyWrite(_op: WriteOperation): Promise<WriteResult> { throw new AdportError('POLICY_VIOLATION', 'This analytics integration is read-only.'); }\n}\n\nexport class Ga4Provider extends ReadOnlyAnalytics {\n readonly id = 'ga4';\n constructor(private readonly client: AnalyticsClient) { super(); }\n async listAccounts(): Promise<Account[]> {\n const accounts = new Map<string, Account>(), seen = new Set<string>();\n let pageToken: string | undefined;\n do {\n const result = await this.client.request('admin', 'accountSummaries', undefined, { pageSize: '200', ...(pageToken ? { pageToken } : {}) });\n for (const account of (result.accountSummaries ?? []) as Array<{ displayName?: string; propertySummaries?: Array<{ property: string; displayName?: string }> }>) {\n for (const property of account.propertySummaries ?? []) {\n const id = propertyId(property.property.replace(/^properties\\//, ''));\n accounts.set(id, { provider: this.id, id, name: [property.displayName ?? id, account.displayName].filter(Boolean).join(' — ') });\n }\n }\n pageToken = result.nextPageToken as string | undefined;\n if (pageToken && seen.has(pageToken)) throw new AdportError('PROVIDER_ERROR', 'GA4 repeated a property pagination token.');\n if (pageToken) seen.add(pageToken);\n } while (pageToken);\n return [...accounts.values()];\n }\n property(accountId: string) { return this.client.request('admin', `properties/${propertyId(accountId)}`); }\n metadata(accountId: string) { return this.client.request('data', `properties/${propertyId(accountId)}/metadata`); }\n async analyticsReport(input: Ga4ReportInput | Ga4RealtimeInput, realtime = false) {\n const i = realtime ? ga4RealtimeSchema.parse(input) : ga4ReportSchema.parse(input);\n const offset = realtime ? 0 : (i as Ga4ReportInput).offset;\n const filters = i.dimension_filters.map(filter => ({ filter: { fieldName: filter.field,\n stringFilter: { matchType: filter.match, value: filter.value, caseSensitive: filter.case_sensitive } } }));\n const body = {\n dimensions: i.dimensions.map(name => ({ name })), metrics: i.metrics.map(name => ({ name })),\n ...(!realtime ? { dateRanges: [{ startDate: (i as Ga4ReportInput).start_date, endDate: (i as Ga4ReportInput).end_date }] } : {}),\n ...(filters.length ? { dimensionFilter: filters.length === 1 ? filters[0] : { [i.filter_mode === 'and' ? 'andGroup' : 'orGroup']: { expressions: filters } } } : {}),\n limit: String(i.limit), ...(!realtime ? { offset: String(offset) } : {}), returnPropertyQuota: true,\n };\n const result = await this.client.request('data', `properties/${propertyId(i.account_id)}:${realtime ? 'runRealtimeReport' : 'runReport'}`, body);\n const dimensions = (result.dimensionHeaders ?? []) as Array<{ name: string }>;\n const metrics = (result.metricHeaders ?? []) as Array<{ name: string; type: string }>;\n const rows = ((result.rows ?? []) as Array<{ dimensionValues?: Array<{ value: string }>; metricValues?: Array<{ value: string }> }>).map(row => ({\n dimensions: Object.fromEntries(dimensions.map((d, index) => [d.name, row.dimensionValues?.[index]?.value ?? ''])),\n metrics: Object.fromEntries(metrics.map((m, index) => [m.name, row.metricValues?.[index]?.value ?? ''])),\n }));\n const rowCount = Number(result.rowCount ?? rows.length), metadata = result.metadata as Resource | undefined;\n return { provider: this.id, account_id: i.account_id, report_type: realtime ? 'realtime' : 'historical',\n rows, metric_headers: metrics, metadata, row_count: rowCount, offset, limit: i.limit,\n ...(!realtime && offset + rows.length < rowCount && rows.length ? { next_offset: offset + rows.length, truncated: true } : {}),\n notes: [realtime ? 'Realtime dimensions and metrics differ from historical reporting.' : 'Dates use the GA4 property reporting time zone.',\n ...(metadata?.subjectToThresholding ? ['Privacy thresholds may omit data.'] : []),\n ...(Array.isArray(metadata?.samplingMetadatas) && metadata.samplingMetadatas.length ? ['This report contains sampled data.'] : [])],\n property_quota: result.propertyQuota };\n }\n}\n\nexport class SearchConsoleProvider extends ReadOnlyAnalytics {\n readonly id = 'gsc';\n constructor(private readonly client: AnalyticsClient) { super(); }\n private path(accountId: string) { return `sites/${encodeURIComponent(searchConsoleSite.parse(accountId))}`; }\n async listAccounts(): Promise<Account[]> {\n const result = await this.client.request('search', 'sites');\n return ((result.siteEntry ?? []) as Array<{ siteUrl: string; permissionLevel: string }>).filter(site => site.permissionLevel !== 'siteUnverifiedUser')\n .map(site => ({ provider: this.id, id: searchConsoleSite.parse(site.siteUrl), name: site.siteUrl, status: site.permissionLevel }));\n }\n site(accountId: string) { return this.client.request('search', this.path(accountId)); }\n sitemaps(accountId: string) { return this.client.request('search', `${this.path(accountId)}/sitemaps`); }\n inspectUrl(accountId: string, inspectionUrl: string) {\n return this.client.request('inspection', 'urlInspection/index:inspect', { siteUrl: searchConsoleSite.parse(accountId), inspectionUrl, languageCode: 'en-US' });\n }\n async searchAnalytics(input: GscReportInput) {\n const i = gscReportSchema.parse(input);\n const result = await this.client.request('search', `${this.path(i.account_id)}/searchAnalytics/query`, {\n startDate: i.start_date, endDate: i.end_date, dimensions: i.dimensions, type: i.type,\n ...(i.filters.length ? { dimensionFilterGroups: [{ groupType: 'and', filters: i.filters }] } : {}),\n aggregationType: i.aggregation_type, rowLimit: i.limit, startRow: i.start_row,\n });\n const rows = ((result.rows ?? []) as Array<{ keys?: string[]; clicks: number; impressions: number; ctr: number; position: number }>).map(row => ({\n dimensions: Object.fromEntries(i.dimensions.map((name, index) => [name, row.keys?.[index] ?? ''])),\n metrics: { clicks: row.clicks, impressions: row.impressions, ctr: row.ctr, position: row.position },\n }));\n return { provider: this.id, account_id: i.account_id, rows, start_row: i.start_row, limit: i.limit,\n ...(rows.length === i.limit ? { next_start_row: i.start_row + rows.length, truncated: true } : {}),\n aggregation_type: result.responseAggregationType, date_range: { start: i.start_date, end: i.end_date, timezone: 'America/Los_Angeles' },\n notes: ['Organic Google Search data. The API returns top rows; privacy filtering and API limits can omit queries. CTR is a fraction; position is an average, not a total.'] };\n }\n}\n"],"mappings":";AAAA,SAAS,UAAU,gBAA2D;;;ACA9E,SAAS,mBAAmB;AAI5B,IAAM,WAAW;AAAA,EACf,OAAO,EAAE,QAAQ,iDAAiD,KAAK,0CAA0C,MAAM,KAAK;AAAA,EAC5H,MAAM,EAAE,QAAQ,gDAAgD,KAAK,+BAA+B,MAAM,oDAAoD;AAAA,EAC9J,QAAQ,EAAE,QAAQ,6CAA6C,KAAK,sCAAsC,MAAM,yCAAyC;AAAA,EACzJ,YAAY,EAAE,QAAQ,4CAA4C,KAAK,MAAM,MAAM,iCAAiC;AACtH;AAGO,IAAM,kBAAN,MAAsB;AAAA,EAE3B,YAA6BA,cAAoD,YAA0B,OAAO;AAArF,uBAAAA;AAAoD;AAAA,EAAkC;AAAA,EAAtF;AAAA,EAAoD;AAAA,EADzE;AAAA,EAER,MAAM,QAAQ,SAAgC,MAAc,MAAgB,QAAgC,CAAC,GAAsB;AACjI,UAAM,MAAM,SAAS,OAAO;AAC5B,QAAI,EAAE,SAAS,SAAY,IAAI,MAAM,IAAI,MAAM,KAAK,IAAI,KAAK,CAAC,KAAM,OAAM,IAAI,YAAY,iBAAiB,sCAAsC;AACjJ,QAAI,CAAC,KAAK,SAAS,KAAK,MAAM,SAAS,KAAK,IAAI,GAAG;AACjD,YAAMC,YAAW,MAAM,KAAK,UAAU,uCAAuC;AAAA,QAC3E,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AAc,KAAK;AAAA,IAAe,cAAc,KAAK;AAAA,EACjF;AACA,QAAM,SAAS,SAAS,YAAY;AACpC,QAAM,WAAW,QAAQ,IAAI,GAAG,MAAM,YAAY;AAClD,QAAM,eAAe,QAAQ,IAAI,GAAG,MAAM,gBAAgB;AAC1D,QAAM,eAAe,QAAQ,IAAI,GAAG,MAAM,gBAAgB;AAC1D,SAAO,YAAY,gBAAgB,eAAe,EAAE,UAAU,cAAc,aAAa,IAAI;AAC/F;AACA,eAAsB,gBAAgB,OAA6D;AACjG,QAAM,QAAQ,MAAM,YAAY,OAAO,KAAK;AAAG,MAAI,CAAC,MAAO,QAAO;AAClE,QAAM,WAAW,IAAI,YAAY,IAAI,gBAAgB,KAAK,CAAC;AAAG,SAAO,EAAE,UAAU,OAAO,SAAS,QAAQ,EAAE;AAC7G;AACA,eAAsB,gBAAgB,OAA6D;AACjG,QAAM,QAAQ,MAAM,YAAY,OAAO,KAAK;AAAG,MAAI,CAAC,MAAO,QAAO;AAClE,QAAM,WAAW,IAAI,sBAAsB,IAAI,gBAAgB,KAAK,CAAC;AAAG,SAAO,EAAE,UAAU,OAAO,SAAS,QAAQ,EAAE;AACvH;","names":["credentials","response","AdportError","ga4Tools","gscTools"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,48 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@adport/provider-analytics",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.10.0",
|
|
4
|
+
"description": "Read-only Google Analytics 4 and Search Console providers 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.6.7",
|
|
20
|
+
"@adport/core": "0.10.0"
|
|
21
|
+
},
|
|
22
|
+
"devDependencies": {
|
|
23
|
+
"@types/node": "^26.6.6",
|
|
24
|
+
"tsup": "^8.3.0",
|
|
25
|
+
"typescript": "^5.8.0",
|
|
26
|
+
"vitest": "^4.1.10"
|
|
27
|
+
},
|
|
28
|
+
"repository": {
|
|
29
|
+
"type": "git",
|
|
30
|
+
"url": "git+https://github.com/ynnickw/adport.git",
|
|
31
|
+
"directory": "packages/analytics"
|
|
32
|
+
},
|
|
33
|
+
"homepage": "https://github.com/ynnickw/adport#readme",
|
|
34
|
+
"bugs": {
|
|
35
|
+
"url": "https://github.com/ynnickw/adport/issues"
|
|
36
|
+
},
|
|
37
|
+
"engines": {
|
|
38
|
+
"node": ">=22.13"
|
|
39
|
+
},
|
|
40
|
+
"publishConfig": {
|
|
41
|
+
"access": "public"
|
|
42
|
+
},
|
|
43
|
+
"scripts": {
|
|
44
|
+
"build": "tsup src/index.ts --format esm --dts --sourcemap --clean",
|
|
45
|
+
"test": "vitest run",
|
|
46
|
+
"typecheck": "tsc --noEmit"
|
|
47
|
+
}
|
|
6
48
|
}
|