@nitpicker/report-google-sheets 0.21.0 → 0.22.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.
@@ -7,7 +7,13 @@ import type { CreateSheet } from '../sheets/types.js';
7
7
  * into a `Report.violations` array before generation started (via
8
8
  * `getPluginReports`). No read-model dependency: `analysis_violations` is a
9
9
  * write-model table.
10
- * @param _reports - Unused; the Violations sheet has no plugin-report dependency.
11
- * @param accessor - The archive accessor to query.
10
+ * `options.urls` (already normalized via `resolvePageListUrlFilter`)
11
+ * restricts both `estimateRowCount` and `run` to violations reported
12
+ * against exactly those pages.
13
+ * @param options - Row-set restriction. Omitted or `urls: undefined` reports every violation.
14
+ * @param options.urls - See above.
15
+ * @returns A {@link CreateSheet} factory for the Violations sheet.
12
16
  */
13
- export declare const createViolations: CreateSheet;
17
+ export declare function createViolations(options?: {
18
+ urls?: readonly string[];
19
+ }): CreateSheet;
@@ -1,15 +1,18 @@
1
- import { streamAllViolations } from '@nitpicker/query';
1
+ import { applyEqualityOrInFilter, streamAllViolations } from '@nitpicker/query';
2
2
  import { createCellData } from '../sheets/create-cell-data.js';
3
3
  import { defaultCellFormat } from '../sheets/default-cell-format.js';
4
4
  /**
5
5
  * Counts every `analysis_violations` row, for `estimateRowCount()`.
6
6
  * @param accessor - The archive accessor to query.
7
+ * @param urls - Exact-match URL allowlist, already normalized. Omitted or empty counts every row.
7
8
  */
