@nitpicker/report-google-sheets 0.8.0 → 0.11.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,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
- * Creates the "Resources" sheet configuration.
6
- *
7
- * Lists all network resources (CSS, JS, images, fonts, etc.) discovered
8
- * during crawling, with one row per unique resource URL. Each row includes
9
- * HTTP status, content type, size, and the number of pages that reference
10
- * the resource (with URLs listed in the cell note).
11
- *
12
- * Uses `eachResource` (Phase 3) to iterate over the archive's resource
13
- * table rather than page-by-page iteration.
14
- */
15
- export const createResources = () => {
16
- return {
17
- name: 'Resources',
18
- createHeaders() {
19
- return [
20
- 'URL',
21
- 'Status Code',
22
- 'Status Text',
23
- 'Content Type',
24
- 'Content Length',
25
- 'Referrers',
26
- ];
27
- },
28
- async eachResource(resource) {
29
- reportLog(`Read: Resource referrers (Search: ${resource.url})`);
30
- const referrers = await resource.getReferrers();
31
- const data = [
32
- createCellData({ value: resource.url }, defaultCellFormat),
33
- createCellData({ value: resource.status }, defaultCellFormat),
34
- createCellData({ value: resource.statusText }, defaultCellFormat),
35
- createCellData({ value: resource.contentType }, defaultCellFormat),
36
- createCellData({ value: resource.contentLength }, defaultCellFormat),
37
- createCellData({
38
- value: `${referrers.length} pages`,
39
- note: referrers.join('\n'),
40
- }, defaultCellFormat),
41
- ];
42
- return [data];
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.
package/lib/report.js CHANGED
@@ -46,7 +46,7 @@ import { createSheets } from './sheets/create-sheets.js';
46
46
  * ```
47
47
  */
48
48
  export async function report(params) {
49
- const { filePath, sheetUrl, credentialFilePath, configPath, limit, all, silent } = params;
49
+ const { filePath, sheetUrl, credentialFilePath, configPath, limit, all, silent, dedupeResources, } = params;
50
50
  log('Initialization');
51
51
  const SCOPES = ['https://www.googleapis.com/auth/spreadsheets'];
52
52
  log('Authenticating');
@@ -130,7 +130,7 @@ export async function report(params) {
130
130
  createSheetList.push(createResourcesRelationalTable);
131
131
  }
132
132
  if (selectedSheetNames.includes('Resources')) {
133
- createSheetList.push(createResources);
133
+ createSheetList.push(createResources({ dedupe: dedupeResources }));
134
134
  }
135
135
  if (selectedSheetNames.includes('Images')) {
136
136
  createSheetList.push(createImageList);
@@ -37,31 +37,26 @@ export interface CreateSheetsParams {
37
37
  * → Phase 5 (Formatting sheets)
38
38
  * ```
39
39
  *
40
- * ## Lanes 進捗表示
41
- *
42
- * ### ヘッダー: 加重平均による集計
40
+ * ## 行送信戦略
43
41
  *
44
- * Phase 2/3 のヘッダーは全子タスク(シート)の進捗を加重平均で集計する。
42
+ * Phase 2 / 3 はページ・リソースを反復しながら、生成した行を都度
43
+ * `sheet.appendRow(...rows)` に渡してストリーミング送信する。`sheet.appendRow()` は
44
+ * `@d-zero/google-sheets` 側で 2500 行ごとに自動 flush する(呼び出し元は
45
+ * チャンクサイズを意識しない)。バッチ終端で `sheet.flush()` を呼んで残余を排出する。
45
46
  *
46
- * 以前の実装では `Math.min()` で最遅シートのページ生成進捗のみを表示していたが、
47
- * シートごとに「生成完了→行送信中」「まだ生成中」「送信完了」と異なるサブフェーズに
48
- * いる場合、ヘッダーの数値と各レーンの表示が乖離する問題があった。
49
- * 例: ヘッダー「174/755 (23%)」だが Page List は既に Sent、
50
- * Referrers RT は Sending rows 7500/13256 — ヘッダーが全体を見ていない。
47
+ * 遅延セル(`createCellData(() => ...)` の thunk)を含む行が混ざった場合、
48
+ * `appendRow()` はその時点で自動 flush を停止し、明示的な `flush()` 呼び出しまで
49
+ * バッファに保留する(順序保証)。Page List の「Internal Referrers」列がこの
50
+ * 仕組みに乗っており、バッチ終端の `flush()` で初めて評価される。
51
51
  *
52
- * 解決策として、各シートの進捗を 0.0〜1.0 の fraction で管理し、
53
- * 全シートの平均値をヘッダーに表示する:
52
+ * ## Lanes 進捗表示
54
53
  *
55
- * - **生成フェーズ**: `(pageNum / max) * 0.5` → 0%〜50%
56
- * - **送信フェーズ**: `0.5 + (sentRows / totalRows) * 0.5` → 50%〜100%
57
- * (`sendRowsInChunks` の `onProgress` コールバック経由)
58
- * - **完了**: 1.0 (100%)
54
+ * ### ヘッダー: 加重平均による集計
59
55
  *
60
- * 生成と送信を 50:50 で重み付けしている理由:
61
- * - 生成だけで 0〜100% にすると、全シートが生成完了(100%)になっても
62
- * 送信が残っている状態で「100%」と表示されてしまう
63
- * - 送信(特に大量行のチャンク送信)は Google API の
64
- * レート制限により生成と同程度の時間がかかるため、等配分が妥当
56
+ * Phase 2/3 のヘッダーは全子タスク(シート)の進捗 (`pageNum / max`) の
57
+ * 平均をパーセント表示する。生成と送信が同一の `appendRow` 呼び出しで一体化
58
+ * しているため、ヘッダーは単一の fraction で済む(旧実装にあった生成 0〜50% /
59
+ * 送信 50〜100% の二段重み付けは不要になった)。
65
60
  *
66
61
  * ### レーン: フェーズ遷移に応じた状態表示
67
62
  *