@nitpicker/report-google-sheets 0.7.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/README.md +47 -1
- package/lib/data/create-page-list.d.ts +21 -0
- package/lib/data/create-page-list.js +21 -0
- package/lib/data/create-resources.d.ts +152 -8
- package/lib/data/create-resources.js +321 -40
- package/lib/report.d.ts +10 -0
- package/lib/report.js +2 -2
- package/lib/sheets/create-sheets.d.ts +15 -20
- package/lib/sheets/create-sheets.js +62 -83
- package/lib/sheets/run-finalize-resources.d.ts +31 -0
- package/lib/sheets/run-finalize-resources.js +35 -0
- package/lib/sheets/types.d.ts +29 -0
- package/lib/utils/canonicalize-url.d.ts +53 -0
- package/lib/utils/canonicalize-url.js +105 -0
- package/lib/utils/sort-resources-by-url.d.ts +66 -0
- package/lib/utils/sort-resources-by-url.js +220 -0
- package/package.json +5 -5
package/README.md
CHANGED
|
@@ -6,7 +6,53 @@
|
|
|
6
6
|
|
|
7
7
|
`.nitpicker` アーカイブ内のクロールデータと分析結果を Google Sheets に出力します。ページ一覧・リンク・リソース・画像・違反レポートなど、複数のシートを自動生成します。
|
|
8
8
|
|
|
9
|
-
このパッケージは [Nitpicker](
|
|
9
|
+
このパッケージは [Nitpicker](../../../README.md) モノレポの内部パッケージです。単体での利用は想定していません。
|
|
10
|
+
|
|
11
|
+
## 設計のポイント
|
|
12
|
+
|
|
13
|
+
- **5 フェーズ構成**: `Phase 1 (シート作成)` → `Phase 2 (ページ反復) / Phase 3 (リソース反復) / Phase 4 (プラグインデータ)` 並列 → `Phase 5 (フォーマット)`。詳細は [ARCHITECTURE.md §8](../../../ARCHITECTURE.md#8-report-の詳細)。
|
|
14
|
+
- **ストリーミング送信**: 各シートの行生成は `sheet.appendRow(...rows)` でストリーミング送信。`@d-zero/google-sheets` が内部で 2500 行ごとに自動 flush するため、呼び出し元のメモリ滞留はチャンクサイズ分に抑えられる。
|
|
15
|
+
- **Resources シートの dedupe モード**: `--dedupe-resources` で canonical URL ごとに集約。広告・解析タグで per-request unique なクエリが爆発するサイトで、Google Sheets の **1 ドキュメント 10,000,000 セル上限** を回避するための機能(実例: 1.6M raw → 63K rows、96% 削減)。
|
|
16
|
+
- **Phase 3 finalize での進捗表示**: 集約後の大量行を `appendRow(...finalRows)` で一括送信する間も、`Sheet.onProgress` を購読して chunk flush ごとに Lanes に `Sending N/total` を反映する。実装は [`src/sheets/run-finalize-resources.ts`](./src/sheets/run-finalize-resources.ts)。
|
|
17
|
+
|
|
18
|
+
## 拡張ポイント(新規シート追加時)
|
|
19
|
+
|
|
20
|
+
新しいシートを追加するときの典型パターン:
|
|
21
|
+
|
|
22
|
+
| やりたいこと | 使う hook |
|
|
23
|
+
| ---------------------------------------------- | ----------------------------------------------------------- |
|
|
24
|
+
| ページごとに行を生成 | `eachPage` |
|
|
25
|
+
| ページ反復前に状態を蓄積(例: 親子関係マップ) | `preEachPage` |
|
|
26
|
+
| リソースごとに行を生成 | `eachResource` |
|
|
27
|
+
| リソース反復の終端で集約結果を 1 回だけ送信 | `eachResource` で Map に蓄積 → `finalizeResources` で flush |
|
|
28
|
+
| プラグインデータ等、反復不要で一括送信 | `addRows`(Phase 2/3 と並列実行) |
|
|
29
|
+
| データ送信後にフォーマット適用 | `updateSheet` |
|
|
30
|
+
|
|
31
|
+
> **集約系シートで `eachResource` 内の `num`/`total` を見て最後だけ emit する設計は禁止**。Phase 3 が将来並列化されると壊れる。必ず `finalizeResources` hook を使うこと([ARCHITECTURE.md の説明](../../../ARCHITECTURE.md#行送信戦略))。
|
|
32
|
+
|
|
33
|
+
## トラブルシューティング
|
|
34
|
+
|
|
35
|
+
| 症状 | 原因と対処 |
|
|
36
|
+
| ----------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
37
|
+
| `Error: This document is too large to continue editing.` | Google Sheets の 10M セル上限到達。`--dedupe-resources` を有効にして Resources を集約する。 |
|
|
38
|
+
| Phase 3 で「Sending N/total」の N が止まったまま | 進捗表示は `Sheet.onProgress` 駆動。`@d-zero/google-sheets` を 0.9.0 以上に保つ必要がある。 |
|
|
39
|
+
| `RangeError: Maximum call stack size exceeded` (Phase 3 finalize) | `appendRow(...finalRows)` のスプレッドが V8 引数上限(実用上 6.5 万件付近)を超えた。`finalizeResources` の戻り値件数が更に増えた場合は chunk 単位で複数回 `appendRow` を呼ぶよう書き換える。[ARCHITECTURE.md の既知の制約セクション](../../../ARCHITECTURE.md#行送信戦略)を参照。 |
|
|
40
|
+
| sort に長時間ブロックされて HTTPS が EPIPE で落ちる | `sortResourcesByUrl` は Pool `strnatcmp` の派生文字列ゼロ実装。`Intl.Collator.compare` や Schwartzian transform への書き換えは禁止(過去にやって両方とも本番障害を起こした)。詳細は [ARCHITECTURE.md](../../../ARCHITECTURE.md#行送信戦略)。 |
|
|
41
|
+
|
|
42
|
+
## テスト
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
yarn vitest run packages/@nitpicker/report-google-sheets
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
E2E は `yarn vitest run --config vitest.e2e.config.ts` でリポジトリ全体一括(Google Sheets API モックは未整備のため、本番送信パスは手動検証)。
|
|
49
|
+
|
|
50
|
+
## 参照
|
|
51
|
+
|
|
52
|
+
- [ARCHITECTURE.md §8 Report の詳細](../../../ARCHITECTURE.md#8-report-の詳細) — フェーズ詳細、行送信戦略、sort 実装の根拠
|
|
53
|
+
- [`@d-zero/google-sheets`](https://www.npmjs.com/package/@d-zero/google-sheets) — Sheet ストリーミング送信 API
|
|
54
|
+
- [Google Sheets API 制限](https://developers.google.com/sheets/api/limits) — 10M セル上限、batchUpdate サイズ
|
|
55
|
+
- [Martin Pool, "Natural Order String Comparison"](https://sourcefrog.net/projects/natsort/) — sort 実装の出典
|
|
10
56
|
|
|
11
57
|
## ライセンス
|
|
12
58
|
|
|
@@ -24,6 +24,27 @@ import type { CreateSheet } from '../sheets/types.js';
|
|
|
24
24
|
* - Error-like titles and non-success status codes
|
|
25
25
|
*
|
|
26
26
|
* Unused path columns (beyond the deepest URL) are hidden automatically.
|
|
27
|
+
*
|
|
28
|
+
* ## Lazy thunk in "Internal Referrers"
|
|
29
|
+
*
|
|
30
|
+
* The "Internal Referrers" column is emitted via `createCellData(() => ...)`
|
|
31
|
+
* — a thunk that reads `parentRefs` / `indexRefs` at `provide()` time. The
|
|
32
|
+
* thunk is deliberately deferred because sibling index pages mutate the
|
|
33
|
+
* shared maps as the batch iterates, so the final referrer count is only
|
|
34
|
+
* accurate after every page has been processed.
|
|
35
|
+
*
|
|
36
|
+
* `@d-zero/google-sheets` detects this lazy cell (via the
|
|
37
|
+
* `Cell.prototype.provide` identity check) and switches the sheet's
|
|
38
|
+
* `appendRow()` into buffered mode automatically. The buffered rows are
|
|
39
|
+
* sent on the explicit `sheet.flush()` call at batch end, by which time
|
|
40
|
+
* the maps are fully populated.
|
|
41
|
+
*
|
|
42
|
+
* If a future refactor removes the thunk pattern from this column, the
|
|
43
|
+
* sheet can be sent as a pure stream — no per-sheet configuration change
|
|
44
|
+
* is needed since the library auto-detects. The corresponding spec
|
|
45
|
+
* (`create-page-list.spec.ts`) asserts the presence of at least one lazy
|
|
46
|
+
* cell so the maintainer who removes the thunk will see the test fail and
|
|
47
|
+
* be prompted to reconsider whether the change is intentional.
|
|
27
48
|
* @param reports - Analyze plugin reports to extract per-page data columns from
|
|
28
49
|
*/
|
|
29
50
|
export declare const createPageList: CreateSheet;
|
|
@@ -30,6 +30,27 @@ const log = pLog.extend('PageList');
|
|
|
30
30
|
* - Error-like titles and non-success status codes
|
|
31
31
|
*
|
|
32
32
|
* Unused path columns (beyond the deepest URL) are hidden automatically.
|
|
33
|
+
*
|
|
34
|
+
* ## Lazy thunk in "Internal Referrers"
|
|
35
|
+
*
|
|
36
|
+
* The "Internal Referrers" column is emitted via `createCellData(() => ...)`
|
|
37
|
+
* — a thunk that reads `parentRefs` / `indexRefs` at `provide()` time. The
|
|
38
|
+
* thunk is deliberately deferred because sibling index pages mutate the
|
|
39
|
+
* shared maps as the batch iterates, so the final referrer count is only
|
|
40
|
+
* accurate after every page has been processed.
|
|
41
|
+
*
|
|
42
|
+
* `@d-zero/google-sheets` detects this lazy cell (via the
|
|
43
|
+
* `Cell.prototype.provide` identity check) and switches the sheet's
|
|
44
|
+
* `appendRow()` into buffered mode automatically. The buffered rows are
|
|
45
|
+
* sent on the explicit `sheet.flush()` call at batch end, by which time
|
|
46
|
+
* the maps are fully populated.
|
|
47
|
+
*
|
|
48
|
+
* If a future refactor removes the thunk pattern from this column, the
|
|
49
|
+
* sheet can be sent as a pure stream — no per-sheet configuration change
|
|
50
|
+
* is needed since the library auto-detects. The corresponding spec
|
|
51
|
+
* (`create-page-list.spec.ts`) asserts the presence of at least one lazy
|
|
52
|
+
* cell so the maintainer who removes the thunk will see the test fail and
|
|
53
|
+
* be prompted to reconsider whether the change is intentional.
|
|
33
54
|
* @param reports - Analyze plugin reports to extract per-page data columns from
|
|
34
55
|
*/
|
|
35
56
|
export const createPageList = (reports) => {
|
|
@@ -1,13 +1,157 @@
|
|
|
1
1
|
import type { CreateSheet } from '../sheets/types.js';
|
|
2
2
|
/**
|
|
3
|
-
*
|
|
3
|
+
* Options for the {@link createResources} factory.
|
|
4
|
+
*/
|
|
5
|
+
export interface CreateResourcesOptions {
|
|
6
|
+
/**
|
|
7
|
+
* Collapse raw resource rows that share the same canonical URL
|
|
8
|
+
* (query *values* stripped, query *keys* sorted) into one row per
|
|
9
|
+
* `(canonical URL, status, contentType)` combination. Adds a `Count`
|
|
10
|
+
* column showing how many raw resources each row collapses.
|
|
11
|
+
*
|
|
12
|
+
* Path-embedded identifiers (e.g. tracking IDs in
|
|
13
|
+
* `/pagead/viewthroughconversion/<id>/`) are preserved, so the
|
|
14
|
+
* aggregated rows still expose every tracker present in the archive.
|
|
15
|
+
*
|
|
16
|
+
* Defaults to `false` (raw mode — one row per raw resource URL).
|
|
17
|
+
*/
|
|
18
|
+
readonly dedupe?: boolean;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Safety cap for the joined referrer URL list inserted into a cell note.
|
|
22
|
+
* Google Sheets caps cell content / notes around 50,000 characters; we
|
|
23
|
+
* truncate well below that to leave room for the "and N more" suffix.
|
|
24
|
+
*/
|
|
25
|
+
export declare const NOTE_MAX_LENGTH = 49000;
|
|
26
|
+
/**
|
|
27
|
+
* Maximum number of unique values to keep per query parameter key in
|
|
28
|
+
* dedupe mode. The Query Pattern cell only shows unique counts, but
|
|
29
|
+
* we keep a small sample for cell notes and to avoid unbounded memory
|
|
30
|
+
* growth on trackers that send a unique-per-request value
|
|
31
|
+
* (e.g. session IDs).
|
|
32
|
+
*/
|
|
33
|
+
export declare const MAX_PARAM_VALUE_SAMPLES = 100;
|
|
34
|
+
/**
|
|
35
|
+
* Per-key tracker for query parameter values inside a dedupe entry.
|
|
36
|
+
* `values` is capped at {@link MAX_PARAM_VALUE_SAMPLES}; once the cap
|
|
37
|
+
* is reached, further observations increment `overflowedCount`
|
|
38
|
+
* instead of growing the set. {@link formatQueryPattern} uses
|
|
39
|
+
* `overflowedCount > 0` as the precise condition for appending `+`
|
|
40
|
+
* to the cell — so `key=100` means "exactly 100 sampled, no
|
|
41
|
+
* observation was lost", and `key=100+` means "the sample set lost
|
|
42
|
+
* at least one observation after the cap".
|
|
43
|
+
*/
|
|
44
|
+
export interface ParamValueTracker {
|
|
45
|
+
/** Sampled unique values (bounded by {@link MAX_PARAM_VALUE_SAMPLES}). */
|
|
46
|
+
readonly values: Set<string>;
|
|
47
|
+
/** Observations that arrived after the sample set was full and therefore could not enter the set. */
|
|
48
|
+
overflowedCount: number;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* In-memory aggregation entry for dedupe mode. One per
|
|
52
|
+
* `(canonical, status, contentType)` combination.
|
|
53
|
+
*/
|
|
54
|
+
export interface DedupeEntry {
|
|
55
|
+
/** Canonical URL representing this entry. */
|
|
56
|
+
readonly canonical: string;
|
|
57
|
+
/** HTTP status code shared by all raw resources in this entry. */
|
|
58
|
+
readonly status: number | null;
|
|
59
|
+
/** HTTP status text — first non-null value observed. */
|
|
60
|
+
statusText: string | null;
|
|
61
|
+
/** Content type shared by all raw resources in this entry. */
|
|
62
|
+
readonly contentType: string | null;
|
|
63
|
+
/** Smallest non-null content length observed. */
|
|
64
|
+
contentLengthMin: number | null;
|
|
65
|
+
/** Largest non-null content length observed. */
|
|
66
|
+
contentLengthMax: number | null;
|
|
67
|
+
/** Number of raw resources collapsed into this entry. */
|
|
68
|
+
count: number;
|
|
69
|
+
/** Union of referrer page URLs across all raw resources in this entry. */
|
|
70
|
+
readonly referrers: Set<string>;
|
|
71
|
+
/** Per-query-key value trackers; absent for resources without a query string. */
|
|
72
|
+
readonly paramValues: Map<string, ParamValueTracker>;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Builds the Map key for a dedupe entry.
|
|
76
|
+
*
|
|
77
|
+
* Concatenates `status`, `contentType`, and `canonical` with a
|
|
78
|
+
* non-printable separator. A dedicated `null` marker keeps `null`
|
|
79
|
+
* distinct from `''` for `contentType`, and from `0` for `status`,
|
|
80
|
+
* so e.g. `(canonical, 200, null)` and `(canonical, 200, '')` land
|
|
81
|
+
* in different aggregation buckets.
|
|
82
|
+
*
|
|
83
|
+
* String concatenation is used instead of {@link JSON.stringify}
|
|
84
|
+
* because this function is called once per raw resource — on a
|
|
85
|
+
* million-resource archive `JSON.stringify` allocated roughly a
|
|
86
|
+
* million transient `SeqString`s, dominating Phase 3 wall-clock
|
|
87
|
+
* time. Plain concatenation is several times faster and produces
|
|
88
|
+
* the same collision-free key.
|
|
89
|
+
* @param canonical - The canonicalized URL.
|
|
90
|
+
* @param status - HTTP status code (nullable).
|
|
91
|
+
* @param contentType - HTTP content type (nullable).
|
|
92
|
+
*/
|
|
93
|
+
export declare function dedupeKey(canonical: string, status: number | null, contentType: string | null): string;
|
|
94
|
+
/**
|
|
95
|
+
* Joins referrer URLs into a single newline-separated string, truncating
|
|
96
|
+
* at `maxLength` to stay within Google Sheets' note size cap. When
|
|
97
|
+
* truncated, appends a `... and N more` line where `N` counts every URL
|
|
98
|
+
* that did not fit, including the one whose insertion would have
|
|
99
|
+
* crossed the limit.
|
|
100
|
+
* @param referrers - The set of unique referrer page URLs.
|
|
101
|
+
* @param maxLength - Optional override for the character cap (defaults to {@link NOTE_MAX_LENGTH}).
|
|
102
|
+
*/
|
|
103
|
+
export declare function joinReferrersForNote(referrers: ReadonlySet<string>, maxLength?: number): string;
|
|
104
|
+
/**
|
|
105
|
+
* Formats the Query Pattern cell for a dedupe entry. Each tracked key
|
|
106
|
+
* gets a `key=N` token where `N` is the number of distinct values
|
|
107
|
+
* sampled. `+` is appended only when {@link ParamValueTracker.overflowedCount}
|
|
108
|
+
* is non-zero — i.e. when at least one observation arrived after the
|
|
109
|
+
* sample set was already full. Duplicate observations that arrive
|
|
110
|
+
* while the sample set still has capacity do NOT trigger `+`.
|
|
111
|
+
*
|
|
112
|
+
* This gives precise semantics:
|
|
113
|
+
*
|
|
114
|
+
* - `key=1` — exactly one distinct value, seen any number of times
|
|
115
|
+
* - `key=99` — 99 distinct values, sample set still had room
|
|
116
|
+
* - `key=100` — exactly 100 distinct values, no observation lost
|
|
117
|
+
* - `key=100+` — sample set was capped and at least one further
|
|
118
|
+
* observation could not be recorded (real cardinality unknown but
|
|
119
|
+
* at least 100)
|
|
120
|
+
*
|
|
121
|
+
* Keys are sorted alphabetically to match the canonical URL.
|
|
122
|
+
*
|
|
123
|
+
* Returns `null` for entries without any query parameters so the cell
|
|
124
|
+
* appears empty in Google Sheets.
|
|
125
|
+
* @param entry - The dedupe entry to format.
|
|
126
|
+
*/
|
|
127
|
+
export declare function formatQueryPattern(entry: DedupeEntry): string | null;
|
|
128
|
+
/**
|
|
129
|
+
* Formats the Content Length cell value. Returns a single number when
|
|
130
|
+
* every raw resource in the group reported the same size, a `min-max`
|
|
131
|
+
* string when the size varies, or `null` when nothing was recorded.
|
|
132
|
+
* @param entry - The dedupe entry to format.
|
|
133
|
+
*/
|
|
134
|
+
export declare function formatContentLength(entry: DedupeEntry): number | string | null;
|
|
135
|
+
/**
|
|
136
|
+
* Creates the "Resources" sheet configuration factory.
|
|
137
|
+
*
|
|
138
|
+
* Lists all network resources (CSS, JS, images, fonts, tracking pixels,
|
|
139
|
+
* etc.) discovered during crawling. Two modes are supported:
|
|
4
140
|
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
141
|
+
* - **Raw mode** (default): one row per raw resource URL. Six columns:
|
|
142
|
+
* URL, Status Code, Status Text, Content Type, Content Length,
|
|
143
|
+
* Referrers. Matches historical behavior.
|
|
144
|
+
* - **Dedupe mode** (`{ dedupe: true }`): collapses rows that share the
|
|
145
|
+
* same canonical URL (query values stripped, keys sorted) into one
|
|
146
|
+
* row per `(canonical URL, status, contentType)`. Adds a trailing
|
|
147
|
+
* `Count` column showing how many raw resources each row collapses.
|
|
148
|
+
* Useful when third-party tracking pixels generate millions of
|
|
149
|
+
* per-request unique URLs that would otherwise exceed the Google
|
|
150
|
+
* Sheets 10M-cell document limit.
|
|
9
151
|
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
152
|
+
* In dedupe mode the factory accumulates state inside `eachResource`
|
|
153
|
+
* and emits the aggregated rows once via the `finalizeResources` hook,
|
|
154
|
+
* which Phase 3 calls exactly once after the per-resource loop completes.
|
|
155
|
+
* @param options - Optional configuration. See {@link CreateResourcesOptions}.
|
|
12
156
|
*/
|
|
13
|
-
export declare
|
|
157
|
+
export declare function createResources(options?: CreateResourcesOptions): CreateSheet;
|
|
@@ -1,45 +1,326 @@
|
|
|
1
1
|
import { reportLog } from '../debug.js';
|
|
2
2
|
import { createCellData } from '../sheets/create-cell-data.js';
|
|
3
3
|
import { defaultCellFormat } from '../sheets/default-cell-format.js';
|
|
4
|
+
import { canonicalizeUrl, extractQueryPairs } from '../utils/canonicalize-url.js';
|
|
5
|
+
import { naturalCompare } from '../utils/sort-resources-by-url.js';
|
|
6
|
+
const RAW_HEADERS = [
|
|
7
|
+
'URL',
|
|
8
|
+
'Status Code',
|
|
9
|
+
'Status Text',
|
|
10
|
+
'Content Type',
|
|
11
|
+
'Content Length',
|
|
12
|
+
'Referrers',
|
|
13
|
+
];
|
|
14
|
+
const DEDUPE_HEADERS = [
|
|
15
|
+
'URL',
|
|
16
|
+
'Status Code',
|
|
17
|
+
'Status Text',
|
|
18
|
+
'Content Type',
|
|
19
|
+
'Content Length',
|
|
20
|
+
'Referrers',
|
|
21
|
+
'Count',
|
|
22
|
+
'Query Pattern',
|
|
23
|
+
];
|
|
4
24
|
/**
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
25
|
+
* Safety cap for the joined referrer URL list inserted into a cell note.
|
|
26
|
+
* Google Sheets caps cell content / notes around 50,000 characters; we
|
|
27
|
+
* truncate well below that to leave room for the "and N more" suffix.
|
|
28
|
+
*/
|
|
29
|
+
export const NOTE_MAX_LENGTH = 49_000;
|
|
30
|
+
/**
|
|
31
|
+
* Maximum number of unique values to keep per query parameter key in
|
|
32
|
+
* dedupe mode. The Query Pattern cell only shows unique counts, but
|
|
33
|
+
* we keep a small sample for cell notes and to avoid unbounded memory
|
|
34
|
+
* growth on trackers that send a unique-per-request value
|
|
35
|
+
* (e.g. session IDs).
|
|
36
|
+
*/
|
|
37
|
+
export const MAX_PARAM_VALUE_SAMPLES = 100;
|
|
38
|
+
/**
|
|
39
|
+
* Field separator and `null` marker used in {@link dedupeKey}. Both
|
|
40
|
+
* are non-printable ASCII control characters that cannot appear in
|
|
41
|
+
* an HTTP status code, `Content-Type`, or any URL we pull out of the
|
|
42
|
+
* archive — so they are safe to use as in-band sentinels.
|
|
43
|
+
*/
|
|
44
|
+
const DEDUPE_KEY_SEP = String.fromCodePoint(1);
|
|
45
|
+
const DEDUPE_KEY_NULL = String.fromCodePoint(2);
|
|
46
|
+
/**
|
|
47
|
+
* Builds the Map key for a dedupe entry.
|
|
48
|
+
*
|
|
49
|
+
* Concatenates `status`, `contentType`, and `canonical` with a
|
|
50
|
+
* non-printable separator. A dedicated `null` marker keeps `null`
|
|
51
|
+
* distinct from `''` for `contentType`, and from `0` for `status`,
|
|
52
|
+
* so e.g. `(canonical, 200, null)` and `(canonical, 200, '')` land
|
|
53
|
+
* in different aggregation buckets.
|
|
54
|
+
*
|
|
55
|
+
* String concatenation is used instead of {@link JSON.stringify}
|
|
56
|
+
* because this function is called once per raw resource — on a
|
|
57
|
+
* million-resource archive `JSON.stringify` allocated roughly a
|
|
58
|
+
* million transient `SeqString`s, dominating Phase 3 wall-clock
|
|
59
|
+
* time. Plain concatenation is several times faster and produces
|
|
60
|
+
* the same collision-free key.
|
|
61
|
+
* @param canonical - The canonicalized URL.
|
|
62
|
+
* @param status - HTTP status code (nullable).
|
|
63
|
+
* @param contentType - HTTP content type (nullable).
|
|
64
|
+
*/
|
|
65
|
+
export function dedupeKey(canonical, status, contentType) {
|
|
66
|
+
const statusPart = status === null ? DEDUPE_KEY_NULL : String(status);
|
|
67
|
+
const contentTypePart = contentType === null ? DEDUPE_KEY_NULL : contentType;
|
|
68
|
+
return statusPart + DEDUPE_KEY_SEP + contentTypePart + DEDUPE_KEY_SEP + canonical;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Joins referrer URLs into a single newline-separated string, truncating
|
|
72
|
+
* at `maxLength` to stay within Google Sheets' note size cap. When
|
|
73
|
+
* truncated, appends a `... and N more` line where `N` counts every URL
|
|
74
|
+
* that did not fit, including the one whose insertion would have
|
|
75
|
+
* crossed the limit.
|
|
76
|
+
* @param referrers - The set of unique referrer page URLs.
|
|
77
|
+
* @param maxLength - Optional override for the character cap (defaults to {@link NOTE_MAX_LENGTH}).
|
|
78
|
+
*/
|
|
79
|
+
export function joinReferrersForNote(referrers, maxLength = NOTE_MAX_LENGTH) {
|
|
80
|
+
const total = referrers.size;
|
|
81
|
+
if (total === 0) {
|
|
82
|
+
return '';
|
|
83
|
+
}
|
|
84
|
+
const kept = [];
|
|
85
|
+
let used = 0;
|
|
86
|
+
let seen = 0;
|
|
87
|
+
for (const url of referrers) {
|
|
88
|
+
seen++;
|
|
89
|
+
const next = used + url.length + (kept.length > 0 ? 1 : 0);
|
|
90
|
+
if (next > maxLength) {
|
|
91
|
+
const remaining = total - seen + 1;
|
|
92
|
+
kept.push(`... and ${remaining} more`);
|
|
93
|
+
break;
|
|
94
|
+
}
|
|
95
|
+
kept.push(url);
|
|
96
|
+
used = next;
|
|
97
|
+
}
|
|
98
|
+
return kept.join('\n');
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Records a single `(key, value)` pair from a raw resource URL into
|
|
102
|
+
* the entry's per-key value tracker. New keys allocate a tracker; the
|
|
103
|
+
* value Set stops growing past {@link MAX_PARAM_VALUE_SAMPLES}, after
|
|
104
|
+
* which subsequent observations increment `overflowedCount` so
|
|
105
|
+
* {@link formatQueryPattern} can detect lost resolution and append `+`.
|
|
106
|
+
* @param entry - The dedupe entry to merge into.
|
|
107
|
+
* @param key - The query parameter key.
|
|
108
|
+
* @param value - The raw value substring (already extracted, not decoded).
|
|
109
|
+
*/
|
|
110
|
+
function recordParamValue(entry, key, value) {
|
|
111
|
+
let tracker = entry.paramValues.get(key);
|
|
112
|
+
if (!tracker) {
|
|
113
|
+
tracker = { values: new Set(), overflowedCount: 0 };
|
|
114
|
+
entry.paramValues.set(key, tracker);
|
|
115
|
+
}
|
|
116
|
+
if (tracker.values.size < MAX_PARAM_VALUE_SAMPLES) {
|
|
117
|
+
tracker.values.add(value);
|
|
118
|
+
}
|
|
119
|
+
else {
|
|
120
|
+
tracker.overflowedCount++;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Formats the Query Pattern cell for a dedupe entry. Each tracked key
|
|
125
|
+
* gets a `key=N` token where `N` is the number of distinct values
|
|
126
|
+
* sampled. `+` is appended only when {@link ParamValueTracker.overflowedCount}
|
|
127
|
+
* is non-zero — i.e. when at least one observation arrived after the
|
|
128
|
+
* sample set was already full. Duplicate observations that arrive
|
|
129
|
+
* while the sample set still has capacity do NOT trigger `+`.
|
|
130
|
+
*
|
|
131
|
+
* This gives precise semantics:
|
|
132
|
+
*
|
|
133
|
+
* - `key=1` — exactly one distinct value, seen any number of times
|
|
134
|
+
* - `key=99` — 99 distinct values, sample set still had room
|
|
135
|
+
* - `key=100` — exactly 100 distinct values, no observation lost
|
|
136
|
+
* - `key=100+` — sample set was capped and at least one further
|
|
137
|
+
* observation could not be recorded (real cardinality unknown but
|
|
138
|
+
* at least 100)
|
|
139
|
+
*
|
|
140
|
+
* Keys are sorted alphabetically to match the canonical URL.
|
|
141
|
+
*
|
|
142
|
+
* Returns `null` for entries without any query parameters so the cell
|
|
143
|
+
* appears empty in Google Sheets.
|
|
144
|
+
* @param entry - The dedupe entry to format.
|
|
145
|
+
*/
|
|
146
|
+
export function formatQueryPattern(entry) {
|
|
147
|
+
if (entry.paramValues.size === 0) {
|
|
148
|
+
return null;
|
|
149
|
+
}
|
|
150
|
+
const keys = [...entry.paramValues.keys()].toSorted();
|
|
151
|
+
const parts = [];
|
|
152
|
+
for (const key of keys) {
|
|
153
|
+
const tracker = entry.paramValues.get(key);
|
|
154
|
+
const overflowed = tracker.overflowedCount > 0;
|
|
155
|
+
parts.push(`${key}=${tracker.values.size}${overflowed ? '+' : ''}`);
|
|
156
|
+
}
|
|
157
|
+
return parts.join(', ');
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Formats the Content Length cell value. Returns a single number when
|
|
161
|
+
* every raw resource in the group reported the same size, a `min-max`
|
|
162
|
+
* string when the size varies, or `null` when nothing was recorded.
|
|
163
|
+
* @param entry - The dedupe entry to format.
|
|
164
|
+
*/
|
|
165
|
+
export function formatContentLength(entry) {
|
|
166
|
+
if (entry.contentLengthMin == null) {
|
|
167
|
+
return null;
|
|
168
|
+
}
|
|
169
|
+
if (entry.contentLengthMin === entry.contentLengthMax) {
|
|
170
|
+
return entry.contentLengthMin;
|
|
171
|
+
}
|
|
172
|
+
return `${entry.contentLengthMin}-${entry.contentLengthMax}`;
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Builds the cell row representation of a dedupe entry.
|
|
176
|
+
* @param entry - The dedupe entry to serialize.
|
|
177
|
+
*/
|
|
178
|
+
function dedupeEntryToRow(entry) {
|
|
179
|
+
return [
|
|
180
|
+
createCellData({ value: entry.canonical }, defaultCellFormat),
|
|
181
|
+
createCellData({ value: entry.status }, defaultCellFormat),
|
|
182
|
+
createCellData({ value: entry.statusText }, defaultCellFormat),
|
|
183
|
+
createCellData({ value: entry.contentType }, defaultCellFormat),
|
|
184
|
+
createCellData({ value: formatContentLength(entry) }, defaultCellFormat),
|
|
185
|
+
createCellData({
|
|
186
|
+
value: `${entry.referrers.size} pages`,
|
|
187
|
+
note: joinReferrersForNote(entry.referrers),
|
|
188
|
+
}, defaultCellFormat),
|
|
189
|
+
createCellData({ value: entry.count }, defaultCellFormat),
|
|
190
|
+
createCellData({ value: formatQueryPattern(entry) }, defaultCellFormat),
|
|
191
|
+
];
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Builds the cell row for a single raw resource (raw mode).
|
|
195
|
+
* @param resource - The resource record from the archive.
|
|
196
|
+
* @param referrers - The referrer URLs associated with the resource.
|
|
197
|
+
*/
|
|
198
|
+
function rawResourceToRow(resource, referrers) {
|
|
199
|
+
return [
|
|
200
|
+
createCellData({ value: resource.url }, defaultCellFormat),
|
|
201
|
+
createCellData({ value: resource.status }, defaultCellFormat),
|
|
202
|
+
createCellData({ value: resource.statusText }, defaultCellFormat),
|
|
203
|
+
createCellData({ value: resource.contentType }, defaultCellFormat),
|
|
204
|
+
createCellData({ value: resource.contentLength }, defaultCellFormat),
|
|
205
|
+
createCellData({
|
|
206
|
+
value: `${referrers.length} pages`,
|
|
207
|
+
note: referrers.join('\n'),
|
|
208
|
+
}, defaultCellFormat),
|
|
209
|
+
];
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Updates an existing dedupe entry with another raw resource that
|
|
213
|
+
* resolved to the same `(canonical, status, contentType)` key. Encapsulates
|
|
214
|
+
* the "first non-null" / "min-max" merge rules so they live in a single
|
|
215
|
+
* inspectable function.
|
|
216
|
+
* @param entry - The existing entry being merged into.
|
|
217
|
+
* @param resource - The new raw resource being folded into the entry.
|
|
218
|
+
*/
|
|
219
|
+
function mergeIntoEntry(entry, resource) {
|
|
220
|
+
if (entry.statusText == null && resource.statusText != null) {
|
|
221
|
+
entry.statusText = resource.statusText;
|
|
222
|
+
}
|
|
223
|
+
const len = resource.contentLength;
|
|
224
|
+
if (len != null) {
|
|
225
|
+
if (entry.contentLengthMin == null || len < entry.contentLengthMin) {
|
|
226
|
+
entry.contentLengthMin = len;
|
|
227
|
+
}
|
|
228
|
+
if (entry.contentLengthMax == null || len > entry.contentLengthMax) {
|
|
229
|
+
entry.contentLengthMax = len;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* Creates the "Resources" sheet configuration factory.
|
|
235
|
+
*
|
|
236
|
+
* Lists all network resources (CSS, JS, images, fonts, tracking pixels,
|
|
237
|
+
* etc.) discovered during crawling. Two modes are supported:
|
|
238
|
+
*
|
|
239
|
+
* - **Raw mode** (default): one row per raw resource URL. Six columns:
|
|
240
|
+
* URL, Status Code, Status Text, Content Type, Content Length,
|
|
241
|
+
* Referrers. Matches historical behavior.
|
|
242
|
+
* - **Dedupe mode** (`{ dedupe: true }`): collapses rows that share the
|
|
243
|
+
* same canonical URL (query values stripped, keys sorted) into one
|
|
244
|
+
* row per `(canonical URL, status, contentType)`. Adds a trailing
|
|
245
|
+
* `Count` column showing how many raw resources each row collapses.
|
|
246
|
+
* Useful when third-party tracking pixels generate millions of
|
|
247
|
+
* per-request unique URLs that would otherwise exceed the Google
|
|
248
|
+
* Sheets 10M-cell document limit.
|
|
249
|
+
*
|
|
250
|
+
* In dedupe mode the factory accumulates state inside `eachResource`
|
|
251
|
+
* and emits the aggregated rows once via the `finalizeResources` hook,
|
|
252
|
+
* which Phase 3 calls exactly once after the per-resource loop completes.
|
|
253
|
+
* @param options - Optional configuration. See {@link CreateResourcesOptions}.
|
|
254
|
+
*/
|
|
255
|
+
export function createResources(options) {
|
|
256
|
+
const dedupe = options?.dedupe === true;
|
|
257
|
+
return () => {
|
|
258
|
+
if (!dedupe) {
|
|
259
|
+
const setting = {
|
|
260
|
+
name: 'Resources',
|
|
261
|
+
createHeaders: () => [...RAW_HEADERS],
|
|
262
|
+
async eachResource(resource) {
|
|
263
|
+
reportLog(`Read: Resource referrers (Search: ${resource.url})`);
|
|
264
|
+
const referrers = await resource.getReferrers();
|
|
265
|
+
return [rawResourceToRow(resource, referrers)];
|
|
266
|
+
},
|
|
267
|
+
};
|
|
268
|
+
return setting;
|
|
269
|
+
}
|
|
270
|
+
const entries = new Map();
|
|
271
|
+
const setting = {
|
|
272
|
+
name: 'Resources',
|
|
273
|
+
// Sorting the 1M+ raw resource list before aggregation is
|
|
274
|
+
// wasted work: the 63K-row aggregated output is orders of
|
|
275
|
+
// magnitude smaller, and we sort it inside finalizeResources
|
|
276
|
+
// instead. This single flag flip turns a multi-minute sort
|
|
277
|
+
// into a sub-second one on million-resource archives.
|
|
278
|
+
skipSortResources: true,
|
|
279
|
+
createHeaders: () => [...DEDUPE_HEADERS],
|
|
280
|
+
async eachResource(resource) {
|
|
281
|
+
const canonical = canonicalizeUrl(resource.url);
|
|
282
|
+
const key = dedupeKey(canonical, resource.status, resource.contentType);
|
|
283
|
+
let entry = entries.get(key);
|
|
284
|
+
if (entry) {
|
|
285
|
+
mergeIntoEntry(entry, resource);
|
|
286
|
+
}
|
|
287
|
+
else {
|
|
288
|
+
entry = {
|
|
289
|
+
canonical,
|
|
290
|
+
status: resource.status,
|
|
291
|
+
statusText: resource.statusText,
|
|
292
|
+
contentType: resource.contentType,
|
|
293
|
+
contentLengthMin: resource.contentLength,
|
|
294
|
+
contentLengthMax: resource.contentLength,
|
|
295
|
+
count: 0,
|
|
296
|
+
referrers: new Set(),
|
|
297
|
+
paramValues: new Map(),
|
|
298
|
+
};
|
|
299
|
+
entries.set(key, entry);
|
|
300
|
+
}
|
|
301
|
+
entry.count++;
|
|
302
|
+
for (const { key: paramKey, value } of extractQueryPairs(resource.url)) {
|
|
303
|
+
recordParamValue(entry, paramKey, value);
|
|
304
|
+
}
|
|
305
|
+
reportLog(`Read: Resource referrers (Search: ${resource.url})`);
|
|
306
|
+
const referrers = await resource.getReferrers();
|
|
307
|
+
for (const ref of referrers) {
|
|
308
|
+
entry.referrers.add(ref);
|
|
309
|
+
}
|
|
310
|
+
return null;
|
|
311
|
+
},
|
|
312
|
+
finalizeResources() {
|
|
313
|
+
reportLog(`Dedupe complete: ${entries.size} canonical group(s) accumulated`);
|
|
314
|
+
// Sort the aggregated entries by canonical URL in natural
|
|
315
|
+
// order. This is N=tens-of-thousands rather than the
|
|
316
|
+
// millions in `entries`, so the cost is negligible
|
|
317
|
+
// compared to sorting the raw list up front.
|
|
318
|
+
const sortedEntries = [...entries.values()].toSorted((a, b) => naturalCompare(a.canonical, b.canonical));
|
|
319
|
+
const rows = sortedEntries.map(dedupeEntryToRow);
|
|
320
|
+
entries.clear();
|
|
321
|
+
return rows;
|
|
322
|
+
},
|
|
323
|
+
};
|
|
324
|
+
return setting;
|
|
44
325
|
};
|
|
45
|
-
}
|
|
326
|
+
}
|
package/lib/report.d.ts
CHANGED
|
@@ -16,6 +16,16 @@ export interface ReportParams {
|
|
|
16
16
|
readonly all?: boolean;
|
|
17
17
|
/** When `true`, suppress progress display output. */
|
|
18
18
|
readonly silent?: boolean;
|
|
19
|
+
/**
|
|
20
|
+
* When `true`, the Resources sheet collapses rows that share the same
|
|
21
|
+
* canonical URL (query *values* stripped, query *keys* sorted) into
|
|
22
|
+
* one row per `(canonical URL, status, contentType)` combination,
|
|
23
|
+
* with an added `Count` column. Useful for archives where tracking
|
|
24
|
+
* pixels generate millions of per-request unique URLs that would
|
|
25
|
+
* otherwise exceed Google Sheets' 10M-cell document limit. Defaults
|
|
26
|
+
* to `false` (raw mode).
|
|
27
|
+
*/
|
|
28
|
+
readonly dedupeResources?: boolean;
|
|
19
29
|
}
|
|
20
30
|
/**
|
|
21
31
|
* Generates a Google Sheets report from a `.nitpicker` archive file.
|