@nitpicker/report-google-sheets 0.19.0 → 0.20.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.
Files changed (56) hide show
  1. package/lib/data/create-discrepancies.d.ts +10 -12
  2. package/lib/data/create-discrepancies.js +27 -31
  3. package/lib/data/create-image-list.d.ts +26 -6
  4. package/lib/data/create-image-list.js +65 -39
  5. package/lib/data/create-links.d.ts +18 -1
  6. package/lib/data/create-links.js +91 -55
  7. package/lib/data/create-page-list.d.ts +24 -24
  8. package/lib/data/create-page-list.js +177 -225
  9. package/lib/data/create-referrers-relational-table.d.ts +13 -7
  10. package/lib/data/create-referrers-relational-table.js +57 -47
  11. package/lib/data/create-resources-relational-table.d.ts +7 -0
  12. package/lib/data/create-resources-relational-table.js +41 -33
  13. package/lib/data/create-resources.d.ts +24 -124
  14. package/lib/data/create-resources.js +100 -264
  15. package/lib/data/create-violations.d.ts +7 -6
  16. package/lib/data/create-violations.js +34 -19
  17. package/lib/dedupe-progress-message.d.ts +17 -0
  18. package/lib/dedupe-progress-message.js +26 -0
  19. package/lib/format-progress-count.d.ts +19 -0
  20. package/lib/format-progress-count.js +22 -0
  21. package/lib/open-report-archive.d.ts +54 -0
  22. package/lib/open-report-archive.js +76 -0
  23. package/lib/report.d.ts +16 -12
  24. package/lib/report.js +101 -94
  25. package/lib/reports/get-plugin-reports.d.ts +14 -6
  26. package/lib/reports/get-plugin-reports.js +14 -34
  27. package/lib/sheets/create-sheets.d.ts +66 -36
  28. package/lib/sheets/create-sheets.js +228 -362
  29. package/lib/sheets/estimate-cell-budget.d.ts +55 -0
  30. package/lib/sheets/estimate-cell-budget.js +56 -0
  31. package/lib/sheets/types.d.ts +111 -91
  32. package/lib/test-helpers/assert-no-lazy-cells.d.ts +16 -0
  33. package/lib/test-helpers/assert-no-lazy-cells.js +23 -0
  34. package/lib/test-helpers/cell-inspection.d.ts +20 -0
  35. package/lib/test-helpers/cell-inspection.js +21 -0
  36. package/lib/test-helpers/create-mock-sheet.d.ts +30 -0
  37. package/lib/test-helpers/create-mock-sheet.js +71 -0
  38. package/lib/test-helpers/one-chunk.d.ts +8 -0
  39. package/lib/test-helpers/one-chunk.js +11 -0
  40. package/lib/utils/join-urls-for-note.d.ts +27 -0
  41. package/lib/utils/join-urls-for-note.js +48 -0
  42. package/lib/utils/truncate-note-text.d.ts +15 -0
  43. package/lib/utils/truncate-note-text.js +23 -0
  44. package/package.json +7 -9
  45. package/lib/archive.d.ts +0 -29
  46. package/lib/archive.js +0 -49
  47. package/lib/sheets/run-finalize-resources.d.ts +0 -40
  48. package/lib/sheets/run-finalize-resources.js +0 -44
  49. package/lib/types.d.ts +0 -11
  50. package/lib/types.js +0 -1
  51. package/lib/utils/canonicalize-url.d.ts +0 -53
  52. package/lib/utils/canonicalize-url.js +0 -105
  53. package/lib/utils/has-prop-filter.d.ts +0 -18
  54. package/lib/utils/has-prop-filter.js +0 -19
  55. package/lib/utils/sort-resources-by-url.d.ts +0 -69
  56. package/lib/utils/sort-resources-by-url.js +0 -223
@@ -1,399 +1,265 @@
1
- import c from 'ansi-colors';
1
+ import { TaskList } from '@d-zero/dealer';
2
+ import { requireViewerReadModel } from '@nitpicker/query';
2
3
  import { sheetLog } from '../debug.js';
