workers-start 0.8.0 → 0.9.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/CHANGELOG.md +4 -0
- package/README.md +58 -12
- package/dist/google.d.ts +148 -0
- package/dist/google.d.ts.map +1 -0
- package/dist/google.js +224 -0
- package/dist/google.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/package.json +9 -2
- package/src/google.ts +418 -0
- package/src/index.ts +29 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.9.0 (2026-11-20)
|
|
4
|
+
|
|
5
|
+
- `workers-start/google`: Google APIs as a service account on WebCrypto. `googleAccessToken(account, scopes)` signs the JWT and caches the access token per account and scope (shared exchanges, failures not cached), `parseServiceAccount` reads the key file JSON, and `importServiceAccountKey` names a PKCS#1 or non-PEM key. `ga4RunReport`, `ga4BatchRunReports`, `ga4Rows` and `inListFilter` for the GA4 Data API, and `searchConsoleQuery` (with `all: true` paging) for Search Console. Errors throw `GoogleApiError` with Google's status and message.
|
|
6
|
+
|
|
3
7
|
## 0.8.0 (2026-11-20)
|
|
4
8
|
|
|
5
9
|
- `workers-start/access`: `verifyAccessToken(token, config)` checks a Cloudflare Access JWT (RS256 against the team's certs, issuer, audience, `exp`, `nbf`, then an email or service token allowlist) and returns a result with a `code` of `unconfigured`, `unauthenticated`, `forbidden` or `unavailable` instead of throwing. `parseAccessConfig`, `accessToken` (header, then cookie) and `createAccessVerifier` for a verifier with its own key cache and clock.
|
package/README.md
CHANGED
|
@@ -8,18 +8,19 @@ It has no runtime dependencies. Each piece is its own entry point, so an app tak
|
|
|
8
8
|
|
|
9
9
|
Check this list before writing a helper in an app. Anything generic to TanStack Start on Workers that is missing belongs here, with a test, rather than in one app.
|
|
10
10
|
|
|
11
|
-
| Entry point | Exports
|
|
12
|
-
| ------------------------------ |
|
|
13
|
-
| `workers-start/entry` | `createEntry`, `withHeaders`, `wantsMarkdown`, `acceptsHtml`
|
|
14
|
-
| `workers-start/head` | `createPageHead`, `jsonLdScript`
|
|
15
|
-
| `workers-start/scripts` | `themeScript`, `analyticsScript`, `tagManagerScript`, `gaEvent`, `inlineJson`
|
|
16
|
-
| `workers-start/cache` | `withEdgeCache`, `sharedMaxAge`, `withoutBrowserMaxAge`
|
|
17
|
-
| `workers-start/workers` | `getBinding`, `getEnvString`, `afterResponse`, `isKvNamespace`
|
|
18
|
-
| `workers-start/access` | `verifyAccessToken`, `createAccessVerifier`, `parseAccessConfig`, `accessToken`
|
|
19
|
-
| `workers-start/access/testing` | `createTestAccessTeam`
|
|
20
|
-
| `workers-start/
|
|
21
|
-
| `workers-start/
|
|
22
|
-
| `workers-start/
|
|
11
|
+
| Entry point | Exports | For |
|
|
12
|
+
| ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
|
|
13
|
+
| `workers-start/entry` | `createEntry`, `withHeaders`, `wantsMarkdown`, `acceptsHtml` | The Worker entry: Markdown for agents, Accept fixes, 405s, headers on every response |
|
|
14
|
+
| `workers-start/head` | `createPageHead`, `jsonLdScript` | Per-route head tags and escaped JSON-LD |
|
|
15
|
+
| `workers-start/scripts` | `themeScript`, `analyticsScript`, `tagManagerScript`, `gaEvent`, `inlineJson` | Inline bootstraps, analytics events, JSON safe inside a script tag |
|
|
16
|
+
| `workers-start/cache` | `withEdgeCache`, `sharedMaxAge`, `withoutBrowserMaxAge` | Rendered pages kept in the Workers Cache API |
|
|
17
|
+
| `workers-start/workers` | `getBinding`, `getEnvString`, `afterResponse`, `isKvNamespace` | Bindings and `waitUntil` without a static `cloudflare:workers` import |
|
|
18
|
+
| `workers-start/access` | `verifyAccessToken`, `createAccessVerifier`, `parseAccessConfig`, `accessToken` | Cloudflare Access sign-ins checked in the Worker, failing closed |
|
|
19
|
+
| `workers-start/access/testing` | `createTestAccessTeam` | A fake Access team for tests: keys, certs and signed tokens |
|
|
20
|
+
| `workers-start/google` | `googleAccessToken`, `parseServiceAccount`, `ga4RunReport`, `ga4BatchRunReports`, `ga4Rows`, `inListFilter`, `searchConsoleQuery` | Google APIs as a service account: cached tokens, GA4 reports, Search Console |
|
|
21
|
+
| `workers-start/seo` | `sitemapXml`, `robotsTxt`, `escapeXml` | `/sitemap.xml` and `/robots.txt` bodies |
|
|
22
|
+
| `workers-start/accept` | `parseAccept`, `quality` | Accept header parsing |
|
|
23
|
+
| `workers-start/check-bundle` | `workers-start-check-bundle` (bin) | Fails a build that would ship a local secret |
|
|
23
24
|
|
|
24
25
|
## Why
|
|
25
26
|
|
|
@@ -234,6 +235,51 @@ const result = await verify(await team.token("admin@example.com"), team.config);
|
|
|
234
235
|
// { ok: true, email: "admin@example.com" }
|
|
235
236
|
```
|
|
236
237
|
|
|
238
|
+
## Google APIs
|
|
239
|
+
|
|
240
|
+
`workers-start/google` calls Google as a service account with WebCrypto and `fetch`, so it runs in a Worker as well as in Node scripts. It covers the parts apps keep rewriting: the signed JWT exchanged for an access token, the GA4 Data API and Search Console.
|
|
241
|
+
|
|
242
|
+
```ts
|
|
243
|
+
import {
|
|
244
|
+
GA4_SCOPE,
|
|
245
|
+
ga4Rows,
|
|
246
|
+
ga4RunReport,
|
|
247
|
+
googleAccessToken,
|
|
248
|
+
parseServiceAccount,
|
|
249
|
+
SEARCH_CONSOLE_SCOPE,
|
|
250
|
+
searchConsoleQuery,
|
|
251
|
+
} from "workers-start/google";
|
|
252
|
+
|
|
253
|
+
const account = parseServiceAccount(env.GA_SA_JSON); // the key file JSON
|
|
254
|
+
if (!account) throw new Error("GA_SA_JSON is not a service account key");
|
|
255
|
+
const token = await googleAccessToken(account, [
|
|
256
|
+
GA4_SCOPE,
|
|
257
|
+
SEARCH_CONSOLE_SCOPE,
|
|
258
|
+
]);
|
|
259
|
+
|
|
260
|
+
const report = await ga4RunReport(token, env.GA_PROPERTY_ID, {
|
|
261
|
+
dimensions: [{ name: "pagePath" }],
|
|
262
|
+
metrics: [{ name: "screenPageViews" }],
|
|
263
|
+
dateRanges: [{ startDate: "28daysAgo", endDate: "today" }],
|
|
264
|
+
orderBys: [{ metric: { metricName: "screenPageViews" }, desc: true }],
|
|
265
|
+
limit: 10,
|
|
266
|
+
});
|
|
267
|
+
const pages = ga4Rows(report); // [{ pagePath: "/", screenPageViews: 120 }, ...]
|
|
268
|
+
|
|
269
|
+
const queries = await searchConsoleQuery(token, "sc-domain:example.com", {
|
|
270
|
+
startDate: "2026-10-20",
|
|
271
|
+
endDate: "2026-11-17",
|
|
272
|
+
dimensions: ["query"],
|
|
273
|
+
});
|
|
274
|
+
```
|
|
275
|
+
|
|
276
|
+
- An account comes from the key file JSON with `parseServiceAccount`, or from separate vars as `{ clientEmail, privateKey }`. Escaped `\n` in the key is fine. A PKCS#1 key (`BEGIN RSA PRIVATE KEY`) or a value that is not a PEM fails with an error that says so.
|
|
277
|
+
- `googleAccessToken` caches tokens in the isolate per account and scope until five minutes before they expire. Concurrent calls share one exchange, and a failed exchange is not cached. `createGoogleAuth({ fetch, now, marginSeconds })` makes a token source with its own cache, for tests.
|
|
278
|
+
- The API helpers take a token, not an account, so a token from anywhere (such as gcloud impersonation in a script) works too. Each takes `{ fetch, timeoutMs }` (10 seconds by default).
|
|
279
|
+
- `ga4Rows(report)` keys each row by header name, dimensions as strings and metrics as numbers; `{ totals: true }` reads the totals rows. `ga4BatchRunReports` sends up to five reports in one call. `inListFilter(field, values)` builds the common dimension filter.
|
|
280
|
+
- `searchConsoleQuery` fills missing fields with zeros and treats a reply with no `rows` as no rows. `{ all: true }` pages with `startRow` until a short page.
|
|
281
|
+
- A Google error status throws `GoogleApiError` with `status`, Google's message and its JSON `body`.
|
|
282
|
+
|
|
237
283
|
## Sitemap and robots.txt
|
|
238
284
|
|
|
239
285
|
`workers-start/seo` builds the bodies for `/sitemap.xml` and `/robots.txt` routes. The entries and options take the same shape as Next's `MetadataRoute.Sitemap` and `MetadataRoute.Robots`.
|
package/dist/google.d.ts
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Google APIs as a service account, on WebCrypto and `fetch` only: the signed
|
|
3
|
+
* JWT exchanged for an access token (cached per account and scope), the GA4
|
|
4
|
+
* Data API's `runReport` and `batchRunReports`, and Search Console's
|
|
5
|
+
* `searchAnalytics.query`. Runs in workerd and Node.
|
|
6
|
+
*
|
|
7
|
+
* The API helpers take a token rather than an account, so a token from
|
|
8
|
+
* anywhere (gcloud impersonation in a script, say) works with them too.
|
|
9
|
+
*/
|
|
10
|
+
export declare const GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token";
|
|
11
|
+
export declare const GA4_SCOPE = "https://www.googleapis.com/auth/analytics.readonly";
|
|
12
|
+
export declare const SEARCH_CONSOLE_SCOPE = "https://www.googleapis.com/auth/webmasters.readonly";
|
|
13
|
+
export interface ServiceAccount {
|
|
14
|
+
clientEmail: string;
|
|
15
|
+
/** The PKCS#8 PEM. Escaped `\n` sequences are fine. */
|
|
16
|
+
privateKey: string;
|
|
17
|
+
/** Sent as the JWT's `kid` when present. */
|
|
18
|
+
privateKeyId?: string | undefined;
|
|
19
|
+
/** Defaults to Google's token endpoint. */
|
|
20
|
+
tokenUri?: string | undefined;
|
|
21
|
+
}
|
|
22
|
+
/** A Google API answered with an error status. */
|
|
23
|
+
export declare class GoogleApiError extends Error {
|
|
24
|
+
readonly status: number;
|
|
25
|
+
/** Google's error body, when it sent JSON. */
|
|
26
|
+
readonly body?: unknown;
|
|
27
|
+
readonly name = "GoogleApiError";
|
|
28
|
+
constructor(message: string, status: number,
|
|
29
|
+
/** Google's error body, when it sent JSON. */
|
|
30
|
+
body?: unknown);
|
|
31
|
+
}
|
|
32
|
+
/** The key file JSON (`client_email`, `private_key`, ...) as an account, or null when it is not one. */
|
|
33
|
+
export declare function parseServiceAccount(raw: string | undefined | null): ServiceAccount | null;
|
|
34
|
+
/**
|
|
35
|
+
* Imports the account's private key for signing. Throws a clear error for a
|
|
36
|
+
* PKCS#1 key (`BEGIN RSA PRIVATE KEY`, which WebCrypto cannot import) or for
|
|
37
|
+
* a value that is not a PEM at all.
|
|
38
|
+
*/
|
|
39
|
+
export declare function importServiceAccountKey(pem: string): Promise<CryptoKey>;
|
|
40
|
+
/** The signed RS256 assertion Google exchanges for an access token. */
|
|
41
|
+
export declare function serviceAccountJwt(account: ServiceAccount, scopes: string | readonly string[], nowMs?: number): Promise<string>;
|
|
42
|
+
type Fetch = (url: string, init?: RequestInit) => Promise<Response>;
|
|
43
|
+
export interface GoogleAuthOptions {
|
|
44
|
+
fetch?: Fetch;
|
|
45
|
+
/** Milliseconds since the epoch. */
|
|
46
|
+
now?: () => number;
|
|
47
|
+
/** Refresh this many seconds before the token expires. Default 300. */
|
|
48
|
+
marginSeconds?: number;
|
|
49
|
+
}
|
|
50
|
+
export type GoogleTokenSource = (account: ServiceAccount, scopes: string | readonly string[]) => Promise<string>;
|
|
51
|
+
/**
|
|
52
|
+
* A token source with its own cache. Tokens are kept per account and scope
|
|
53
|
+
* until `marginSeconds` before they expire. Concurrent calls share one
|
|
54
|
+
* exchange, and a failed exchange is not cached.
|
|
55
|
+
*/
|
|
56
|
+
export declare function createGoogleAuth(options?: GoogleAuthOptions): GoogleTokenSource;
|
|
57
|
+
/** An access token from a token source shared by the whole isolate. */
|
|
58
|
+
export declare function googleAccessToken(account: ServiceAccount, scopes: string | readonly string[]): Promise<string>;
|
|
59
|
+
export interface GoogleCallOptions {
|
|
60
|
+
fetch?: Fetch;
|
|
61
|
+
/** Abort after this long. Default 10 seconds. */
|
|
62
|
+
timeoutMs?: number;
|
|
63
|
+
}
|
|
64
|
+
export interface Ga4DateRange {
|
|
65
|
+
startDate: string;
|
|
66
|
+
endDate: string;
|
|
67
|
+
name?: string;
|
|
68
|
+
}
|
|
69
|
+
/** A GA4 filter expression, passed through as Google defines it. */
|
|
70
|
+
export type Ga4FilterExpression = Record<string, unknown>;
|
|
71
|
+
export interface Ga4ReportRequest {
|
|
72
|
+
dimensions?: {
|
|
73
|
+
name: string;
|
|
74
|
+
}[];
|
|
75
|
+
metrics: {
|
|
76
|
+
name: string;
|
|
77
|
+
}[];
|
|
78
|
+
dateRanges: Ga4DateRange[];
|
|
79
|
+
dimensionFilter?: Ga4FilterExpression;
|
|
80
|
+
metricFilter?: Ga4FilterExpression;
|
|
81
|
+
orderBys?: Record<string, unknown>[];
|
|
82
|
+
limit?: number;
|
|
83
|
+
offset?: number;
|
|
84
|
+
metricAggregations?: ("TOTAL" | "MAXIMUM" | "MINIMUM" | "COUNT")[];
|
|
85
|
+
keepEmptyRows?: boolean;
|
|
86
|
+
}
|
|
87
|
+
interface Ga4Row {
|
|
88
|
+
dimensionValues?: {
|
|
89
|
+
value?: string;
|
|
90
|
+
}[];
|
|
91
|
+
metricValues?: {
|
|
92
|
+
value?: string;
|
|
93
|
+
}[];
|
|
94
|
+
}
|
|
95
|
+
export interface Ga4Report {
|
|
96
|
+
dimensionHeaders?: {
|
|
97
|
+
name: string;
|
|
98
|
+
}[];
|
|
99
|
+
metricHeaders?: {
|
|
100
|
+
name: string;
|
|
101
|
+
type?: string;
|
|
102
|
+
}[];
|
|
103
|
+
rows?: Ga4Row[];
|
|
104
|
+
totals?: Ga4Row[];
|
|
105
|
+
rowCount?: number;
|
|
106
|
+
}
|
|
107
|
+
/** One GA4 report. `propertyId` is the number, with or without `properties/`. */
|
|
108
|
+
export declare function ga4RunReport(token: string, propertyId: string, request: Ga4ReportRequest, options?: GoogleCallOptions): Promise<Ga4Report>;
|
|
109
|
+
/** Up to five GA4 reports in one call, in order. */
|
|
110
|
+
export declare function ga4BatchRunReports(token: string, propertyId: string, requests: readonly Ga4ReportRequest[], options?: GoogleCallOptions): Promise<Ga4Report[]>;
|
|
111
|
+
export type Ga4RowObject = Record<string, string | number>;
|
|
112
|
+
/**
|
|
113
|
+
* A report's rows as objects keyed by header name: dimensions as strings,
|
|
114
|
+
* metrics as numbers. `totals: true` reads the totals rows instead.
|
|
115
|
+
*/
|
|
116
|
+
export declare function ga4Rows(report: Ga4Report, { totals }?: {
|
|
117
|
+
totals?: boolean;
|
|
118
|
+
}): Ga4RowObject[];
|
|
119
|
+
/** A filter matching a dimension against a list of values. */
|
|
120
|
+
export declare function inListFilter(fieldName: string, values: readonly string[]): Ga4FilterExpression;
|
|
121
|
+
export interface SearchAnalyticsQuery {
|
|
122
|
+
startDate: string;
|
|
123
|
+
endDate: string;
|
|
124
|
+
dimensions?: ("query" | "page" | "country" | "device" | "date" | "searchAppearance")[];
|
|
125
|
+
type?: "web" | "image" | "video" | "news" | "discover" | "googleNews";
|
|
126
|
+
dimensionFilterGroups?: Record<string, unknown>[];
|
|
127
|
+
aggregationType?: "auto" | "byPage" | "byProperty";
|
|
128
|
+
dataState?: "final" | "all";
|
|
129
|
+
rowLimit?: number;
|
|
130
|
+
startRow?: number;
|
|
131
|
+
}
|
|
132
|
+
export interface SearchAnalyticsRow {
|
|
133
|
+
keys: string[];
|
|
134
|
+
clicks: number;
|
|
135
|
+
impressions: number;
|
|
136
|
+
ctr: number;
|
|
137
|
+
position: number;
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Search Console rows for `siteUrl` (`sc-domain:example.com` or a URL
|
|
141
|
+
* prefix). With `all: true` it pages with `startRow` until Google returns a
|
|
142
|
+
* short page.
|
|
143
|
+
*/
|
|
144
|
+
export declare function searchConsoleQuery(token: string, siteUrl: string, query: SearchAnalyticsQuery, options?: GoogleCallOptions & {
|
|
145
|
+
all?: boolean;
|
|
146
|
+
}): Promise<SearchAnalyticsRow[]>;
|
|
147
|
+
export {};
|
|
148
|
+
//# sourceMappingURL=google.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"google.d.ts","sourceRoot":"","sources":["../src/google.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,eAAO,MAAM,gBAAgB,wCAA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BAAgB,YAAY,CAC1B,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,SAAS,MAAM,EAAE,GACxB,mBAAmB,CAErB;AAID,MAAM,WAAW,oBAAoB;IACnC,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,CAAC,EAAE,CACT,OAAO,GACP,MAAM,GACN,SAAS,GACT,QAAQ,GACR,MAAM,GACN,kBAAkB,CACrB,EAAE,CAAC;IACJ,IAAI,CAAC,EAAE,KAAK,GAAG,OAAO,GAAG,OAAO,GAAG,MAAM,GAAG,UAAU,GAAG,YAAY,CAAC;IACtE,qBAAqB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAC;IAClD,eAAe,CAAC,EAAE,MAAM,GAAG,QAAQ,GAAG,YAAY,CAAC;IACnD,SAAS,CAAC,EAAE,OAAO,GAAG,KAAK,CAAC;IAC5B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,kBAAkB;IACjC,IAAI,EAAE,MAAM,EAAE,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,WAAW,EAAE,MAAM,CAAC;IACpB,GAAG,EAAE,MAAM,CAAC;IACZ,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED;;;;GAIG;AACH,wBAAsB,kBAAkB,CACtC,KAAK,EAAE,MAAM,EACb,OAAO,EAAE,MAAM,EACf,KAAK,EAAE,oBAAoB,EAC3B,OAAO,GAAE,iBAAiB,GAAG;IAAE,GAAG,CAAC,EAAE,OAAO,CAAA;CAAO,GAClD,OAAO,CAAC,kBAAkB,EAAE,CAAC,CAwB/B"}
|
package/dist/google.js
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Google APIs as a service account, on WebCrypto and `fetch` only: the signed
|
|
3
|
+
* JWT exchanged for an access token (cached per account and scope), the GA4
|
|
4
|
+
* Data API's `runReport` and `batchRunReports`, and Search Console's
|
|
5
|
+
* `searchAnalytics.query`. Runs in workerd and Node.
|
|
6
|
+
*
|
|
7
|
+
* The API helpers take a token rather than an account, so a token from
|
|
8
|
+
* anywhere (gcloud impersonation in a script, say) works with them too.
|
|
9
|
+
*/
|
|
10
|
+
export const GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token";
|
|
11
|
+
export const GA4_SCOPE = "https://www.googleapis.com/auth/analytics.readonly";
|
|
12
|
+
export const SEARCH_CONSOLE_SCOPE = "https://www.googleapis.com/auth/webmasters.readonly";
|
|
13
|
+
/** A Google API answered with an error status. */
|
|
14
|
+
export class GoogleApiError extends Error {
|
|
15
|
+
status;
|
|
16
|
+
body;
|
|
17
|
+
name = "GoogleApiError";
|
|
18
|
+
constructor(message, status,
|
|
19
|
+
/** Google's error body, when it sent JSON. */
|
|
20
|
+
body) {
|
|
21
|
+
super(message);
|
|
22
|
+
this.status = status;
|
|
23
|
+
this.body = body;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/** The key file JSON (`client_email`, `private_key`, ...) as an account, or null when it is not one. */
|
|
27
|
+
export function parseServiceAccount(raw) {
|
|
28
|
+
if (!raw)
|
|
29
|
+
return null;
|
|
30
|
+
try {
|
|
31
|
+
const v = JSON.parse(raw);
|
|
32
|
+
if (typeof v.client_email !== "string" || typeof v.private_key !== "string")
|
|
33
|
+
return null;
|
|
34
|
+
return {
|
|
35
|
+
clientEmail: v.client_email,
|
|
36
|
+
privateKey: v.private_key,
|
|
37
|
+
privateKeyId: typeof v.private_key_id === "string" ? v.private_key_id : undefined,
|
|
38
|
+
tokenUri: typeof v.token_uri === "string" ? v.token_uri : undefined,
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
const PKCS8_HEADER = "-----BEGIN PRIVATE KEY-----";
|
|
46
|
+
const PKCS8_FOOTER = "-----END PRIVATE KEY-----";
|
|
47
|
+
const RS256 = { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" };
|
|
48
|
+
/**
|
|
49
|
+
* Imports the account's private key for signing. Throws a clear error for a
|
|
50
|
+
* PKCS#1 key (`BEGIN RSA PRIVATE KEY`, which WebCrypto cannot import) or for
|
|
51
|
+
* a value that is not a PEM at all.
|
|
52
|
+
*/
|
|
53
|
+
export async function importServiceAccountKey(pem) {
|
|
54
|
+
const text = pem.replace(/\\n/g, "\n").trim();
|
|
55
|
+
if (text.startsWith("-----BEGIN RSA PRIVATE KEY-----")) {
|
|
56
|
+
throw new Error("The private key is PKCS#1 (BEGIN RSA PRIVATE KEY). WebCrypto imports PKCS#8 only (BEGIN PRIVATE KEY), which is what a Google service account key file holds.");
|
|
57
|
+
}
|
|
58
|
+
const start = text.indexOf(PKCS8_HEADER);
|
|
59
|
+
const end = text.indexOf(PKCS8_FOOTER);
|
|
60
|
+
if (start === -1 || end === -1) {
|
|
61
|
+
throw new Error("The private key is not a PEM. Copy the private_key field from the service account JSON as it is.");
|
|
62
|
+
}
|
|
63
|
+
const body = text.slice(start + PKCS8_HEADER.length, end).replace(/\s+/g, "");
|
|
64
|
+
let der;
|
|
65
|
+
try {
|
|
66
|
+
der = Uint8Array.from(atob(body), (ch) => ch.charCodeAt(0));
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
throw new Error("The private key's body is not valid base64.");
|
|
70
|
+
}
|
|
71
|
+
return crypto.subtle.importKey("pkcs8", der, RS256, false, ["sign"]);
|
|
72
|
+
}
|
|
73
|
+
const encoder = new TextEncoder();
|
|
74
|
+
function b64url(data) {
|
|
75
|
+
const bytes = typeof data === "string" ? encoder.encode(data) : data;
|
|
76
|
+
let bin = "";
|
|
77
|
+
for (const b of bytes)
|
|
78
|
+
bin += String.fromCharCode(b);
|
|
79
|
+
return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
80
|
+
}
|
|
81
|
+
/** The signed RS256 assertion Google exchanges for an access token. */
|
|
82
|
+
export async function serviceAccountJwt(account, scopes, nowMs = Date.now()) {
|
|
83
|
+
const iat = Math.floor(nowMs / 1000);
|
|
84
|
+
const header = { alg: "RS256", typ: "JWT" };
|
|
85
|
+
if (account.privateKeyId)
|
|
86
|
+
header.kid = account.privateKeyId;
|
|
87
|
+
const claims = {
|
|
88
|
+
iss: account.clientEmail,
|
|
89
|
+
scope: typeof scopes === "string" ? scopes : scopes.join(" "),
|
|
90
|
+
aud: account.tokenUri ?? GOOGLE_TOKEN_URL,
|
|
91
|
+
iat,
|
|
92
|
+
exp: iat + 3600,
|
|
93
|
+
};
|
|
94
|
+
const input = `${b64url(JSON.stringify(header))}.${b64url(JSON.stringify(claims))}`;
|
|
95
|
+
const key = await importServiceAccountKey(account.privateKey);
|
|
96
|
+
const sig = await crypto.subtle.sign(RS256, key, encoder.encode(input));
|
|
97
|
+
return `${input}.${b64url(new Uint8Array(sig))}`;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* A token source with its own cache. Tokens are kept per account and scope
|
|
101
|
+
* until `marginSeconds` before they expire. Concurrent calls share one
|
|
102
|
+
* exchange, and a failed exchange is not cached.
|
|
103
|
+
*/
|
|
104
|
+
export function createGoogleAuth(options = {}) {
|
|
105
|
+
const { fetch: fetcher = (url, init) => fetch(url, init), now = Date.now, marginSeconds = 300, } = options;
|
|
106
|
+
const cache = new Map();
|
|
107
|
+
return (account, scopes) => {
|
|
108
|
+
const scope = typeof scopes === "string" ? scopes : scopes.join(" ");
|
|
109
|
+
const key = `${account.clientEmail}\n${scope}`;
|
|
110
|
+
const hit = cache.get(key);
|
|
111
|
+
if (hit && hit.expiresAt > now())
|
|
112
|
+
return hit.token;
|
|
113
|
+
const entry = { token: Promise.resolve(""), expiresAt: Infinity };
|
|
114
|
+
entry.token = (async () => {
|
|
115
|
+
const assertion = await serviceAccountJwt(account, scope, now());
|
|
116
|
+
const res = await fetcher(account.tokenUri ?? GOOGLE_TOKEN_URL, {
|
|
117
|
+
method: "POST",
|
|
118
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
119
|
+
body: new URLSearchParams({
|
|
120
|
+
grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
|
|
121
|
+
assertion,
|
|
122
|
+
}).toString(),
|
|
123
|
+
});
|
|
124
|
+
const body = (await res.json().catch(() => null));
|
|
125
|
+
if (!res.ok || !body?.access_token) {
|
|
126
|
+
const why = body?.error_description ?? body?.error ?? "no access token";
|
|
127
|
+
throw new GoogleApiError(`Google token exchange failed (${res.status}): ${why}`, res.status, body);
|
|
128
|
+
}
|
|
129
|
+
entry.expiresAt =
|
|
130
|
+
now() + ((body.expires_in ?? 3600) - marginSeconds) * 1000;
|
|
131
|
+
return body.access_token;
|
|
132
|
+
})();
|
|
133
|
+
entry.token.catch(() => {
|
|
134
|
+
if (cache.get(key) === entry)
|
|
135
|
+
cache.delete(key);
|
|
136
|
+
});
|
|
137
|
+
cache.set(key, entry);
|
|
138
|
+
return entry.token;
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
let shared;
|
|
142
|
+
/** An access token from a token source shared by the whole isolate. */
|
|
143
|
+
export function googleAccessToken(account, scopes) {
|
|
144
|
+
shared ??= createGoogleAuth();
|
|
145
|
+
return shared(account, scopes);
|
|
146
|
+
}
|
|
147
|
+
async function googleJson(url, token, body, { fetch: fetcher = (u, i) => fetch(u, i), timeoutMs = 10_000, }, what) {
|
|
148
|
+
const res = await fetcher(url, {
|
|
149
|
+
method: "POST",
|
|
150
|
+
headers: {
|
|
151
|
+
authorization: `Bearer ${token}`,
|
|
152
|
+
"content-type": "application/json",
|
|
153
|
+
},
|
|
154
|
+
body: JSON.stringify(body),
|
|
155
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
156
|
+
});
|
|
157
|
+
const json = (await res.json().catch(() => null));
|
|
158
|
+
if (!res.ok) {
|
|
159
|
+
const message = json?.error?.message ??
|
|
160
|
+
res.statusText;
|
|
161
|
+
throw new GoogleApiError(`${what} failed (${res.status}): ${message}`, res.status, json);
|
|
162
|
+
}
|
|
163
|
+
return json;
|
|
164
|
+
}
|
|
165
|
+
const ga4Url = (propertyId, method) => `https://analyticsdata.googleapis.com/v1beta/properties/${encodeURIComponent(propertyId.replace(/^properties\//, ""))}:${method}`;
|
|
166
|
+
/** One GA4 report. `propertyId` is the number, with or without `properties/`. */
|
|
167
|
+
export function ga4RunReport(token, propertyId, request, options = {}) {
|
|
168
|
+
return googleJson(ga4Url(propertyId, "runReport"), token, request, options, "GA4 runReport");
|
|
169
|
+
}
|
|
170
|
+
/** Up to five GA4 reports in one call, in order. */
|
|
171
|
+
export async function ga4BatchRunReports(token, propertyId, requests, options = {}) {
|
|
172
|
+
if (requests.length > 5)
|
|
173
|
+
throw new Error("GA4 batchRunReports takes at most 5 reports.");
|
|
174
|
+
const res = await googleJson(ga4Url(propertyId, "batchRunReports"), token, { requests }, options, "GA4 batchRunReports");
|
|
175
|
+
return res.reports ?? [];
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* A report's rows as objects keyed by header name: dimensions as strings,
|
|
179
|
+
* metrics as numbers. `totals: true` reads the totals rows instead.
|
|
180
|
+
*/
|
|
181
|
+
export function ga4Rows(report, { totals = false } = {}) {
|
|
182
|
+
const dims = report.dimensionHeaders?.map((h) => h.name) ?? [];
|
|
183
|
+
const mets = report.metricHeaders?.map((h) => h.name) ?? [];
|
|
184
|
+
return ((totals ? report.totals : report.rows) ?? []).map((row) => {
|
|
185
|
+
const out = {};
|
|
186
|
+
dims.forEach((name, i) => {
|
|
187
|
+
out[name] = row.dimensionValues?.[i]?.value ?? "";
|
|
188
|
+
});
|
|
189
|
+
mets.forEach((name, i) => {
|
|
190
|
+
out[name] = Number(row.metricValues?.[i]?.value ?? 0);
|
|
191
|
+
});
|
|
192
|
+
return out;
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
/** A filter matching a dimension against a list of values. */
|
|
196
|
+
export function inListFilter(fieldName, values) {
|
|
197
|
+
return { filter: { fieldName, inListFilter: { values: [...values] } } };
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* Search Console rows for `siteUrl` (`sc-domain:example.com` or a URL
|
|
201
|
+
* prefix). With `all: true` it pages with `startRow` until Google returns a
|
|
202
|
+
* short page.
|
|
203
|
+
*/
|
|
204
|
+
export async function searchConsoleQuery(token, siteUrl, query, options = {}) {
|
|
205
|
+
const url = `https://www.googleapis.com/webmasters/v3/sites/${encodeURIComponent(siteUrl)}/searchAnalytics/query`;
|
|
206
|
+
const pageSize = query.rowLimit ?? (options.all ? 25_000 : 1_000);
|
|
207
|
+
const rows = [];
|
|
208
|
+
let startRow = query.startRow ?? 0;
|
|
209
|
+
for (;;) {
|
|
210
|
+
const res = await googleJson(url, token, { ...query, rowLimit: pageSize, startRow }, options, "Search Console query");
|
|
211
|
+
const page = (res.rows ?? []).map((r) => ({
|
|
212
|
+
keys: r.keys ?? [],
|
|
213
|
+
clicks: r.clicks ?? 0,
|
|
214
|
+
impressions: r.impressions ?? 0,
|
|
215
|
+
ctr: r.ctr ?? 0,
|
|
216
|
+
position: r.position ?? 0,
|
|
217
|
+
}));
|
|
218
|
+
rows.push(...page);
|
|
219
|
+
if (!options.all || page.length < pageSize)
|
|
220
|
+
return rows;
|
|
221
|
+
startRow += page.length;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
//# sourceMappingURL=google.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"google.js","sourceRoot":"","sources":["../src/google.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,MAAM,CAAC,MAAM,gBAAgB,GAAG,qCAAqC,CAAC;AACtE,MAAM,CAAC,MAAM,SAAS,GAAG,oDAAoD,CAAC;AAC9E,MAAM,CAAC,MAAM,oBAAoB,GAC/B,qDAAqD,CAAC;AAYxD,kDAAkD;AAClD,MAAM,OAAO,cAAe,SAAQ,KAAK;IAI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AAO,EACP,sBAAsB,CACvB,CAAC;QACF,MAAM,IAAI,GAAG,CAAC,GAAG,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;YACxC,IAAI,EAAE,CAAC,CAAC,IAAI,IAAI,EAAE;YAClB,MAAM,EAAE,CAAC,CAAC,MAAM,IAAI,CAAC;YACrB,WAAW,EAAE,CAAC,CAAC,WAAW,IAAI,CAAC;YAC/B,GAAG,EAAE,CAAC,CAAC,GAAG,IAAI,CAAC;YACf,QAAQ,EAAE,CAAC,CAAC,QAAQ,IAAI,CAAC;SAC1B,CAAC,CAAC,CAAC;QACJ,IAAI,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC;QACnB,IAAI,CAAC,OAAO,CAAC,GAAG,IAAI,IAAI,CAAC,MAAM,GAAG,QAAQ;YAAE,OAAO,IAAI,CAAC;QACxD,QAAQ,IAAI,IAAI,CAAC,MAAM,CAAC;IAC1B,CAAC;AACH,CAAC"}
|
package/dist/index.d.ts
CHANGED
|
@@ -6,6 +6,8 @@ export type { EdgeCacheOptions } from "./cache.js";
|
|
|
6
6
|
export { sharedMaxAge, withEdgeCache, withoutBrowserMaxAge, } from "./cache.js";
|
|
7
7
|
export type { EntryOptions, FetchHandler, MarkdownPage, MarkdownResult, } from "./entry.js";
|
|
8
8
|
export { acceptsHtml, createEntry, defaultIsPage, MARKDOWN_HEADERS, mergeVary, normalizePath, underPrefix, wantsMarkdown, withHeaders, } from "./entry.js";
|
|
9
|
+
export type { Ga4DateRange, Ga4FilterExpression, Ga4Report, Ga4ReportRequest, Ga4RowObject, GoogleAuthOptions, GoogleCallOptions, GoogleTokenSource, SearchAnalyticsQuery, SearchAnalyticsRow, ServiceAccount, } from "./google.js";
|
|
10
|
+
export { createGoogleAuth, GA4_SCOPE, GOOGLE_TOKEN_URL, GoogleApiError, ga4BatchRunReports, ga4Rows, ga4RunReport, googleAccessToken, importServiceAccountKey, inListFilter, parseServiceAccount, SEARCH_CONSOLE_SCOPE, searchConsoleQuery, serviceAccountJwt, } from "./google.js";
|
|
9
11
|
export type { HeadLink, HeadScript, HeadTags, MetaTag, PageImage, PageSeo, SiteHead, } from "./head.js";
|
|
10
12
|
export { createPageHead, jsonLdScript } from "./head.js";
|
|
11
13
|
export type { AnalyticsScriptOptions, GaEventParams, TagManagerScriptOptions, ThemeScriptOptions, } from "./scripts.js";
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACnD,YAAY,EACV,YAAY,EACZ,SAAS,EACT,aAAa,EACb,YAAY,EACZ,cAAc,EACd,qBAAqB,GACtB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,WAAW,EACX,oBAAoB,EACpB,iBAAiB,EACjB,iBAAiB,GAClB,MAAM,aAAa,CAAC;AACrB,YAAY,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AACnD,OAAO,EACL,YAAY,EACZ,aAAa,EACb,oBAAoB,GACrB,MAAM,YAAY,CAAC;AACpB,YAAY,EACV,YAAY,EACZ,YAAY,EACZ,YAAY,EACZ,cAAc,GACf,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,WAAW,EACX,WAAW,EACX,aAAa,EACb,gBAAgB,EAChB,SAAS,EACT,aAAa,EACb,WAAW,EACX,aAAa,EACb,WAAW,GACZ,MAAM,YAAY,CAAC;AACpB,YAAY,EACV,QAAQ,EACR,UAAU,EACV,QAAQ,EACR,OAAO,EACP,SAAS,EACT,OAAO,EACP,QAAQ,GACT,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AACzD,YAAY,EACV,sBAAsB,EACtB,aAAa,EACb,uBAAuB,EACvB,kBAAkB,GACnB,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,eAAe,EACf,OAAO,EACP,UAAU,EACV,gBAAgB,EAChB,WAAW,GACZ,MAAM,cAAc,CAAC;AACtB,YAAY,EAAE,aAAa,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AACxE,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AAC5D,YAAY,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAClD,OAAO,EACL,aAAa,EACb,UAAU,EACV,YAAY,EACZ,aAAa,EACb,WAAW,EACX,gBAAgB,GACjB,MAAM,cAAc,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACnD,YAAY,EACV,YAAY,EACZ,SAAS,EACT,aAAa,EACb,YAAY,EACZ,cAAc,EACd,qBAAqB,GACtB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,WAAW,EACX,oBAAoB,EACpB,iBAAiB,EACjB,iBAAiB,GAClB,MAAM,aAAa,CAAC;AACrB,YAAY,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AACnD,OAAO,EACL,YAAY,EACZ,aAAa,EACb,oBAAoB,GACrB,MAAM,YAAY,CAAC;AACpB,YAAY,EACV,YAAY,EACZ,YAAY,EACZ,YAAY,EACZ,cAAc,GACf,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,WAAW,EACX,WAAW,EACX,aAAa,EACb,gBAAgB,EAChB,SAAS,EACT,aAAa,EACb,WAAW,EACX,aAAa,EACb,WAAW,GACZ,MAAM,YAAY,CAAC;AACpB,YAAY,EACV,YAAY,EACZ,mBAAmB,EACnB,SAAS,EACT,gBAAgB,EAChB,YAAY,EACZ,iBAAiB,EACjB,iBAAiB,EACjB,iBAAiB,EACjB,oBAAoB,EACpB,kBAAkB,EAClB,cAAc,GACf,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,gBAAgB,EAChB,SAAS,EACT,gBAAgB,EAChB,cAAc,EACd,kBAAkB,EAClB,OAAO,EACP,YAAY,EACZ,iBAAiB,EACjB,uBAAuB,EACvB,YAAY,EACZ,mBAAmB,EACnB,oBAAoB,EACpB,kBAAkB,EAClB,iBAAiB,GAClB,MAAM,aAAa,CAAC;AACrB,YAAY,EACV,QAAQ,EACR,UAAU,EACV,QAAQ,EACR,OAAO,EACP,SAAS,EACT,OAAO,EACP,QAAQ,GACT,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AACzD,YAAY,EACV,sBAAsB,EACtB,aAAa,EACb,uBAAuB,EACvB,kBAAkB,GACnB,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,eAAe,EACf,OAAO,EACP,UAAU,EACV,gBAAgB,EAChB,WAAW,GACZ,MAAM,cAAc,CAAC;AACtB,YAAY,EAAE,aAAa,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AACxE,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AAC5D,YAAY,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAClD,OAAO,EACL,aAAa,EACb,UAAU,EACV,YAAY,EACZ,aAAa,EACb,WAAW,EACX,gBAAgB,GACjB,MAAM,cAAc,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -2,6 +2,7 @@ export { parseAccept, quality } from "./accept.js";
|
|
|
2
2
|
export { accessToken, createAccessVerifier, parseAccessConfig, verifyAccessToken, } from "./access.js";
|
|
3
3
|
export { sharedMaxAge, withEdgeCache, withoutBrowserMaxAge, } from "./cache.js";
|
|
4
4
|
export { acceptsHtml, createEntry, defaultIsPage, MARKDOWN_HEADERS, mergeVary, normalizePath, underPrefix, wantsMarkdown, withHeaders, } from "./entry.js";
|
|
5
|
+
export { createGoogleAuth, GA4_SCOPE, GOOGLE_TOKEN_URL, GoogleApiError, ga4BatchRunReports, ga4Rows, ga4RunReport, googleAccessToken, importServiceAccountKey, inListFilter, parseServiceAccount, SEARCH_CONSOLE_SCOPE, searchConsoleQuery, serviceAccountJwt, } from "./google.js";
|
|
5
6
|
export { createPageHead, jsonLdScript } from "./head.js";
|
|
6
7
|
export { analyticsScript, gaEvent, inlineJson, tagManagerScript, themeScript, } from "./scripts.js";
|
|
7
8
|
export { escapeXml, robotsTxt, sitemapXml } from "./seo.js";
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AASnD,OAAO,EACL,WAAW,EACX,oBAAoB,EACpB,iBAAiB,EACjB,iBAAiB,GAClB,MAAM,aAAa,CAAC;AAErB,OAAO,EACL,YAAY,EACZ,aAAa,EACb,oBAAoB,GACrB,MAAM,YAAY,CAAC;AAOpB,OAAO,EACL,WAAW,EACX,WAAW,EACX,aAAa,EACb,gBAAgB,EAChB,SAAS,EACT,aAAa,EACb,WAAW,EACX,aAAa,EACb,WAAW,GACZ,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AASnD,OAAO,EACL,WAAW,EACX,oBAAoB,EACpB,iBAAiB,EACjB,iBAAiB,GAClB,MAAM,aAAa,CAAC;AAErB,OAAO,EACL,YAAY,EACZ,aAAa,EACb,oBAAoB,GACrB,MAAM,YAAY,CAAC;AAOpB,OAAO,EACL,WAAW,EACX,WAAW,EACX,aAAa,EACb,gBAAgB,EAChB,SAAS,EACT,aAAa,EACb,WAAW,EACX,aAAa,EACb,WAAW,GACZ,MAAM,YAAY,CAAC;AAcpB,OAAO,EACL,gBAAgB,EAChB,SAAS,EACT,gBAAgB,EAChB,cAAc,EACd,kBAAkB,EAClB,OAAO,EACP,YAAY,EACZ,iBAAiB,EACjB,uBAAuB,EACvB,YAAY,EACZ,mBAAmB,EACnB,oBAAoB,EACpB,kBAAkB,EAClB,iBAAiB,GAClB,MAAM,aAAa,CAAC;AAUrB,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAOzD,OAAO,EACL,eAAe,EACf,OAAO,EACP,UAAU,EACV,gBAAgB,EAChB,WAAW,GACZ,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AAE5D,OAAO,EACL,aAAa,EACb,UAAU,EACV,YAAY,EACZ,aAAa,EACb,WAAW,EACX,gBAAgB,GACjB,MAAM,cAAc,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "workers-start",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.0",
|
|
4
4
|
"description": "The parts every TanStack Start app on Cloudflare Workers ends up writing: Markdown for agents on the same URL, a head helper that stops share cards leaking between pages, lazy Workers bindings, and a check that no local secret ships in the build.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Ryan Ghods",
|
|
@@ -21,7 +21,9 @@
|
|
|
21
21
|
"vite",
|
|
22
22
|
"seo",
|
|
23
23
|
"markdown",
|
|
24
|
-
"llms"
|
|
24
|
+
"llms",
|
|
25
|
+
"google-analytics",
|
|
26
|
+
"search-console"
|
|
25
27
|
],
|
|
26
28
|
"type": "module",
|
|
27
29
|
"sideEffects": false,
|
|
@@ -81,6 +83,11 @@
|
|
|
81
83
|
"import": "./dist/access-testing.js",
|
|
82
84
|
"default": "./dist/access-testing.js"
|
|
83
85
|
},
|
|
86
|
+
"./google": {
|
|
87
|
+
"types": "./dist/google.d.ts",
|
|
88
|
+
"import": "./dist/google.js",
|
|
89
|
+
"default": "./dist/google.js"
|
|
90
|
+
},
|
|
84
91
|
"./package.json": "./package.json"
|
|
85
92
|
},
|
|
86
93
|
"bin": {
|
package/src/google.ts
ADDED
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Google APIs as a service account, on WebCrypto and `fetch` only: the signed
|
|
3
|
+
* JWT exchanged for an access token (cached per account and scope), the GA4
|
|
4
|
+
* Data API's `runReport` and `batchRunReports`, and Search Console's
|
|
5
|
+
* `searchAnalytics.query`. Runs in workerd and Node.
|
|
6
|
+
*
|
|
7
|
+
* The API helpers take a token rather than an account, so a token from
|
|
8
|
+
* anywhere (gcloud impersonation in a script, say) works with them too.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
export const GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token";
|
|
12
|
+
export const GA4_SCOPE = "https://www.googleapis.com/auth/analytics.readonly";
|
|
13
|
+
export const SEARCH_CONSOLE_SCOPE =
|
|
14
|
+
"https://www.googleapis.com/auth/webmasters.readonly";
|
|
15
|
+
|
|
16
|
+
export interface ServiceAccount {
|
|
17
|
+
clientEmail: string;
|
|
18
|
+
/** The PKCS#8 PEM. Escaped `\n` sequences are fine. */
|
|
19
|
+
privateKey: string;
|
|
20
|
+
/** Sent as the JWT's `kid` when present. */
|
|
21
|
+
privateKeyId?: string | undefined;
|
|
22
|
+
/** Defaults to Google's token endpoint. */
|
|
23
|
+
tokenUri?: string | undefined;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** A Google API answered with an error status. */
|
|
27
|
+
export class GoogleApiError extends Error {
|
|
28
|
+
override readonly name = "GoogleApiError";
|
|
29
|
+
constructor(
|
|
30
|
+
message: string,
|
|
31
|
+
readonly status: number,
|
|
32
|
+
/** Google's error body, when it sent JSON. */
|
|
33
|
+
readonly body?: unknown,
|
|
34
|
+
) {
|
|
35
|
+
super(message);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The key file JSON (`client_email`, `private_key`, ...) as an account, or null when it is not one. */
|
|
40
|
+
export function parseServiceAccount(
|
|
41
|
+
raw: string | undefined | null,
|
|
42
|
+
): ServiceAccount | null {
|
|
43
|
+
if (!raw) return null;
|
|
44
|
+
try {
|
|
45
|
+
const v = JSON.parse(raw) as Record<string, unknown>;
|
|
46
|
+
if (typeof v.client_email !== "string" || typeof v.private_key !== "string")
|
|
47
|
+
return null;
|
|
48
|
+
return {
|
|
49
|
+
clientEmail: v.client_email,
|
|
50
|
+
privateKey: v.private_key,
|
|
51
|
+
privateKeyId:
|
|
52
|
+
typeof v.private_key_id === "string" ? v.private_key_id : undefined,
|
|
53
|
+
tokenUri: typeof v.token_uri === "string" ? v.token_uri : undefined,
|
|
54
|
+
};
|
|
55
|
+
} catch {
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const PKCS8_HEADER = "-----BEGIN PRIVATE KEY-----";
|
|
61
|
+
const PKCS8_FOOTER = "-----END PRIVATE KEY-----";
|
|
62
|
+
const RS256 = { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" } as const;
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Imports the account's private key for signing. Throws a clear error for a
|
|
66
|
+
* PKCS#1 key (`BEGIN RSA PRIVATE KEY`, which WebCrypto cannot import) or for
|
|
67
|
+
* a value that is not a PEM at all.
|
|
68
|
+
*/
|
|
69
|
+
export async function importServiceAccountKey(pem: string): Promise<CryptoKey> {
|
|
70
|
+
const text = pem.replace(/\\n/g, "\n").trim();
|
|
71
|
+
if (text.startsWith("-----BEGIN RSA PRIVATE KEY-----")) {
|
|
72
|
+
throw new Error(
|
|
73
|
+
"The private key is PKCS#1 (BEGIN RSA PRIVATE KEY). WebCrypto imports PKCS#8 only (BEGIN PRIVATE KEY), which is what a Google service account key file holds.",
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
const start = text.indexOf(PKCS8_HEADER);
|
|
77
|
+
const end = text.indexOf(PKCS8_FOOTER);
|
|
78
|
+
if (start === -1 || end === -1) {
|
|
79
|
+
throw new Error(
|
|
80
|
+
"The private key is not a PEM. Copy the private_key field from the service account JSON as it is.",
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
const body = text.slice(start + PKCS8_HEADER.length, end).replace(/\s+/g, "");
|
|
84
|
+
let der: Uint8Array<ArrayBuffer>;
|
|
85
|
+
try {
|
|
86
|
+
der = Uint8Array.from(atob(body), (ch) => ch.charCodeAt(0));
|
|
87
|
+
} catch {
|
|
88
|
+
throw new Error("The private key's body is not valid base64.");
|
|
89
|
+
}
|
|
90
|
+
return crypto.subtle.importKey("pkcs8", der, RS256, false, ["sign"]);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const encoder = new TextEncoder();
|
|
94
|
+
function b64url(data: string | Uint8Array): string {
|
|
95
|
+
const bytes = typeof data === "string" ? encoder.encode(data) : data;
|
|
96
|
+
let bin = "";
|
|
97
|
+
for (const b of bytes) bin += String.fromCharCode(b);
|
|
98
|
+
return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** The signed RS256 assertion Google exchanges for an access token. */
|
|
102
|
+
export async function serviceAccountJwt(
|
|
103
|
+
account: ServiceAccount,
|
|
104
|
+
scopes: string | readonly string[],
|
|
105
|
+
nowMs: number = Date.now(),
|
|
106
|
+
): Promise<string> {
|
|
107
|
+
const iat = Math.floor(nowMs / 1000);
|
|
108
|
+
const header: Record<string, string> = { alg: "RS256", typ: "JWT" };
|
|
109
|
+
if (account.privateKeyId) header.kid = account.privateKeyId;
|
|
110
|
+
const claims = {
|
|
111
|
+
iss: account.clientEmail,
|
|
112
|
+
scope: typeof scopes === "string" ? scopes : scopes.join(" "),
|
|
113
|
+
aud: account.tokenUri ?? GOOGLE_TOKEN_URL,
|
|
114
|
+
iat,
|
|
115
|
+
exp: iat + 3600,
|
|
116
|
+
};
|
|
117
|
+
const input = `${b64url(JSON.stringify(header))}.${b64url(JSON.stringify(claims))}`;
|
|
118
|
+
const key = await importServiceAccountKey(account.privateKey);
|
|
119
|
+
const sig = await crypto.subtle.sign(RS256, key, encoder.encode(input));
|
|
120
|
+
return `${input}.${b64url(new Uint8Array(sig))}`;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
type Fetch = (url: string, init?: RequestInit) => Promise<Response>;
|
|
124
|
+
|
|
125
|
+
export interface GoogleAuthOptions {
|
|
126
|
+
fetch?: Fetch;
|
|
127
|
+
/** Milliseconds since the epoch. */
|
|
128
|
+
now?: () => number;
|
|
129
|
+
/** Refresh this many seconds before the token expires. Default 300. */
|
|
130
|
+
marginSeconds?: number;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export type GoogleTokenSource = (
|
|
134
|
+
account: ServiceAccount,
|
|
135
|
+
scopes: string | readonly string[],
|
|
136
|
+
) => Promise<string>;
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* A token source with its own cache. Tokens are kept per account and scope
|
|
140
|
+
* until `marginSeconds` before they expire. Concurrent calls share one
|
|
141
|
+
* exchange, and a failed exchange is not cached.
|
|
142
|
+
*/
|
|
143
|
+
export function createGoogleAuth(
|
|
144
|
+
options: GoogleAuthOptions = {},
|
|
145
|
+
): GoogleTokenSource {
|
|
146
|
+
const {
|
|
147
|
+
fetch: fetcher = (url, init) => fetch(url, init),
|
|
148
|
+
now = Date.now,
|
|
149
|
+
marginSeconds = 300,
|
|
150
|
+
} = options;
|
|
151
|
+
const cache = new Map<
|
|
152
|
+
string,
|
|
153
|
+
{ token: Promise<string>; expiresAt: number }
|
|
154
|
+
>();
|
|
155
|
+
|
|
156
|
+
return (account, scopes) => {
|
|
157
|
+
const scope = typeof scopes === "string" ? scopes : scopes.join(" ");
|
|
158
|
+
const key = `${account.clientEmail}\n${scope}`;
|
|
159
|
+
const hit = cache.get(key);
|
|
160
|
+
if (hit && hit.expiresAt > now()) return hit.token;
|
|
161
|
+
const entry = { token: Promise.resolve(""), expiresAt: Infinity };
|
|
162
|
+
entry.token = (async () => {
|
|
163
|
+
const assertion = await serviceAccountJwt(account, scope, now());
|
|
164
|
+
const res = await fetcher(account.tokenUri ?? GOOGLE_TOKEN_URL, {
|
|
165
|
+
method: "POST",
|
|
166
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
167
|
+
body: new URLSearchParams({
|
|
168
|
+
grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
|
|
169
|
+
assertion,
|
|
170
|
+
}).toString(),
|
|
171
|
+
});
|
|
172
|
+
const body = (await res.json().catch(() => null)) as {
|
|
173
|
+
access_token?: string;
|
|
174
|
+
expires_in?: number;
|
|
175
|
+
error?: string;
|
|
176
|
+
error_description?: string;
|
|
177
|
+
} | null;
|
|
178
|
+
if (!res.ok || !body?.access_token) {
|
|
179
|
+
const why = body?.error_description ?? body?.error ?? "no access token";
|
|
180
|
+
throw new GoogleApiError(
|
|
181
|
+
`Google token exchange failed (${res.status}): ${why}`,
|
|
182
|
+
res.status,
|
|
183
|
+
body,
|
|
184
|
+
);
|
|
185
|
+
}
|
|
186
|
+
entry.expiresAt =
|
|
187
|
+
now() + ((body.expires_in ?? 3600) - marginSeconds) * 1000;
|
|
188
|
+
return body.access_token;
|
|
189
|
+
})();
|
|
190
|
+
entry.token.catch(() => {
|
|
191
|
+
if (cache.get(key) === entry) cache.delete(key);
|
|
192
|
+
});
|
|
193
|
+
cache.set(key, entry);
|
|
194
|
+
return entry.token;
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
let shared: GoogleTokenSource | undefined;
|
|
199
|
+
|
|
200
|
+
/** An access token from a token source shared by the whole isolate. */
|
|
201
|
+
export function googleAccessToken(
|
|
202
|
+
account: ServiceAccount,
|
|
203
|
+
scopes: string | readonly string[],
|
|
204
|
+
): Promise<string> {
|
|
205
|
+
shared ??= createGoogleAuth();
|
|
206
|
+
return shared(account, scopes);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
export interface GoogleCallOptions {
|
|
210
|
+
fetch?: Fetch;
|
|
211
|
+
/** Abort after this long. Default 10 seconds. */
|
|
212
|
+
timeoutMs?: number;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
async function googleJson<T>(
|
|
216
|
+
url: string,
|
|
217
|
+
token: string,
|
|
218
|
+
body: unknown,
|
|
219
|
+
{
|
|
220
|
+
fetch: fetcher = (u, i) => fetch(u, i),
|
|
221
|
+
timeoutMs = 10_000,
|
|
222
|
+
}: GoogleCallOptions,
|
|
223
|
+
what: string,
|
|
224
|
+
): Promise<T> {
|
|
225
|
+
const res = await fetcher(url, {
|
|
226
|
+
method: "POST",
|
|
227
|
+
headers: {
|
|
228
|
+
authorization: `Bearer ${token}`,
|
|
229
|
+
"content-type": "application/json",
|
|
230
|
+
},
|
|
231
|
+
body: JSON.stringify(body),
|
|
232
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
233
|
+
});
|
|
234
|
+
const json = (await res.json().catch(() => null)) as unknown;
|
|
235
|
+
if (!res.ok) {
|
|
236
|
+
const message =
|
|
237
|
+
(json as { error?: { message?: string } } | null)?.error?.message ??
|
|
238
|
+
res.statusText;
|
|
239
|
+
throw new GoogleApiError(
|
|
240
|
+
`${what} failed (${res.status}): ${message}`,
|
|
241
|
+
res.status,
|
|
242
|
+
json,
|
|
243
|
+
);
|
|
244
|
+
}
|
|
245
|
+
return json as T;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// GA4 Data API
|
|
249
|
+
|
|
250
|
+
export interface Ga4DateRange {
|
|
251
|
+
startDate: string;
|
|
252
|
+
endDate: string;
|
|
253
|
+
name?: string;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** A GA4 filter expression, passed through as Google defines it. */
|
|
257
|
+
export type Ga4FilterExpression = Record<string, unknown>;
|
|
258
|
+
|
|
259
|
+
export interface Ga4ReportRequest {
|
|
260
|
+
dimensions?: { name: string }[];
|
|
261
|
+
metrics: { name: string }[];
|
|
262
|
+
dateRanges: Ga4DateRange[];
|
|
263
|
+
dimensionFilter?: Ga4FilterExpression;
|
|
264
|
+
metricFilter?: Ga4FilterExpression;
|
|
265
|
+
orderBys?: Record<string, unknown>[];
|
|
266
|
+
limit?: number;
|
|
267
|
+
offset?: number;
|
|
268
|
+
metricAggregations?: ("TOTAL" | "MAXIMUM" | "MINIMUM" | "COUNT")[];
|
|
269
|
+
keepEmptyRows?: boolean;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
interface Ga4Row {
|
|
273
|
+
dimensionValues?: { value?: string }[];
|
|
274
|
+
metricValues?: { value?: string }[];
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
export interface Ga4Report {
|
|
278
|
+
dimensionHeaders?: { name: string }[];
|
|
279
|
+
metricHeaders?: { name: string; type?: string }[];
|
|
280
|
+
rows?: Ga4Row[];
|
|
281
|
+
totals?: Ga4Row[];
|
|
282
|
+
rowCount?: number;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
const ga4Url = (propertyId: string, method: string) =>
|
|
286
|
+
`https://analyticsdata.googleapis.com/v1beta/properties/${encodeURIComponent(propertyId.replace(/^properties\//, ""))}:${method}`;
|
|
287
|
+
|
|
288
|
+
/** One GA4 report. `propertyId` is the number, with or without `properties/`. */
|
|
289
|
+
export function ga4RunReport(
|
|
290
|
+
token: string,
|
|
291
|
+
propertyId: string,
|
|
292
|
+
request: Ga4ReportRequest,
|
|
293
|
+
options: GoogleCallOptions = {},
|
|
294
|
+
): Promise<Ga4Report> {
|
|
295
|
+
return googleJson(
|
|
296
|
+
ga4Url(propertyId, "runReport"),
|
|
297
|
+
token,
|
|
298
|
+
request,
|
|
299
|
+
options,
|
|
300
|
+
"GA4 runReport",
|
|
301
|
+
);
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** Up to five GA4 reports in one call, in order. */
|
|
305
|
+
export async function ga4BatchRunReports(
|
|
306
|
+
token: string,
|
|
307
|
+
propertyId: string,
|
|
308
|
+
requests: readonly Ga4ReportRequest[],
|
|
309
|
+
options: GoogleCallOptions = {},
|
|
310
|
+
): Promise<Ga4Report[]> {
|
|
311
|
+
if (requests.length > 5)
|
|
312
|
+
throw new Error("GA4 batchRunReports takes at most 5 reports.");
|
|
313
|
+
const res = await googleJson<{ reports?: Ga4Report[] }>(
|
|
314
|
+
ga4Url(propertyId, "batchRunReports"),
|
|
315
|
+
token,
|
|
316
|
+
{ requests },
|
|
317
|
+
options,
|
|
318
|
+
"GA4 batchRunReports",
|
|
319
|
+
);
|
|
320
|
+
return res.reports ?? [];
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
export type Ga4RowObject = Record<string, string | number>;
|
|
324
|
+
|
|
325
|
+
/**
|
|
326
|
+
* A report's rows as objects keyed by header name: dimensions as strings,
|
|
327
|
+
* metrics as numbers. `totals: true` reads the totals rows instead.
|
|
328
|
+
*/
|
|
329
|
+
export function ga4Rows(
|
|
330
|
+
report: Ga4Report,
|
|
331
|
+
{ totals = false }: { totals?: boolean } = {},
|
|
332
|
+
): Ga4RowObject[] {
|
|
333
|
+
const dims = report.dimensionHeaders?.map((h) => h.name) ?? [];
|
|
334
|
+
const mets = report.metricHeaders?.map((h) => h.name) ?? [];
|
|
335
|
+
return ((totals ? report.totals : report.rows) ?? []).map((row) => {
|
|
336
|
+
const out: Ga4RowObject = {};
|
|
337
|
+
dims.forEach((name, i) => {
|
|
338
|
+
out[name] = row.dimensionValues?.[i]?.value ?? "";
|
|
339
|
+
});
|
|
340
|
+
mets.forEach((name, i) => {
|
|
341
|
+
out[name] = Number(row.metricValues?.[i]?.value ?? 0);
|
|
342
|
+
});
|
|
343
|
+
return out;
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/** A filter matching a dimension against a list of values. */
|
|
348
|
+
export function inListFilter(
|
|
349
|
+
fieldName: string,
|
|
350
|
+
values: readonly string[],
|
|
351
|
+
): Ga4FilterExpression {
|
|
352
|
+
return { filter: { fieldName, inListFilter: { values: [...values] } } };
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
// Search Console
|
|
356
|
+
|
|
357
|
+
export interface SearchAnalyticsQuery {
|
|
358
|
+
startDate: string;
|
|
359
|
+
endDate: string;
|
|
360
|
+
dimensions?: (
|
|
361
|
+
| "query"
|
|
362
|
+
| "page"
|
|
363
|
+
| "country"
|
|
364
|
+
| "device"
|
|
365
|
+
| "date"
|
|
366
|
+
| "searchAppearance"
|
|
367
|
+
)[];
|
|
368
|
+
type?: "web" | "image" | "video" | "news" | "discover" | "googleNews";
|
|
369
|
+
dimensionFilterGroups?: Record<string, unknown>[];
|
|
370
|
+
aggregationType?: "auto" | "byPage" | "byProperty";
|
|
371
|
+
dataState?: "final" | "all";
|
|
372
|
+
rowLimit?: number;
|
|
373
|
+
startRow?: number;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
export interface SearchAnalyticsRow {
|
|
377
|
+
keys: string[];
|
|
378
|
+
clicks: number;
|
|
379
|
+
impressions: number;
|
|
380
|
+
ctr: number;
|
|
381
|
+
position: number;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/**
|
|
385
|
+
* Search Console rows for `siteUrl` (`sc-domain:example.com` or a URL
|
|
386
|
+
* prefix). With `all: true` it pages with `startRow` until Google returns a
|
|
387
|
+
* short page.
|
|
388
|
+
*/
|
|
389
|
+
export async function searchConsoleQuery(
|
|
390
|
+
token: string,
|
|
391
|
+
siteUrl: string,
|
|
392
|
+
query: SearchAnalyticsQuery,
|
|
393
|
+
options: GoogleCallOptions & { all?: boolean } = {},
|
|
394
|
+
): Promise<SearchAnalyticsRow[]> {
|
|
395
|
+
const url = `https://www.googleapis.com/webmasters/v3/sites/${encodeURIComponent(siteUrl)}/searchAnalytics/query`;
|
|
396
|
+
const pageSize = query.rowLimit ?? (options.all ? 25_000 : 1_000);
|
|
397
|
+
const rows: SearchAnalyticsRow[] = [];
|
|
398
|
+
let startRow = query.startRow ?? 0;
|
|
399
|
+
for (;;) {
|
|
400
|
+
const res = await googleJson<{ rows?: Partial<SearchAnalyticsRow>[] }>(
|
|
401
|
+
url,
|
|
402
|
+
token,
|
|
403
|
+
{ ...query, rowLimit: pageSize, startRow },
|
|
404
|
+
options,
|
|
405
|
+
"Search Console query",
|
|
406
|
+
);
|
|
407
|
+
const page = (res.rows ?? []).map((r) => ({
|
|
408
|
+
keys: r.keys ?? [],
|
|
409
|
+
clicks: r.clicks ?? 0,
|
|
410
|
+
impressions: r.impressions ?? 0,
|
|
411
|
+
ctr: r.ctr ?? 0,
|
|
412
|
+
position: r.position ?? 0,
|
|
413
|
+
}));
|
|
414
|
+
rows.push(...page);
|
|
415
|
+
if (!options.all || page.length < pageSize) return rows;
|
|
416
|
+
startRow += page.length;
|
|
417
|
+
}
|
|
418
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -37,6 +37,35 @@ export {
|
|
|
37
37
|
wantsMarkdown,
|
|
38
38
|
withHeaders,
|
|
39
39
|
} from "./entry.js";
|
|
40
|
+
export type {
|
|
41
|
+
Ga4DateRange,
|
|
42
|
+
Ga4FilterExpression,
|
|
43
|
+
Ga4Report,
|
|
44
|
+
Ga4ReportRequest,
|
|
45
|
+
Ga4RowObject,
|
|
46
|
+
GoogleAuthOptions,
|
|
47
|
+
GoogleCallOptions,
|
|
48
|
+
GoogleTokenSource,
|
|
49
|
+
SearchAnalyticsQuery,
|
|
50
|
+
SearchAnalyticsRow,
|
|
51
|
+
ServiceAccount,
|
|
52
|
+
} from "./google.js";
|
|
53
|
+
export {
|
|
54
|
+
createGoogleAuth,
|
|
55
|
+
GA4_SCOPE,
|
|
56
|
+
GOOGLE_TOKEN_URL,
|
|
57
|
+
GoogleApiError,
|
|
58
|
+
ga4BatchRunReports,
|
|
59
|
+
ga4Rows,
|
|
60
|
+
ga4RunReport,
|
|
61
|
+
googleAccessToken,
|
|
62
|
+
importServiceAccountKey,
|
|
63
|
+
inListFilter,
|
|
64
|
+
parseServiceAccount,
|
|
65
|
+
SEARCH_CONSOLE_SCOPE,
|
|
66
|
+
searchConsoleQuery,
|
|
67
|
+
serviceAccountJwt,
|
|
68
|
+
} from "./google.js";
|
|
40
69
|
export type {
|
|
41
70
|
HeadLink,
|
|
42
71
|
HeadScript,
|