@pagebridge/core 0.0.2 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,254 +0,0 @@
1
- import type { DrizzleClient } from "@pagebridge/db";
2
- import { searchAnalytics } from "@pagebridge/db";
3
- import { and, avg, gte, lte, sql, eq } from "drizzle-orm";
4
-
5
- export interface DecayRule {
6
- type: "position_decay" | "low_ctr" | "impressions_drop";
7
- threshold: number;
8
- minImpressions: number;
9
- comparisonWindowDays: number;
10
- sustainedDays: number;
11
- }
12
-
13
- export interface QuietPeriodConfig {
14
- enabled: boolean;
15
- days: number;
16
- }
17
-
18
- export interface DecaySignal {
19
- page: string;
20
- reason: "position_decay" | "low_ctr" | "impressions_drop";
21
- severity: "low" | "medium" | "high";
22
- metrics: {
23
- positionBefore: number;
24
- positionNow: number;
25
- positionDelta: number;
26
- ctrBefore: number;
27
- ctrNow: number;
28
- impressions: number;
29
- };
30
- }
31
-
32
- interface PageMetrics {
33
- page: string;
34
- position: number;
35
- ctr: number;
36
- impressions: number;
37
- }
38
-
39
- export const defaultRules: DecayRule[] = [
40
- {
41
- type: "position_decay",
42
- threshold: 3,
43
- minImpressions: 100,
44
- comparisonWindowDays: 28,
45
- sustainedDays: 14,
46
- },
47
- {
48
- type: "low_ctr",
49
- threshold: 0.01,
50
- minImpressions: 1000,
51
- comparisonWindowDays: 28,
52
- sustainedDays: 7,
53
- },
54
- {
55
- type: "impressions_drop",
56
- threshold: 0.5,
57
- minImpressions: 500,
58
- comparisonWindowDays: 28,
59
- sustainedDays: 14,
60
- },
61
- ];
62
-
63
- export class DecayDetector {
64
- constructor(
65
- private db: DrizzleClient,
66
- private rules: DecayRule[] = defaultRules,
67
- ) {}
68
-
69
- async detectDecay(
70
- siteId: string,
71
- publishedDates: Map<string, Date>,
72
- quietPeriod: QuietPeriodConfig = { enabled: true, days: 45 },
73
- ): Promise<DecaySignal[]> {
74
- const signals: DecaySignal[] = [];
75
- const now = new Date();
76
-
77
- for (const rule of this.rules) {
78
- const currentPeriodEnd = now;
79
- const currentPeriodStart = daysAgo(rule.sustainedDays);
80
- const previousPeriodEnd = daysAgo(rule.comparisonWindowDays);
81
- const previousPeriodStart = daysAgo(
82
- rule.comparisonWindowDays + rule.sustainedDays,
83
- );
84
-
85
- const [currentMetrics, previousMetrics] = await Promise.all([
86
- this.getAverageMetrics(siteId, currentPeriodStart, currentPeriodEnd),
87
- this.getAverageMetrics(siteId, previousPeriodStart, previousPeriodEnd),
88
- ]);
89
-
90
- for (const current of currentMetrics) {
91
- if (quietPeriod.enabled) {
92
- const publishDate = publishedDates.get(current.page);
93
- if (publishDate && daysSince(publishDate) < quietPeriod.days) {
94
- continue;
95
- }
96
- }
97
-
98
- if (current.impressions < rule.minImpressions) continue;
99
-
100
- const previous = previousMetrics.find((p) => p.page === current.page);
101
- if (!previous) continue;
102
-
103
- const signal = this.evaluateRule(rule, current, previous);
104
- if (signal) signals.push(signal);
105
- }
106
- }
107
-
108
- return this.deduplicateSignals(signals);
109
- }
110
-
111
- private async getAverageMetrics(
112
- siteId: string,
113
- startDate: Date,
114
- endDate: Date,
115
- ): Promise<PageMetrics[]> {
116
- const results = await this.db
117
- .select({
118
- page: searchAnalytics.page,
119
- avgPosition: avg(searchAnalytics.position),
120
- avgCtr: avg(searchAnalytics.ctr),
121
- totalImpressions: sql<number>`sum(${searchAnalytics.impressions})`,
122
- })
123
- .from(searchAnalytics)
124
- .where(
125
- and(
126
- eq(searchAnalytics.siteId, siteId),
127
- gte(searchAnalytics.date, formatDate(startDate)),
128
- lte(searchAnalytics.date, formatDate(endDate)),
129
- ),
130
- )
131
- .groupBy(searchAnalytics.page);
132
-
133
- return results.map((r) => ({
134
- page: r.page,
135
- position: Number(r.avgPosition) || 0,
136
- ctr: Number(r.avgCtr) || 0,
137
- impressions: Number(r.totalImpressions) || 0,
138
- }));
139
- }
140
-
141
- private evaluateRule(
142
- rule: DecayRule,
143
- current: PageMetrics,
144
- previous: PageMetrics,
145
- ): DecaySignal | undefined {
146
- switch (rule.type) {
147
- case "position_decay": {
148
- const delta = current.position - previous.position;
149
- if (delta >= rule.threshold) {
150
- return {
151
- page: current.page,
152
- reason: "position_decay",
153
- severity: this.calculateSeverity(delta, [3, 5, 8]),
154
- metrics: {
155
- positionBefore: previous.position,
156
- positionNow: current.position,
157
- positionDelta: delta,
158
- ctrBefore: previous.ctr,
159
- ctrNow: current.ctr,
160
- impressions: current.impressions,
161
- },
162
- };
163
- }
164
- break;
165
- }
166
-
167
- case "low_ctr": {
168
- if (current.ctr < rule.threshold && current.position <= 10) {
169
- return {
170
- page: current.page,
171
- reason: "low_ctr",
172
- severity: this.calculateSeverity(
173
- rule.threshold - current.ctr,
174
- [0.005, 0.01, 0.02],
175
- ),
176
- metrics: {
177
- positionBefore: previous.position,
178
- positionNow: current.position,
179
- positionDelta: current.position - previous.position,
180
- ctrBefore: previous.ctr,
181
- ctrNow: current.ctr,
182
- impressions: current.impressions,
183
- },
184
- };
185
- }
186
- break;
187
- }
188
-
189
- case "impressions_drop": {
190
- const dropRatio = 1 - current.impressions / previous.impressions;
191
- if (dropRatio >= rule.threshold) {
192
- return {
193
- page: current.page,
194
- reason: "impressions_drop",
195
- severity: this.calculateSeverity(dropRatio, [0.3, 0.5, 0.7]),
196
- metrics: {
197
- positionBefore: previous.position,
198
- positionNow: current.position,
199
- positionDelta: current.position - previous.position,
200
- ctrBefore: previous.ctr,
201
- ctrNow: current.ctr,
202
- impressions: current.impressions,
203
- },
204
- };
205
- }
206
- break;
207
- }
208
- }
209
-
210
- return undefined;
211
- }
212
-
213
- private calculateSeverity(
214
- value: number,
215
- thresholds: [number, number, number],
216
- ): "low" | "medium" | "high" {
217
- if (value >= thresholds[2]) return "high";
218
- if (value >= thresholds[1]) return "medium";
219
- return "low";
220
- }
221
-
222
- private deduplicateSignals(signals: DecaySignal[]): DecaySignal[] {
223
- const byPage = new Map<string, DecaySignal>();
224
- const severityOrder = { high: 3, medium: 2, low: 1 };
225
-
226
- for (const signal of signals) {
227
- const existing = byPage.get(signal.page);
228
- if (
229
- !existing ||
230
- severityOrder[signal.severity] > severityOrder[existing.severity]
231
- ) {
232
- byPage.set(signal.page, signal);
233
- }
234
- }
235
-
236
- return Array.from(byPage.values());
237
- }
238
- }
239
-
240
- function daysAgo(days: number): Date {
241
- const date = new Date();
242
- date.setDate(date.getDate() - days);
243
- return date;
244
- }
245
-
246
- function daysSince(date: Date): number {
247
- const now = new Date();
248
- const diff = now.getTime() - date.getTime();
249
- return Math.floor(diff / (1000 * 60 * 60 * 24));
250
- }
251
-
252
- function formatDate(date: Date): string {
253
- return date.toISOString().split("T")[0]!;
254
- }
package/src/gsc-client.ts DELETED
@@ -1,126 +0,0 @@
1
- import { google, type searchconsole_v1 } from "googleapis";
2
- import type { JWT } from "google-auth-library";
3
-
4
- export interface GSCClientOptions {
5
- credentials: {
6
- client_email: string;
7
- private_key: string;
8
- };
9
- }
10
-
11
- export interface SearchAnalyticsRow {
12
- page: string;
13
- query?: string;
14
- date?: string;
15
- clicks: number;
16
- impressions: number;
17
- ctr: number;
18
- position: number;
19
- }
20
-
21
- export interface FetchOptions {
22
- siteUrl: string;
23
- startDate: Date;
24
- endDate: Date;
25
- dimensions?: ("page" | "query" | "date")[];
26
- rowLimit?: number;
27
- }
28
-
29
- export type IndexVerdict = "PASS" | "FAIL" | "NEUTRAL" | "VERDICT_UNSPECIFIED";
30
-
31
- export interface IndexStatusResult {
32
- verdict: IndexVerdict;
33
- coverageState: string | null;
34
- indexingState: string | null;
35
- pageFetchState: string | null;
36
- lastCrawlTime: Date | null;
37
- robotsTxtState: string | null;
38
- }
39
-
40
- export class GSCClient {
41
- private auth: JWT;
42
- private searchConsole: searchconsole_v1.Searchconsole;
43
-
44
- constructor(options: GSCClientOptions) {
45
- this.auth = new google.auth.JWT({
46
- email: options.credentials.client_email,
47
- key: options.credentials.private_key,
48
- scopes: ["https://www.googleapis.com/auth/webmasters.readonly"],
49
- });
50
-
51
- this.searchConsole = google.searchconsole({
52
- version: "v1",
53
- auth: this.auth,
54
- });
55
- }
56
-
57
- async fetchSearchAnalytics(options: FetchOptions): Promise<SearchAnalyticsRow[]> {
58
- const { siteUrl, startDate, endDate, dimensions = ["page", "date"], rowLimit = 25000 } = options;
59
-
60
- const rows: SearchAnalyticsRow[] = [];
61
- let startRow = 0;
62
-
63
- while (true) {
64
- const response = await this.searchConsole.searchanalytics.query({
65
- siteUrl,
66
- requestBody: {
67
- startDate: formatDate(startDate),
68
- endDate: formatDate(endDate),
69
- dimensions,
70
- rowLimit,
71
- startRow,
72
- },
73
- });
74
-
75
- const responseRows = response.data.rows ?? [];
76
- if (responseRows.length === 0) break;
77
-
78
- for (const row of responseRows) {
79
- const keys = row.keys ?? [];
80
- rows.push({
81
- page: dimensions.includes("page") ? keys[dimensions.indexOf("page")]! : "",
82
- query: dimensions.includes("query") ? keys[dimensions.indexOf("query")] : undefined,
83
- date: dimensions.includes("date") ? keys[dimensions.indexOf("date")] : undefined,
84
- clicks: row.clicks ?? 0,
85
- impressions: row.impressions ?? 0,
86
- ctr: row.ctr ?? 0,
87
- position: row.position ?? 0,
88
- });
89
- }
90
-
91
- if (responseRows.length < rowLimit) break;
92
- startRow += rowLimit;
93
- }
94
-
95
- return rows;
96
- }
97
-
98
- async listSites(): Promise<string[]> {
99
- const response = await this.searchConsole.sites.list();
100
- return (response.data.siteEntry ?? []).map((site) => site.siteUrl!).filter(Boolean);
101
- }
102
-
103
- async inspectUrl(siteUrl: string, inspectionUrl: string): Promise<IndexStatusResult> {
104
- const response = await this.searchConsole.urlInspection.index.inspect({
105
- requestBody: {
106
- inspectionUrl,
107
- siteUrl,
108
- },
109
- });
110
-
111
- const result = response.data.inspectionResult?.indexStatusResult;
112
-
113
- return {
114
- verdict: (result?.verdict as IndexVerdict) ?? "VERDICT_UNSPECIFIED",
115
- coverageState: result?.coverageState ?? null,
116
- indexingState: result?.indexingState ?? null,
117
- pageFetchState: result?.pageFetchState ?? null,
118
- lastCrawlTime: result?.lastCrawlTime ? new Date(result.lastCrawlTime) : null,
119
- robotsTxtState: result?.robotsTxtState ?? null,
120
- };
121
- }
122
- }
123
-
124
- function formatDate(date: Date): string {
125
- return date.toISOString().split("T")[0]!;
126
- }
package/src/index.ts DELETED
@@ -1,31 +0,0 @@
1
- export {
2
- GSCClient,
3
- type GSCClientOptions,
4
- type IndexStatusResult,
5
- type IndexVerdict,
6
- } from "./gsc-client.js";
7
- export {
8
- SyncEngine,
9
- type SyncOptions,
10
- type SyncResult,
11
- type IndexStatusSyncResult,
12
- } from "./sync-engine.js";
13
- export {
14
- DecayDetector,
15
- defaultRules,
16
- type DecayRule,
17
- type DecaySignal,
18
- type QuietPeriodConfig,
19
- } from "./decay-detector.js";
20
- export {
21
- URLMatcher,
22
- type MatchResult,
23
- type URLMatcherConfig,
24
- type UnmatchReason,
25
- type MatchDiagnostics,
26
- } from "./url-matcher.js";
27
- export {
28
- TaskGenerator,
29
- type TaskGeneratorOptions,
30
- type QueryContext,
31
- } from "./task-generator.js";