3
- import { hasPropFilter } from '../utils/has-prop-filter.js';
4
- import { sortResourcesByUrl } from '../utils/sort-resources-by-url.js';
5
- import { runFinalizeResources } from './run-finalize-resources.js';
4
+ import { dedupeProgressMessage } from '../dedupe-progress-message.js';
5
+ import { formatProgressCount } from '../format-progress-count.js';
6
+ import { createCellData } from './create-cell-data.js';
7
+ import { defaultCellFormat } from './default-cell-format.js';
8
+ import { CELL_BUDGET_LIMIT, estimateCellBudget } from './estimate-cell-budget.js';
9
+ /** A `write()`-only sink that renders nothing, for `options.silent`. */
10
+ const NULL_STREAM = {
11
+ write: () => true,
12
+ on: () => NULL_STREAM,
13
+ off: () => NULL_STREAM,
14
+ };
6
15
  /**
7
16
  * Google Sheets にシートを作成し、データを投入してフォーマットする。
8
17
  *
9
- * ## 処理フェーズ
18
+ * ## タスクリスト構成
10
19
  *
11
- * 5つのフェーズで構成され、Phase 2+3 と Phase 4 は並列実行される:
20
+ * `@d-zero/dealer` の `TaskList`(逐次パイプライン)で、選択されたシートの数だけ
21
+ * 動的にステップを積む — 固定行数ではなくユーザー選択に応じて可変:
12
22
  *
13
23
  * ```
14
- * Phase 1 (Creating sheets)
15
- * → Phase 2 (Processing pages) ─→ Phase 3 (Processing resources)
16
- * → Phase 4 (Plugin data / addRows) ← Phase 2+3 と並列
17
- * → Phase 5 (Formatting sheets)
24
+ * Create sheet: <name> ×N(ヘッダ設定まで)
25
+ * Estimate cell budget ×1(`estimateCellBudget` の事前警告 + 予算初期値の算出)
26
+ * Insert rows: <name> ×N(行生成 + 実送信。両者は同じステップの中で起きる)
27
+ * Format sheet: <name> ×M(`updateSheet` を持つシートのみ)
18
28
  * ```
19
29
  *
20
- * ## 行送信戦略
30
+ * 全ステップが厳密に逐次実行されるため、Google Sheets API へのリクエストが並列に
31
+ * 飛ばない(レート制限への配慮)のと同時に、シート作成順・書式適用順も予測可能になる。
21
32
  *
22
- * Phase 2 / 3 はページ・リソースを反復しながら、生成した行を都度
23
- * `sheet.appendRow(...rows)` に渡してストリーミング送信する。`sheet.appendRow()` は
24
- * `@d-zero/google-sheets` 側で 2500 行ごとに自動 flush する(呼び出し元は
25
- * チャンクサイズを意識しない)。バッチ終端で `sheet.flush()` を呼んで残余を排出する。
33
+ * `Insert rows: <name>` の中で Google Sheets へ実際に届くリクエストは、2500 行の
34
+ * チャンクごとに「グリッド拡張 + `updateCells`」(`@d-zero/google-sheets` の
35
+ * `Sheet#addRowData`)だけ——`sheet.appendRow()` はバッファが 2500 行に達した
36
+ * 時点でその場で送るため、行生成(メモリ内処理)とその送信(ネットワーク往復)は
37
+ * 別ステップに分けられない。`run()` 自身が呼ぶ `sheet.flush()` もそのまま生きた
38
+ * 実装で動く。ステップ末尾で TRUNCATED マーカー行(truncation 時のみ)を追記した
39
+ * 後に改めて呼ぶ `flush()` は、バッファが空なら no-op になる契約
40
+ * (`@d-zero/google-sheets` 側)なので無条件に呼んでよい。セル予算のデクリメント
41
+ * (`sheet.sentCount` 実測)はこのステップ自身の戻り値で次のシートへ渡す。
26
42
  *
27
- * 遅延セル(`createCellData(() => ...)` の thunk)を含む行が混ざった場合、
28
- * `appendRow()` はその時点で自動 flush を停止し、明示的な `flush()` 呼び出しまで
29
- * バッファに保留する(順序保証)。Page List の「Internal Referrers」列がこの
30
- * 仕組みに乗っており、バッチ終端の `flush()` で初めて評価される。
43
+ * ## セル予算配分(report OOM 修正・Google Sheets 10M セル上限対策)
31
44
  *
32
- * ## Lanes 進捗表示
45
+ * `Estimate cell budget` ステップで全シートの見積もり行数から超過見込みを警告表示する
46
+ * (`options.onWarn`)。実際の予算執行は `Insert rows: <name>` ステップ間でパイプラインの
47
+ * 搬送値(残セル数)を実測(`sheet.sentCount`)でデクリメントしながら受け渡す —
48
+ * `maxRows = floor(残セル数 / 列数)` を各シート開始時に確定し、優先順位の高い
49
+ * シートの未使用分が後続シートに回る。`run()` が `maxRows` に達すると自身の
50
+ * ループを打ち切り、打ち切られたシートには TRUNCATED マーカー行を追記する。
33
51
  *
34
- * ### ヘッダー: 加重平均による集計
52
+ * ## 進捗表示(行数ベース、% 付き)
35
53
  *
36
- * Phase 2/3 のヘッダーは全子タスク(シート)の進捗 (`pageNum / max`) の
37
- * 平均をパーセント表示する。生成と送信が同一の `appendRow` 呼び出しで一体化
38
- * しているため、ヘッダーは単一の fraction で済む(旧実装にあった生成 0〜50% /
39
- * 送信 50〜100% の二段重み付けは不要になった)。
54
+ * `run()` は `ctx.onProgress(sent, total)` を都度呼び、`total` は
55
+ * `ctx.estimatedTotal`(`estimateRowCount()` の結果)が正——`maxRows`(セル予算の
56
+ * 打ち切り上限)ではない。`formatProgressCount` で `"1,234/5,000 rows (25%)"`
57
+ * 形式に整形し、`dedupeProgressMessage` で同一文字列の連続再描画を間引く
58
+ * (百万行規模のシートで毎行再描画するとターミナルが埋まる)。`sheet.onProgress`
59
+ * (`@d-zero/google-sheets` 側、チャンク単位のコールバック)も同時に配線しており、
60
+ * `appendRow()` の自動 flush や末尾の明示 `flush()` 呼び出し——数秒かかりうる
61
+ * ネットワーク往復——の最中も無音区間にならない。
40
62
  *
41
- * ### レーン: フェーズ遷移に応じた状態表示
63
+ * Google Sheets API のレート制限(429/403/5xx/ECONNRESET)による待機は
64
+ * `sheets.onLog` 経由で検知し、その時点で実行中のステップの行に一時的に上書き表示
65
+ * する(`active`)— 待機中は該当行が数十秒止まって見えるため、原因を明示する。
42
66
  *
43
- * - **アクティブフェーズ内で完了 + 将来フェーズあり**: `c.green("Sent (N rows)")`
44
- * - **アクティブフェーズ内で完了 + 全フェーズ完了**: `c.green("Done (N rows)")`
45
- * - **非アクティブ + 完了済み**: `c.dim` で同じテキスト(色だけ変化、Waiting に戻らない)
46
- * - **非アクティブ + 未着手**: `c.dim("Waiting...")`
67
+ * ## 行送信戦略(lazy cell 全廃)
68
+ *
69
+ * 各シートの `run()` はページ/リソース/違反等を自分でストリームしながら、生成した
70
+ * 行を都度 `sheet.appendRow(...)` に渡す。`sheet.appendRow()` は
71
+ * `@d-zero/google-sheets` 側で 2500 行ごとに自動 flush する。遅延セル
72
+ * (`createCellData(() => ...)` の thunk)はこの契約では一切使わない — 遅延セルが
73
+ * 1つでもバッチに混入すると、明示的な `flush()` を呼ぶまで自動 flush が停止し、
74
+ * バッチ全体が無制限にメモリへ滞留する(`create-cell-data.ts` の docs 参照)。
75
+ * 各列の値は現在のカーソル行 1 件だけから同期的に決定できるため、この停止条件は
76
+ * 構造的に発生しない。
47
77
  * @param params - シート作成に必要なパラメータ
48
78
  */