8
- async function countViolations(accessor) {
9
+ async function countViolations(accessor, urls) {
9
10
  const knex = accessor.getKnex();
10
- const [row] = await knex('analysis_violations').count({
11
- count: '*',
12
- });
11
+ const [row] = await knex('analysis_violations as v')
12
+ .join('content_items as p', 'p.id', 'v.page_id')
13
+ .join('url_refs as ur', 'ur.id', 'p.url_id')
14
+ .modify((qb) => applyEqualityOrInFilter(qb, 'ur.url', urls))
15
+ .count({ count: '*' });
13
16
  return Number(row?.count ?? 0);
14
17
  }
15
18
  /**
@@ -20,38 +23,45 @@ async function countViolations(accessor) {
20
23
  * into a `Report.violations` array before generation started (via
21
24
  * `getPluginReports`). No read-model dependency: `analysis_violations` is a
22
25
  * write-model table.
23
- * @param _reports - Unused; the Violations sheet has no plugin-report dependency.
24
- * @param accessor - The archive accessor to query.
26
+ * `options.urls` (already normalized via `resolvePageListUrlFilter`)
27
+ * restricts both `estimateRowCount` and `run` to violations reported
28
+ * against exactly those pages.
29
+ * @param options - Row-set restriction. Omitted or `urls: undefined` reports every violation.
30
+ * @param options.urls - See above.
31
+ * @returns A {@link CreateSheet} factory for the Violations sheet.
25
32
  */
26
- export const createViolations = (_reports, accessor) => {
27
- return {
28
- name: 'Violations',
29
- createHeaders() {
30
- return ['Validator', 'Severity', 'Rule', 'Code', 'Message', 'URL'];
31
- },
32
- estimateRowCount: () => countViolations(accessor),
33
- async run({ sheet, maxRows, estimatedTotal, onProgress }) {
34
- let sent = 0;
35
- const total = estimatedTotal;
36
- for await (const chunk of streamAllViolations(accessor)) {
37
- for (const violation of chunk) {
38
- if (sent >= maxRows) {
39
- await sheet.flush();
40
- return;
33
+ export function createViolations(options) {
34
+ const urls = options?.urls;
35
+ return (_reports, accessor) => {
36
+ return {
37
+ name: 'Violations',
38
+ createHeaders() {
39
+ return ['Validator', 'Severity', 'Rule', 'Code', 'Message', 'URL'];
40
+ },
41
+ estimateRowCount: () => countViolations(accessor, urls),
42
+ async run({ sheet, maxRows, estimatedTotal, onProgress }) {
43
+ let sent = 0;
44
+ const total = estimatedTotal;
45
+ for await (const chunk of streamAllViolations(accessor, { urls })) {
46
+ for (const violation of chunk) {
47
+ if (sent >= maxRows) {
48
+ await sheet.flush();
49
+ return;
50
+ }
51
+ await sheet.appendRow([
52
+ createCellData({ value: violation.validator }, defaultCellFormat),
53
+ createCellData({ value: violation.severity }, defaultCellFormat),
54
+ createCellData({ value: violation.rule }, defaultCellFormat),
55
+ createCellData({ value: violation.code }, defaultCellFormat),
56
+ createCellData({ value: violation.message }, defaultCellFormat),
57
+ createCellData({ value: violation.url }, defaultCellFormat),
58
+ ]);
59
+ sent++;
60
+ onProgress(sent, total);
41
61
  }
42
- await sheet.appendRow([
43
- createCellData({ value: violation.validator }, defaultCellFormat),
44
- createCellData({ value: violation.severity }, defaultCellFormat),
45
- createCellData({ value: violation.rule }, defaultCellFormat),
46
- createCellData({ value: violation.code }, defaultCellFormat),
47
- createCellData({ value: violation.message }, defaultCellFormat),
48
- createCellData({ value: violation.url }, defaultCellFormat),
49
- ]);
50
- sent++;
51
- onProgress(sent, total);
52
62
  }
53
- }
54
- await sheet.flush();
55
- },
63
+ await sheet.flush();
64
+ },
65
+ };
56
66
  };
57
- };
67
+ }
@@ -1 +1,2 @@
1
- export { report } from './report.js';
1
+ export { report, SHEET_PRIORITY_ORDER } from './report.js';
2
+ export type { ReportParams, SheetName } from './report.js';
@@ -1 +1 @@
1
- export { report } from './report.js';
1
+ export { report, SHEET_PRIORITY_ORDER } from './report.js';
package/lib/report.d.ts CHANGED
@@ -1,3 +1,13 @@
1
+ /**
2
+ * Every generatable sheet name, in **priority order** — the order
3
+ * `createSheetList` is built in below, which `create-sheets.ts`'s Phase 2
4
+ * treats as the cell-budget allocation priority (see that file's docs).
5
+ * User-visible, more universally useful sheets first; the two relational
6
+ * tables last since their row counts (one row per edge, not per page) are
7
+ * the most likely to explode past the Google Sheets 10M-cell limit.
8
+ */
9
+ export declare const SHEET_PRIORITY_ORDER: readonly ["Page List", "Links", "Violations", "Discrepancies", "Resources", "Images", "Referrers Relational Table", "Resources Relational Table", "Summary"];
10
+ export type SheetName = (typeof SHEET_PRIORITY_ORDER)[number];
1
11
  /**
2
12
  * Parameters for {@link report}.
3
13
  */
@@ -27,6 +37,30 @@ export interface ReportParams {
27
37
  * value here.
28
38
  */
29
39
  readonly dedupeResources?: boolean;
40
+ /**
41
+ * Restricts generation to pages matching these URLs (raw, pre-normalization —
42
+ * normalized internally against the archive's `disableQueries` config via
43
+ * `resolveAndValidatePageListUrlFilter`). When set, only the four sheets whose
44
+ * rows are one-per-page (`Page List`, `Links`, `Violations`, `Images`) are
45
+ * eligible for generation — see {@link URL_FILTERABLE_SHEETS}'s docs for why
46
+ * the rest are excluded. An empty array is rejected by
47
+ * `resolveAndValidatePageListUrlFilter` rather than silently falling back to
48
+ * "no filter" — the underlying `applyEqualityOrInFilter` treats an empty
49
+ * array as no filter, which here would turn a mistaken empty `--urls` into an
50
+ * unfiltered full run.
51
+ */
52
+ readonly urls?: readonly string[];
53
+ /**
54
+ * Explicit sheet names to generate, bypassing both `--all` and the
55
+ * interactive multiselect prompt (`--all`/interactive are the only two
56
+ * selection modes exposed by the CLI otherwise, and a non-interactive
57
+ * caller that wants a specific subset of sheets has no way to express
58
+ * that). Takes precedence over `all` when both are set. Not validated
59
+ * against `--urls`'s `URL_FILTERABLE_SHEETS` restriction — the caller is
60
+ * responsible for only requesting sheets that make sense with whatever
61
+ * `urls` filter it also passed.
62
+ */
63
+ readonly sheets?: readonly SheetName[];
30
64
  /**
31
65
  * Called during the archive-open untar step with bytes read so far and
32
66
  * the archive's total size (issue #294: a large archive's extraction can
@@ -67,5 +101,16 @@ export interface ReportParams {
67
101
  * configPath: './nitpicker.config.json',
68
102
  * });
69
103
  * ```
104
+ * @example
105
+ * ```ts
106
+ * // Skip the interactive prompt and generate exactly these sheets.
107
+ * await report({
108
+ * filePath: './output.nitpicker',
109
+ * sheetUrl: 'https://docs.google.com/spreadsheets/d/xxx/edit',
110
+ * credentialFilePath: './credentials.json',
111
+ * configPath: null,
112
+ * sheets: ['Page List', 'Links'],
113
+ * });
114
+ * ```
70
115
  */
71
116
  export declare function report(params: ReportParams): Promise<void>;
package/lib/report.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { authentication } from '@d-zero/google-auth';
2
2
  import { Sheets } from '@d-zero/google-sheets';
3
+ import { resolveAndValidatePageListUrlFilter, warnUnmatchedPageListUrls, } from '@nitpicker/query';
3
4
  import enquirer from 'enquirer';
4
5
  import { createDiscrepancies } from './data/create-discrepancies.js';
5
6
  import { createImageList } from './data/create-image-list.js';
@@ -22,7 +23,7 @@ import { createSheets } from './sheets/create-sheets.js';
22
23
  * tables last since their row counts (one row per edge, not per page) are
23
24
  * the most likely to explode past the Google Sheets 10M-cell limit.
24
25
  */
25
- const SHEET_PRIORITY_ORDER = [
26
+ export const SHEET_PRIORITY_ORDER = [
26
27
  'Page List',
27
28
  'Links',
28
29
  'Violations',
@@ -33,6 +34,31 @@ const SHEET_PRIORITY_ORDER = [
33
34
  'Resources Relational Table',
34
35
  'Summary',
35
36
  ];
37
+ /**
38
+ * Sheets whose row set can be restricted to a `--urls` allowlist: each one's
39
+ * row is a single page's own data, so "restrict to these pages" has an
40
+ * unambiguous meaning. The rest are excluded from both `--all` and the
41
+ * interactive picker when `--urls` is given:
42
+ *
43
+ * - `Discrepancies` compares two URLs per row (`leftSourceUrl`/
44
+ * `rightSourceUrl`) — which side matching `--urls` should keep is
45
+ * undefined.
46
+ * - `Resources` / `Resources Relational Table` are many-to-many with pages
47
+ * (one resource can be referenced by many pages), and the dedupe-mode
48
+ * aggregation is precomputed at `viewer-build` time across the whole
49
+ * archive — filtering it after the fact would make its `Count`/referrer
50
+ * columns disagree with their own documented meaning.
51
+ * - `Referrers Relational Table` is a source/dest edge — restricting by
52
+ * either side alone would silently change which half of the table
53
+ * "restrict to these pages" means.
54
+ * - `Summary` has no generator at all (see the `switch` below).
55
+ */
56
+ const URL_FILTERABLE_SHEETS = [
57
+ 'Page List',
58
+ 'Links',
59
+ 'Violations',
60
+ 'Images',
61
+ ];
36
62
  /**
37
63
  * Generates a Google Sheets report from a `.nitpicker` archive file.
38
64
  *
@@ -64,10 +90,22 @@ const SHEET_PRIORITY_ORDER = [
64
90
  * configPath: './nitpicker.config.json',
65
91
  * });
66
92
  * ```
93
+ * @example
94
+ * ```ts
95
+ * // Skip the interactive prompt and generate exactly these sheets.
96
+ * await report({
97
+ * filePath: './output.nitpicker',
98
+ * sheetUrl: 'https://docs.google.com/spreadsheets/d/xxx/edit',
99
+ * credentialFilePath: './credentials.json',
100
+ * configPath: null,
101
+ * sheets: ['Page List', 'Links'],
102
+ * });
103
+ * ```
67
104
  */
68
105
  export async function report(params) {
69
106
  const { filePath, sheetUrl, credentialFilePath, configPath, all, silent, dedupeResources, onExtractProgress, } = params;
70
107
  log('Initialization');
108
+ const warnings = [];
71
109
  const SCOPES = ['https://www.googleapis.com/auth/spreadsheets'];
72
110
  log('Authenticating');
73
111
  const auth = await authentication(credentialFilePath, SCOPES, {
@@ -78,6 +116,10 @@ export async function report(params) {
78
116
  await using archiveHandle = await openReportArchive(filePath, onExtractProgress);
79
117
  const { accessor } = archiveHandle;
80
118
  log('Archive opened');
119
+ const collectWarning = (message) => warnings.push(`${message}\n`);
120
+ const normalizedUrls = params.urls === undefined
121
+ ? undefined
122
+ : await resolveAndValidatePageListUrlFilter(accessor, params.urls, collectWarning);
81
123
  log('Loading config');
82
124
  const config = await loadConfig(configPath);
83
125
  log('Config loaded');
@@ -90,10 +132,19 @@ export async function report(params) {
90
132
  log('Plugin reports loaded: %d', reports.length);
91
133
  const sheets = new Sheets(sheetUrl, auth);
92
134
  log('Reporting starts');
135
+ const availableSheetNames = normalizedUrls === undefined ? SHEET_PRIORITY_ORDER : URL_FILTERABLE_SHEETS;
136
+ if (normalizedUrls !== undefined) {
137
+ const excluded = SHEET_PRIORITY_ORDER.filter((name) => !URL_FILTERABLE_SHEETS.includes(name));
138
+ warnings.push(`--urls: restricting to URL-filterable sheets only. Excluded (no unambiguous per-URL restriction): ${excluded.join(', ')}.\n`);
139
+ }
93
140
  let selectedSheetNames;
94
- if (all) {
141
+ if (params.sheets) {
142
+ log('Explicit sheets selected: %O', params.sheets);
143
+ selectedSheetNames = [...params.sheets];
144
+ }
145
+ else if (all) {
95
146
  log('All sheets selected (--all or non-TTY)');
96
- selectedSheetNames = [...SHEET_PRIORITY_ORDER];
147
+ selectedSheetNames = [...availableSheetNames];
97
148
  }
98
149
  else {
99
150
  log('Choice creating data');
@@ -103,7 +154,7 @@ export async function report(params) {
103
154
  message: 'What do you report?',
104
155
  name: 'sheetName',
105
156
  type: 'multiselect',
106
- choices: [...SHEET_PRIORITY_ORDER],
157
+ choices: [...availableSheetNames],
107
158
  },
108
159
  ])
109
160
  .catch(() => {
@@ -119,7 +170,6 @@ export async function report(params) {
119
170
  selectedSheetNames = chosenSheets.sheetName;
120
171
  }
121
172
  log('Chosen sheets: %O', selectedSheetNames);
122
- const warnings = [];
123
173
  // Priority order is the fixed SHEET_PRIORITY_ORDER, not the user's
124
174
  // selection-click order — createSheets's Phase 2 treats array order as
125
175
  // the cell-budget allocation priority (see that file's docs).
@@ -130,15 +180,15 @@ export async function report(params) {
130
180
  }
131
181
  switch (name) {
132
182
  case 'Page List': {
133
- createSheetList.push(createPageList);
183
+ createSheetList.push(createPageList({ urls: normalizedUrls }));
134
184
  break;
135
185
  }
136
186
  case 'Links': {
137
- createSheetList.push(createLinks);
187
+ createSheetList.push(createLinks({ urls: normalizedUrls }));
138
188
  break;
139
189
  }
140
190
  case 'Violations': {
141
- createSheetList.push(createViolations);
191
+ createSheetList.push(createViolations({ urls: normalizedUrls }));
142
192
  break;
143
193
  }
144
194
  case 'Discrepancies': {
@@ -150,7 +200,7 @@ export async function report(params) {
150
200
  break;
151
201
  }
152
202
  case 'Images': {
153
- createSheetList.push(createImageList);
203
+ createSheetList.push(createImageList({ urls: normalizedUrls }));
154
204
  break;
155
205
  }
156
206
  case 'Referrers Relational Table': {
@@ -187,6 +237,9 @@ export async function report(params) {
187
237
  },
188
238
  });
189
239
  log('Reporting done');
240
+ if (normalizedUrls !== undefined) {
241
+ await warnUnmatchedPageListUrls(accessor, normalizedUrls, collectWarning);
242
+ }
190
243
  for (const warning of warnings) {
191
244
  // eslint-disable-next-line no-console
192
245
  console.error(warning);
@@ -77,8 +77,17 @@ export interface CreateSheetsParams {
77
77
  * 形式に整形し、`dedupeProgressMessage` で同一文字列の連続再描画を間引く
78
78
  * (百万行規模のシートで毎行再描画するとターミナルが埋まる)。`sheet.onProgress`
79
79
  * (`@d-zero/google-sheets` 側、チャンク単位のコールバック)も同時に配線しており、
80
- * `appendRow()` の自動 flush や末尾の明示 `flush()` 呼び出し——数秒かかりうる
81
- * ネットワーク往復——の最中も無音区間にならない。
80
+ * `appendRow()` の自動 flush が完了するたびに表示を更新する。
81
+ *
82
+ * ただし `onProgress` はチャンクの `batchUpdate` 完了**後**にしか発火しない
83
+ * ため、そのネットワーク往復自体(数秒〜数十秒かかりうる)は無音区間になる。
84
+ * 総行数が `SEND_CHUNK_SIZE`(2500)の倍数でない限り、`run()` 自身の
85
+ * `onProgress` は最終行をバッファへ積んだ時点で `100%` を表示してしまい、
86
+ * 直後のステップ末尾の明示 `flush()` 呼び出し(残りバッファの実送信)が
87
+ * ちょうどこの無音区間に当たる——`100%` のまま応答が止まって見える原因。
88
+ * そのため `flush()` 呼び出し直前に `sheet.pendingCount`(未送信バッファ行数)
89
+ * を使って `"flushing N rows..."` という一時メッセージを出し、無反応に見える
90
+ * 区間を作らない。
82
91
  *
83
92
  * Google Sheets API のレート制限(429/403/5xx/ECONNRESET)による待機は
84
93
  * `sheets.onLog` 経由で検知し、その時点で実行中のステップの行に一時的に上書き表示
@@ -57,8 +57,17 @@ const NULL_STREAM = {
57
57
  * 形式に整形し、`dedupeProgressMessage` で同一文字列の連続再描画を間引く
58
58
  * (百万行規模のシートで毎行再描画するとターミナルが埋まる)。`sheet.onProgress`
59
59
  * (`@d-zero/google-sheets` 側、チャンク単位のコールバック)も同時に配線しており、
60
- * `appendRow()` の自動 flush や末尾の明示 `flush()` 呼び出し——数秒かかりうる
61
- * ネットワーク往復——の最中も無音区間にならない。
60
+ * `appendRow()` の自動 flush が完了するたびに表示を更新する。
61
+ *
62
+ * ただし `onProgress` はチャンクの `batchUpdate` 完了**後**にしか発火しない
63
+ * ため、そのネットワーク往復自体(数秒〜数十秒かかりうる)は無音区間になる。
64
+ * 総行数が `SEND_CHUNK_SIZE`(2500)の倍数でない限り、`run()` 自身の
65
+ * `onProgress` は最終行をバッファへ積んだ時点で `100%` を表示してしまい、
66
+ * 直後のステップ末尾の明示 `flush()` 呼び出し(残りバッファの実送信)が
67
+ * ちょうどこの無音区間に当たる——`100%` のまま応答が止まって見える原因。
68
+ * そのため `flush()` 呼び出し直前に `sheet.pendingCount`(未送信バッファ行数)
69
+ * を使って `"flushing N rows..."` という一時メッセージを出し、無反応に見える
70
+ * 区間を作らない。
62
71
  *
63
72
  * Google Sheets API のレート制限(429/403/5xx/ECONNRESET)による待機は
64
73
  * `sheets.onLog` 経由で検知し、その時点で実行中のステップの行に一時的に上書き表示
@@ -238,6 +247,14 @@ export async function createSheets(params) {
238
247
  // the TRUNCATED marker row appended above, if any. `flush()`
239
248
  // is a no-op on an empty buffer, so calling it unconditionally
240
249
  // here is safe either way.
250
+ //
251
+ // `run()`'s own onProgress already reported 100% once the last
252
+ // row was buffered (see this function's JSDoc) — without this,
253
+ // the display would sit frozen at 100% for the entire network
254
+ // round trip below, with nothing to show it's still working.
255
+ if (sheet.pendingCount > 0) {
256
+ active?.(`flushing ${sheet.pendingCount.toLocaleString()} rows...`);
257
+ }
241
258
  await sheet.flush();
242
259
  if (truncated) {
243
260
  onWarn?.(`Warning: "${setting.name}" was truncated at ${sent} rows (cell budget).\n`);
@@ -36,6 +36,13 @@ export function createMockSheet() {
36
36
  get sentCount() {
37
37
  return rows.length;
38
38
  },
39
+ // This mock treats every `appendRow()` call as immediately sent (see
40
+ // `sentCount` above) rather than simulating the real `Sheet`'s
41
+ // buffer-until-chunk-threshold behavior, so nothing is ever "pending"
42
+ // in its model.
43
+ get pendingCount() {
44
+ return 0;
45
+ },
39
46
  frozen() {
40
47
  return Promise.resolve();
41
48
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nitpicker/report-google-sheets",
3
- "version": "0.21.0",
3
+ "version": "0.22.0",
4
4
  "description": "Nitpicker reporter that outputs crawl and analysis results to Google Sheets",
5
5
  "author": "D-ZERO",
6
6
  "license": "Apache-2.0",
@@ -30,13 +30,13 @@
30
30
  "clean": "tsc --build --clean"
31
31
  },
32
32
  "dependencies": {
33
- "@d-zero/dealer": "1.13.1",
33
+ "@d-zero/dealer": "1.14.0",
34
34
  "@d-zero/google-auth": "0.7.6",
35
- "@d-zero/google-sheets": "0.10.0",
35
+ "@d-zero/google-sheets": "0.11.0",
36
36
  "@d-zero/shared": "0.23.0",
37
- "@nitpicker/crawler": "0.21.0",
38
- "@nitpicker/query": "0.21.0",
39
- "@nitpicker/types": "0.21.0",
37
+ "@nitpicker/crawler": "0.22.0",
38
+ "@nitpicker/query": "0.22.0",
39
+ "@nitpicker/types": "0.22.0",
40
40
  "ansi-colors": "4.1.3",
41
41
  "debug": "4.4.3",
42
42
  "enquirer": "2.4.1"
@@ -46,5 +46,5 @@
46
46
  "googleapis": "173.0.0",
47
47
  "vitest": "4.1.11"
48
48
  },
49
- "gitHead": "233d081009aeeeb2d2622536ca29b22693ba65ca"
49
+ "gitHead": "934b1714f4394effb3865d84bf8348ed74f45840"
50
50
  }