@nitpicker/report-google-sheets 0.18.1 → 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.
- package/lib/data/create-discrepancies.d.ts +10 -12
- package/lib/data/create-discrepancies.js +27 -31
- package/lib/data/create-image-list.d.ts +26 -6
- package/lib/data/create-image-list.js +65 -39
- package/lib/data/create-links.d.ts +18 -1
- package/lib/data/create-links.js +91 -55
- package/lib/data/create-page-list.d.ts +24 -24
- package/lib/data/create-page-list.js +178 -224
- package/lib/data/create-referrers-relational-table.d.ts +13 -7
- package/lib/data/create-referrers-relational-table.js +57 -47
- package/lib/data/create-resources-relational-table.d.ts +7 -0
- package/lib/data/create-resources-relational-table.js +41 -33
- package/lib/data/create-resources.d.ts +24 -124
- package/lib/data/create-resources.js +100 -264
- package/lib/data/create-violations.d.ts +7 -6
- package/lib/data/create-violations.js +34 -19
- package/lib/dedupe-progress-message.d.ts +17 -0
- package/lib/dedupe-progress-message.js +26 -0
- package/lib/format-progress-count.d.ts +19 -0
- package/lib/format-progress-count.js +22 -0
- package/lib/open-report-archive.d.ts +54 -0
- package/lib/open-report-archive.js +76 -0
- package/lib/report.d.ts +23 -10
- package/lib/report.js +146 -149
- package/lib/reports/get-plugin-reports.d.ts +14 -6
- package/lib/reports/get-plugin-reports.js +14 -34
- package/lib/sheets/create-sheets.d.ts +66 -36
- package/lib/sheets/create-sheets.js +228 -362
- package/lib/sheets/estimate-cell-budget.d.ts +55 -0
- package/lib/sheets/estimate-cell-budget.js +56 -0
- package/lib/sheets/types.d.ts +111 -91
- package/lib/test-helpers/assert-no-lazy-cells.d.ts +16 -0
- package/lib/test-helpers/assert-no-lazy-cells.js +23 -0
- package/lib/test-helpers/cell-inspection.d.ts +20 -0
- package/lib/test-helpers/cell-inspection.js +21 -0
- package/lib/test-helpers/create-mock-sheet.d.ts +30 -0
- package/lib/test-helpers/create-mock-sheet.js +71 -0
- package/lib/test-helpers/one-chunk.d.ts +8 -0
- package/lib/test-helpers/one-chunk.js +11 -0
- package/lib/utils/join-urls-for-note.d.ts +27 -0
- package/lib/utils/join-urls-for-note.js +48 -0
- package/lib/utils/truncate-note-text.d.ts +15 -0
- package/lib/utils/truncate-note-text.js +23 -0
- package/package.json +13 -12
- package/lib/archive.d.ts +0 -20
- package/lib/archive.js +0 -34
- package/lib/sheets/run-finalize-resources.d.ts +0 -40
- package/lib/sheets/run-finalize-resources.js +0 -44
- package/lib/types.d.ts +0 -11
- package/lib/types.js +0 -1
- package/lib/utils/canonicalize-url.d.ts +0 -53
- package/lib/utils/canonicalize-url.js +0 -105
- package/lib/utils/has-prop-filter.d.ts +0 -18
- package/lib/utils/has-prop-filter.js +0 -19
- package/lib/utils/sort-resources-by-url.d.ts +0 -69
- package/lib/utils/sort-resources-by-url.js +0 -223
|
@@ -1,399 +1,265 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { TaskList } from '@d-zero/dealer';
|
|
2
|
+
import { requireViewerReadModel } from '@nitpicker/query';
|
|
2
3
|
import { sheetLog } from '../debug.js';
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
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
|
-
*
|
|
20
|
+
* `@d-zero/dealer` の `TaskList`(逐次パイプライン)で、選択されたシートの数だけ
|
|
21
|
+
* 動的にステップを積む — 固定行数ではなくユーザー選択に応じて可変:
|
|
12
22
|
*
|
|
13
23
|
* ```
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
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
|
-
*
|
|
23
|
-
* `
|
|
24
|
-
*
|
|
25
|
-
*
|
|
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
|
-
*
|
|
28
|
-
* `appendRow()` はその時点で自動 flush を停止し、明示的な `flush()` 呼び出しまで
|
|
29
|
-
* バッファに保留する(順序保証)。Page List の「Internal Referrers」列がこの
|
|
30
|
-
* 仕組みに乗っており、バッチ終端の `flush()` で初めて評価される。
|
|
43
|
+
* ## セル予算配分(report OOM 修正・Google Sheets 10M セル上限対策)
|
|
31
44
|
*
|
|
32
|
-
*
|
|
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
|
-
*
|
|
37
|
-
*
|
|
38
|
-
*
|
|
39
|
-
*
|
|
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
|
-
*
|
|
44
|
-
*
|
|
45
|
-
*
|
|
46
|
-
*
|
|
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,
|
|
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
|
|
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
|
-
|
|
75
|
-
|
|
76
|
-
|
|
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
|
-
|
|
131
|
-
|
|
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
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
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
|
-
|
|
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
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
const
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
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
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
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
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
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
|
-
|
|
353
|
-
//
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
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
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
const
|
|
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
|
-
|
|
395
|
-
|
|
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
|
}
|