49
79
  export async function createSheets(params) {
50
- const { sheets, archive, reports, limit, createSheetList, options } = params;
80
+ const { sheets, accessor, reports, createSheetList, options } = params;
51
81
  if (!createSheetList) {
52
82
  sheetLog('createSheetList is empty');
53
83
  return;
54
84
  }
55
- const lanes = options?.lanes;
56
- let lineId = 0;
57
- const sheetIds = new Map();
58
- /**
59
- * Returns a stable numeric lane ID for the given sheet name.
60
- * IDs are assigned sequentially on first access and cached.
61
- * @param name - The sheet display name.
62
- */
63
- function getSheetId(name) {
64
- let id = sheetIds.get(name);
65
- if (id == null) {
66
- id = lineId++;
67
- sheetIds.set(name, id);
68
- }
69
- return id;
70
- }
85
+ const onWarn = options?.onWarn;
71
86
  sheetLog('Initializing %d sheet setting(s)', createSheetList.length);
72
- const settings = await Promise.all(createSheetList.map((createSheet) => createSheet(reports)));
87
+ const settings = await Promise.all(createSheetList.map((createSheet) => createSheet(reports, accessor)));
73
88
  sheetLog('Sheet settings initialized: %O', settings.map((s) => s.name));
74
- // Filter variables (early declaration for phase counting)
75
- const preEachPageRoutineList = settings.filter(hasPropFilter('preEachPage'));
76
- const eachPageRoutineList = settings.filter(hasPropFilter('eachPage'));
77
- const eachResourceRoutineList = settings.filter(hasPropFilter('eachResource'));
78
- const addRowsSettings = settings.filter((s) => s.addRows);
79
- const updateSheetSettings = settings.filter((s) => s.updateSheet);
80
- const needsPageIteration = preEachPageRoutineList.length > 0 || eachPageRoutineList.length > 0;
81
- sheetLog('Routines: preEachPage=%d, eachPage=%d, eachResource=%d', preEachPageRoutineList.length, eachPageRoutineList.length, eachResourceRoutineList.length);
82
- // Phase tracking
83
- const phaseLabels = ['Creating sheets'];
84
- if (needsPageIteration)
85
- phaseLabels.push('Processing pages');
86
- if (eachResourceRoutineList.length > 0)
87
- phaseLabels.push('Processing resources');
88
- if (updateSheetSettings.length > 0)
89
- phaseLabels.push('Formatting sheets');
90
- const totalPhases = phaseLabels.length;
91
- let currentPhase = 0;
92
- /**
93
- * Advances to the next phase and updates the Lanes header line.
94
- * @param detail - Optional custom text; defaults to the phase label.
95
- */
96
- function setPhaseHeader(detail) {
97
- currentPhase++;
98
- const prefix = c.bold(`[${currentPhase}/${totalPhases}]`);
99
- lanes?.header(`${prefix} ${detail ?? phaseLabels[currentPhase - 1]}`);
100
- }
101
- /**
102
- * Updates the Lanes header text without advancing the phase counter.
103
- * @param detail - New header text (e.g. progress percentage).
104
- */
105
- function updatePhaseHeader(detail) {
106
- const prefix = c.bold(`[${currentPhase}/${totalPhases}]`);
107
- lanes?.header(`${prefix} ${detail}`);
108
- }
109
- // Completion tracking
110
- const completionDetails = new Map();
111
- let phase4Complete = false;
112
- /**
113
- * Returns the sequential phase numbers (2, 3, 5) that the named sheet
114
- * participates in. Used to determine whether a sheet has future work
115
- * remaining (for "Sent" vs "Done" labeling).
116
- * @param name - The sheet display name.
117
- */
118
- function getSeqPhases(name) {
119
- const phases = [];
120
- if (eachPageRoutineList.some((s) => s.name === name) ||
121
- preEachPageRoutineList.some((s) => s.name === name))
122
- phases.push(2);
123
- if (eachResourceRoutineList.some((s) => s.name === name))
124
- phases.push(3);
125
- if (updateSheetSettings.some((s) => s.name === name))
126
- phases.push(5);
127
- return phases;
89
+ if (settings.length === 0) {
90
+ sheetLog('No sheets selected');
91
+ return;
128
92
  }
129
- /**
130
- * Marks a sheet as completed for the current phase and updates its
131
- * lane display. Shows "Sent" if future phases remain, "Done" otherwise.
132
- * @param name - The sheet display name.
133
- * @param detail - Optional detail text (e.g. row count).
134
- */
135
- function markDone(name, detail) {
136
- completionDetails.set(name, detail ?? '');
137
- const id = getSheetId(name);
138
- const hasFuture = getSeqPhases(name).some((p) => p > currentPhase);
139
- if (hasFuture) {
140
- lanes?.update(id, c.green(`${name}: Sent${detail ? ` (${detail})` : ''}`));
141
- }
142
- else {
143
- lanes?.update(id, c.green(`${name}: Done${detail ? ` (${detail})` : ''}`));
144
- }
93
+ if (settings.some((s) => s.requiresReadModel)) {
94
+ sheetLog('At least one selected sheet requires the viewer read model — checking');
95
+ await requireViewerReadModel(accessor);
145
96
  }
146
- /**
147
- * Formats a status string for a completed sheet, choosing
148
- * "Sent" or "Done" based on whether future phases remain.
149
- * @param name - The sheet display name.
150
- */
151
- function formatSheetStatus(name) {
152
- const detail = completionDetails.get(name);
153
- const hasFuture = getSeqPhases(name).some((p) => p > currentPhase);
154
- if (hasFuture) {
155
- return `${name}: Sent${detail ? ` (${detail})` : ''}`;
97
+ const updateSheetSettings = settings.filter((s) => s.updateSheet);
98
+ const headerColumnsByName = new Map();
99
+ let estimatedRowsByName = new Map();
100
+ // Rate-limit backoff routes onto whichever TaskList row is currently
101
+ // running: Google's API can pause a request for tens of seconds, and the
102
+ // operator needs to see *why* that row looks stalled instead of assuming
103
+ // it's hung. Overwritten by the row's own next progress update once the
104
+ // wait resolves and the retry succeeds — there is nothing to restore here
105
+ // when `message.waiting` is `false`.
106
+ let active = null;
107
+ let countdownSeq = 0;
108
+ sheets.onLog = (message) => {
109
+ if (!message.waiting || !message.waitTime) {
110
+ return;
156
111
  }
157
- return `${name}: Done${detail ? ` (${detail})` : ''}`;
112
+ const id = countdownSeq++;
113
+ const label = message.message === 'TooManyRequestError'
114
+ ? 'Too Many Requests (429)'
115
+ : message.message === 'UserRateLimitExceededError'
116
+ ? 'Rate Limit Exceeded (403)'
117
+ : message.message === 'ServerError'
118
+ ? `Server Error (${message.code ?? '5xx'})`
119
+ : 'Connection Reset';
120
+ active?.(`${label}: waiting %countdown(${message.waitTime}, rateLimit_${id}, s)%s`);
121
+ };
122
+ // Carries the remaining cell budget (in cells) between steps, threaded
123
+ // through the whole pipeline as a `number` — Phase 1's "Create sheet"
124
+ // steps and Phase 3's "Format" steps don't care about it and pass it
125
+ // through unchanged; only "Estimate cell budget" and Phase 2's "Insert rows"
126
+ // steps actually read/update it. A single consistent carried type avoids
127
+ // the `StepFn<T, R>` mismatches a per-phase type change would cause when
128
+ // reassigning back into one `let pipeline` across the loop below (see
129
+ // `cli`'s CLAUDE.md note on annotating `TaskList` step types explicitly).
130
+ let pipeline = TaskList.from(0);
131
+ // Phase 1: create every selected sheet and set its headers, unconditionally
132
+ // — regardless of whether the cell budget will later let it send any rows.
133
+ for (const setting of settings) {
134
+ pipeline = pipeline.pipe(`Create sheet: ${setting.name}`, async (input, ctx) => {
135
+ active = dedupeProgressMessage((message) => ctx.progress(message));
136
+ active('creating...');
137
+ const sheet = await sheets.create(setting.name);
138
+ active('setting headers...');
139
+ const headers = await setting.createHeaders();
140
+ await sheet.setHeaders(headers);
141
+ headerColumnsByName.set(setting.name, headers.length);
142
+ return input;
143
+ });
158
144
  }
159
- /**
160
- * Dims lane displays for sheets that are not active in the given phase.
161
- * Completed sheets show their status in dim color; unstarted sheets
162
- * show "Waiting...". Phase 4 (addRows) sheets are left bright while
163
- * that phase is still running since it executes in parallel.
164
- * @param seqPhaseNum - The current sequential phase number (2, 3, or 5).
165
- */
166
- function dimInactiveSheets(seqPhaseNum) {
167
- for (const setting of settings) {
168
- const name = setting.name;
169
- const seqPhases = getSeqPhases(name);
170
- // このフェーズでアクティブ → スキップ
171
- if (seqPhases.includes(seqPhaseNum))
172
- continue;
173
- // Phase 4 がまだ実行中のシート → スキップ
174
- const inPhase4 = addRowsSettings.some((s) => s.name === name);
175
- if (inPhase4 && !phase4Complete)
176
- continue;
177
- const id = getSheetId(name);
178
- if (completionDetails.has(name)) {
179
- lanes?.update(id, c.dim(formatSheetStatus(name)));
180
- }
181
- else {
182
- lanes?.update(id, c.dim(`${name}: Waiting...`));
183
- }
145
+ // Advisory warning (informational only — see estimate-cell-budget.ts's
146
+ // docs for why the real enforcement below uses live sentCount instead of
147
+ // these estimates) + the initial cell budget every "Insert rows" step decrements.
148
+ pipeline = pipeline.pipe('Estimate cell budget', async (_input, ctx) => {
149
+ active = dedupeProgressMessage((message) => ctx.progress(message));
150
+ active('counting rows per sheet...');
151
+ const estimates = await Promise.all(settings.map(async (setting) => ({
152
+ name: setting.name,
153
+ columns: headerColumnsByName.get(setting.name) ?? 0,
154
+ estimatedRows: await setting.estimateRowCount(),
155
+ })));
156
+ const allocations = estimateCellBudget(estimates);
157
+ estimatedRowsByName = new Map(allocations.map((a) => [a.name, a.estimatedRows]));
158
+ const anyTruncated = allocations.some((a) => a.truncated);
159
+ if (anyTruncated) {
160
+ const summary = allocations
161
+ .filter((a) => a.truncated)
162
+ .map((a) => ` - ${a.name}: ~${a.estimatedRows} rows estimated, budget allows ~${a.maxRows}`)
163
+ .join('\n');
164
+ onWarn?.(`Warning: this report's estimated size exceeds Google Sheets' 10,000,000-cell ` +
165
+ `document limit. The following sheet(s) will be truncated:\n${summary}\n`);
184
166
  }
185
- }
186
- // Phase 1: Create sheets + set headers
187
- sheetLog('Phase 1: Creating %d sheet(s) and setting headers', settings.length);
188
- setPhaseHeader();
189
- await Promise.all(settings.map(async (setting) => {
190
- const name = setting.name;
191
- const id = getSheetId(name);
192
- sheetLog('[%s] Creating sheet via API', name);
193
- lanes?.update(id, `${name}: Creating sheet%dots%`);
194
- const sheet = await sheets.create(name);
195
- sheetLog('[%s] Setting headers', name);
196
- lanes?.update(id, `${name}: Setting headers%dots%`);
197
- const headers = await setting.createHeaders();
198
- await sheet.setHeaders(headers);
199
- sheetLog('[%s] Headers set (%d columns)', name, headers.length);
200
- lanes?.update(id, `${name}: Ready`);
201
- }));
202
- sheetLog('Phase 1 complete');
203
- await Promise.all([
204
- (async () => {
205
- // Phase 2: Page processing (preEachPage + eachPage unified)
206
- if (needsPageIteration) {
207
- sheetLog('Phase 2: Starting page iteration');
208
- setPhaseHeader();
209
- dimInactiveSheets(2);
210
- sheetLog('Loading pages from archive (limit=%d)', limit);
211
- const sheetProgress = new Map();
212
- for (const setting of preEachPageRoutineList) {
213
- sheetProgress.set(setting.name, 0);
214
- }
215
- for (const setting of eachPageRoutineList) {
216
- sheetProgress.set(setting.name, 0);
217
- }
218
- /**
219
- * Recalculates and displays the weighted-average progress
220
- * across all page-processing sheets for the Phase 2 header.
221
- */
222
- function updatePhase2Header() {
223
- if (sheetProgress.size === 0)
224
- return;
225
- const avg = [...sheetProgress.values()].reduce((a, b) => a + b, 0) / sheetProgress.size;
226
- const pct = Math.round(avg * 100);
227
- updatePhaseHeader(`Processing pages (${pct}%)`);
228
- }
229
- await archive.getPagesWithRefs(limit, async (pages, offset, max) => {
230
- sheetLog('Batch received: %d pages (offset=%d, total=%d)', pages.length, offset, max);
231
- updatePhase2Header();
232
- // preEachPage first
233
- if (preEachPageRoutineList.length > 0) {
234
- sheetLog('Running preEachPage for %d routine(s)', preEachPageRoutineList.length);
235
- await Promise.all(preEachPageRoutineList.map(async (setting) => {
236
- const id = getSheetId(setting.name);
237
- let num = 1;
238
- let prevPage = null;
239
- for (const page of pages) {
240
- const pageNum = offset + num;
241
- lanes?.update(id, `${setting.name}: Pre-processing ${pageNum}/${max}%dots%`);
242
- sheetProgress.set(setting.name, pageNum / max);
243
- updatePhase2Header();
244
- await setting.preEachPage(page, pageNum, max, prevPage);
245
- prevPage = page;
246
- num++;
247
- }
248
- }));
249
- sheetLog('preEachPage complete for batch (offset=%d)', offset);
250
- }
251
- // eachPage second
252
- if (eachPageRoutineList.length > 0) {
253
- sheetLog('Running eachPage for %d routine(s)', eachPageRoutineList.length);
254
- await Promise.all(eachPageRoutineList.map(async (setting) => {
255
- const id = getSheetId(setting.name);
256
- const name = setting.name;
257
- const sheet = await sheets.create(name);
258
- let num = 1;
259
- let prevPage = null;
260
- for (const page of pages) {
261
- const pageNum = offset + num;
262
- lanes?.update(id, `${name}: Processing ${pageNum}/${max} (sent ${sheet.sentCount})%dots%`);
263
- sheetProgress.set(name, pageNum / max);
264
- updatePhase2Header();
265
- const data = await setting.eachPage(page, pageNum, max, prevPage);
266
- prevPage = page;
267
- if (data) {
268
- await sheet.appendRow(...data);
269
- }
270
- num++;
271
- }
272
- await sheet.flush();
273
- sheetLog('[%s] Send complete (offset=%d, %d rows)', name, offset, sheet.sentCount);
274
- sheetProgress.set(name, 1);
275
- updatePhase2Header();
276
- markDone(name, `${sheet.sentCount} rows`);
277
- }));
278
- }
279
- });
280
- sheetLog('Phase 2 complete');
167
+ // Header-row cost for every selected sheet is already spent in
168
+ // Phase 1, unconditionally — subtracted up front, mirroring
169
+ // estimate-cell-budget.ts's own up-front header deduction.
170
+ const headerCost = allocations.reduce((sum, a) => sum + a.columns, 0);
171
+ const remainingCells = Math.max(0, CELL_BUDGET_LIMIT - headerCost);
172
+ active(`${remainingCells.toLocaleString()} cells remaining`);
173
+ return remainingCells;
174
+ });
175
+ // Phase 2: run every sheet's `run()` in priority order (array order),
176
+ // sequentially — each sheet's actual sent-row count decrements the
177
+ // shared remaining-cell budget (carried as this step's input/output)
178
+ // before the next sheet starts, so an earlier sheet sending fewer rows
179
+ // than its allocation lets the remainder roll over to the next sheet.
180
+ //
181
+ // Every actual Sheets API access in this phase is one thing, repeated
182
+ // per 2500-row chunk: grow the grid, then `updateCells` it
183
+ // (`@d-zero/google-sheets`'s `Sheet#addRowData`, reached both by
184
+ // `appendRow()`'s own auto-flush and by the explicit `flush()` call
185
+ // below). Row generation and that network round trip cannot be split
186
+ // into separate steps — `appendRow()` sends as it goes — so each sheet
187
+ // gets a single step here, not a "build" step followed by an "upload"
188
+ // step.
189
+ for (const setting of settings) {
190
+ pipeline = pipeline.pipe(`Insert rows: ${setting.name}`, async (remainingCells, ctx) => {
191
+ active = dedupeProgressMessage((message) => ctx.progress(message));
192
+ const columns = headerColumnsByName.get(setting.name) ?? 0;
193
+ const maxRows = columns > 0 ? Math.max(0, Math.floor(remainingCells / columns)) : 0;
194
+ if (maxRows <= 0) {
195
+ sheetLog('[%s] Skipped: cell budget exhausted', setting.name);
196
+ active('skipped (cell budget exhausted)');
197
+ onWarn?.(`Warning: "${setting.name}" was skipped entirely — the cell budget was already exhausted by higher-priority sheets.\n`);
198
+ return remainingCells;
281
199
  }
282
- // Phase 3: Resource processing
283
- if (eachResourceRoutineList.length > 0) {
284
- sheetLog('Phase 3: Starting resource processing');
285
- setPhaseHeader();
286
- dimInactiveSheets(3);
287
- const rawResources = await archive.getResources();
288
- sheetLog('Resources loaded: %d', rawResources.length);
289
- // Resources は DB の挿入順で返るため、出力前に URL の自然順に
290
- // 並び替える。ただし `skipSortResources: true` を宣言した setting
291
- // は自分で集約してから sort する責任を持つ(dedupe mode のような
292
- // 「1M 件を sort してから 63K に集約」は無駄なので、集約後に
293
- // 小さな集合だけ sort する)。少なくとも 1 つの setting が
294
- // sort を必要とするなら、ループ前に 1 度だけ実行して共有する。
295
- const needsSort = eachResourceRoutineList.some((s) => !s.skipSortResources);
296
- let sortedResources = null;
297
- if (needsSort) {
298
- updatePhaseHeader('Sorting resources by URL');
299
- sortedResources = sortResourcesByUrl(rawResources);
300
- sheetLog('Resources sorted by natural URL order');
301
- }
302
- const resourceProgress = new Map();
303
- for (const setting of eachResourceRoutineList) {
304
- resourceProgress.set(setting.name, 0);
305
- }
306
- /**
307
- * Recalculates and displays the weighted-average progress
308
- * across all resource-processing sheets for the Phase 3 header.
309
- */
310
- function updatePhase3Header() {
311
- if (resourceProgress.size === 0)
312
- return;
313
- const avg = [...resourceProgress.values()].reduce((a, b) => a + b, 0) /
314
- resourceProgress.size;
315
- const pct = Math.round(avg * 100);
316
- updatePhaseHeader(`Processing resources (${pct}%)`);
317
- }
318
- await Promise.all(eachResourceRoutineList.map(async (setting) => {
319
- const id = getSheetId(setting.name);
320
- const name = setting.name;
321
- const sheet = await sheets.create(name);
322
- const resources = setting.skipSortResources || !sortedResources
323
- ? rawResources
324
- : sortedResources;
325
- let i = 0;
326
- for (const resource of resources) {
327
- i++;
328
- lanes?.update(id, `${name}: Processing ${i}/${resources.length} (sent ${sheet.sentCount})%dots%`);
329
- resourceProgress.set(name, i / resources.length);
330
- updatePhase3Header();
331
- const resourceData = await setting.eachResource(resource);
332
- if (resourceData) {
333
- await sheet.appendRow(...resourceData);
334
- }
335
- }
336
- await runFinalizeResources({
337
- setting,
338
- sheet,
339
- lanes,
340
- laneId: id,
341
- sheetName: name,
342
- });
343
- await sheet.flush();
344
- sheetLog('[%s] Resource send complete (%d rows)', name, sheet.sentCount);
345
- resourceProgress.set(name, 1);
346
- updatePhase3Header();
347
- markDone(name, `${sheet.sentCount} rows`);
348
- }));
349
- sheetLog('Phase 3 complete');
200
+ sheetLog('[%s] Running (maxRows=%d)', setting.name, maxRows);
201
+ const sheet = await sheets.create(setting.name);
202
+ // Real per-chunk numbers for whichever flush is in flight —
203
+ // `appendRow()`'s own 2500-row auto-flush during `run()` below,
204
+ // and the explicit `flush()` call after it, can each be a
205
+ // multi-second network round trip with no other progress
206
+ // signal until they resolve.
207
+ sheet.onProgress = (chunkSent, remaining) => {
208
+ active?.(formatProgressCount(chunkSent, chunkSent + remaining, 'rows'));
209
+ };
210
+ const estimatedRows = estimatedRowsByName.get(setting.name) ?? 0;
211
+ let sent = 0;
212
+ active('inserting...');
213
+ await setting.run({
214
+ sheet,
215
+ maxRows,
216
+ estimatedTotal: estimatedRows,
217
+ onProgress: (progressSent, total) => {
218
+ sent = progressSent;
219
+ active?.(formatProgressCount(sent, total, 'rows'));
220
+ },
221
+ });
222
+ // Truncation is decided live, against this sheet's own maxRows as
223
+ // actually computed above — not against Phase 1.5's advisory
224
+ // `truncated` flag, which can go stale: an earlier sheet sending
225
+ // more or fewer rows than *its own* estimate predicted shifts how
226
+ // much budget later sheets really get, so a sheet the advisory
227
+ // pass scored as "not truncated" can still be cut short for real.
228
+ const truncated = sent >= maxRows && estimatedRows > maxRows;
229
+ if (truncated) {
230
+ await sheet.appendRow([
231
+ createCellData({
232
+ value: `TRUNCATED: this sheet was cut off at ${sent} rows to stay under Google Sheets' 10,000,000-cell document limit.`,
233
+ }, defaultCellFormat),
234
+ ]);
350
235
  }
351
- })(),
352
- (async () => {
353
- // Phase 4: Plugin data (addRows)
354
- if (addRowsSettings.length > 0) {
355
- sheetLog('Phase 4: Processing %d addRows routine(s)', addRowsSettings.length);
356
- await Promise.all(addRowsSettings.map(async (setting) => {
357
- const name = setting.name;
358
- const id = getSheetId(name);
359
- sheetLog('[%s] Creating plugin data', name);
360
- lanes?.update(id, `${name}: Writing plugin data%dots%`);
361
- const data = await setting.addRows();
362
- if (!data) {
363
- sheetLog('[%s] Plugin data is empty', name);
364
- return;
365
- }
366
- const sheet = await sheets.create(name);
367
- sheetLog('[%s] Sending %d rows', name, data.length);
368
- lanes?.update(id, `${name}: Sending ${data.length} rows%dots%`);
369
- await sheet.appendRow(...data);
370
- await sheet.flush();
371
- sheetLog('[%s] Plugin data send complete', name);
372
- if (!completionDetails.has(name)) {
373
- markDone(name, `${data.length} rows`);
374
- }
375
- }));
376
- phase4Complete = true;
377
- sheetLog('Phase 4 complete');
236
+ // `run()` already flushes its own tail per the
237
+ // `CreateSheetSetting.run()` contract — this call only drains
238
+ // the TRUNCATED marker row appended above, if any. `flush()`
239
+ // is a no-op on an empty buffer, so calling it unconditionally
240
+ // here is safe either way.
241
+ await sheet.flush();
242
+ if (truncated) {
243
+ onWarn?.(`Warning: "${setting.name}" was truncated at ${sent} rows (cell budget).\n`);
378
244
  }
379
- })(),
380
- ]);
381
- // Phase 5: Formatting
382
- if (updateSheetSettings.length > 0) {
383
- sheetLog('Phase 5: Formatting %d sheet(s)', updateSheetSettings.length);
384
- setPhaseHeader();
385
- dimInactiveSheets(5);
386
- await Promise.all(updateSheetSettings.map(async (setting) => {
387
- const name = setting.name;
388
- const id = getSheetId(name);
389
- sheetLog('[%s] Applying formatting', name);
390
- lanes?.update(id, `${name}: Applying formatting%dots%`);
391
- const sheet = await sheets.create(name);
245
+ sheetLog('[%s] Done (%d rows sent)', setting.name, sheet.sentCount);
246
+ return Math.max(0, remainingCells - sheet.sentCount * columns);
247
+ });
248
+ }
249
+ // Phase 3: formatting.
250
+ for (const setting of updateSheetSettings) {
251
+ pipeline = pipeline.pipe(`Format sheet: ${setting.name}`, async (input, ctx) => {
252
+ active = dedupeProgressMessage((message) => ctx.progress(message));
253
+ active('applying formatting...');
254
+ const sheet = await sheets.create(setting.name);
392
255
  await setting.updateSheet(sheet);
393
256
  await sheet.overwriteHeaderFormat();
394
- sheetLog('[%s] Formatting complete', name);
395
- markDone(name);
396
- }));
397
- sheetLog('Phase 5 complete');
257
+ return input;
258
+ });
398
259
  }
260
+ await pipeline.run({
261
+ stream: options?.silent ? NULL_STREAM : (options?.stream ?? process.stderr),
262
+ verbose: options?.verbose ?? !process.stdout.isTTY,
263
+ keepElapsed: true,
264
+ });
399
265
  }