@a1-x-tech/mcp-google-sheets 0.1.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/LICENSE +21 -0
- package/README.md +307 -0
- package/README.ru.md +307 -0
- package/dist/client.js +736 -0
- package/dist/config.js +83 -0
- package/dist/index.js +128 -0
- package/dist/telemetry.js +120 -0
- package/dist/tools/format.js +176 -0
- package/dist/tools/objects.js +127 -0
- package/dist/tools/raw.js +30 -0
- package/dist/tools/rules.js +175 -0
- package/dist/tools/sharing.js +86 -0
- package/dist/tools/sheets.js +79 -0
- package/dist/tools/spreadsheets.js +92 -0
- package/dist/tools/util.js +102 -0
- package/dist/tools/values.js +146 -0
- package/dist/types.js +46 -0
- package/package.json +63 -0
- package/test/dist-smoke.test.js +185 -0
package/dist/client.js
ADDED
|
@@ -0,0 +1,736 @@
|
|
|
1
|
+
import { GoogleSheetsError } from "./types.js";
|
|
2
|
+
import { CredentialsError } from "./config.js";
|
|
3
|
+
/** Google's OAuth2 token endpoint — refresh tokens are exchanged here. */
|
|
4
|
+
const TOKEN_URL = "https://oauth2.googleapis.com/token";
|
|
5
|
+
/**
|
|
6
|
+
* Drive API v3 root. An internal dependency only: spreadsheet search and
|
|
7
|
+
* permission management have no Sheets API equivalent. raw_request stays
|
|
8
|
+
* pinned to the Sheets origin and can never reach it.
|
|
9
|
+
*/
|
|
10
|
+
export const DRIVE_BASE = "https://www.googleapis.com/";
|
|
11
|
+
const SPREADSHEET_MIME = "application/vnd.google-apps.spreadsheet";
|
|
12
|
+
/**
|
|
13
|
+
* Parses "#RRGGBB" into the API's { red, green, blue } floats (0..1, rounded
|
|
14
|
+
* to 3 decimals so request bodies stay stable and diffable in tests).
|
|
15
|
+
*/
|
|
16
|
+
export function hexToColor(hex) {
|
|
17
|
+
const match = /^#([0-9a-fA-F]{6})$/.exec(hex);
|
|
18
|
+
if (!match)
|
|
19
|
+
throw new Error(`Invalid color ${JSON.stringify(hex)} — expected "#RRGGBB", e.g. "#1A73E8".`);
|
|
20
|
+
const n = parseInt(match[1], 16);
|
|
21
|
+
const channel = (v) => Math.round((v / 255) * 1000) / 1000;
|
|
22
|
+
return { red: channel((n >> 16) & 0xff), green: channel((n >> 8) & 0xff), blue: channel(n & 0xff) };
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Builds a CellFormat plus the matching fields mask from the normalized
|
|
26
|
+
* format_cells vocabulary. Pure wire mapping — only the provided fields make it
|
|
27
|
+
* into the mask, so untouched formatting survives.
|
|
28
|
+
*/
|
|
29
|
+
export function buildCellFormat(p) {
|
|
30
|
+
if (p.numberFormatPattern !== undefined && p.numberFormatType === undefined) {
|
|
31
|
+
throw new Error("number_format_pattern requires number_format_type.");
|
|
32
|
+
}
|
|
33
|
+
const textFormat = compact({
|
|
34
|
+
bold: p.bold,
|
|
35
|
+
italic: p.italic,
|
|
36
|
+
strikethrough: p.strikethrough,
|
|
37
|
+
underline: p.underline,
|
|
38
|
+
fontSize: p.fontSize,
|
|
39
|
+
fontFamily: p.fontFamily,
|
|
40
|
+
foregroundColor: p.textColor === undefined ? undefined : hexToColor(p.textColor),
|
|
41
|
+
});
|
|
42
|
+
const numberFormat = p.numberFormatType === undefined ? undefined : compact({ type: p.numberFormatType, pattern: p.numberFormatPattern });
|
|
43
|
+
const format = compact({
|
|
44
|
+
backgroundColor: p.backgroundColor === undefined ? undefined : hexToColor(p.backgroundColor),
|
|
45
|
+
textFormat: Object.keys(textFormat).length > 0 ? textFormat : undefined,
|
|
46
|
+
horizontalAlignment: p.horizontalAlignment,
|
|
47
|
+
verticalAlignment: p.verticalAlignment,
|
|
48
|
+
wrapStrategy: p.wrapStrategy,
|
|
49
|
+
numberFormat,
|
|
50
|
+
});
|
|
51
|
+
const fields = [];
|
|
52
|
+
if (format.backgroundColor !== undefined)
|
|
53
|
+
fields.push("userEnteredFormat.backgroundColor");
|
|
54
|
+
for (const key of Object.keys(textFormat))
|
|
55
|
+
fields.push(`userEnteredFormat.textFormat.${key}`);
|
|
56
|
+
if (p.horizontalAlignment !== undefined)
|
|
57
|
+
fields.push("userEnteredFormat.horizontalAlignment");
|
|
58
|
+
if (p.verticalAlignment !== undefined)
|
|
59
|
+
fields.push("userEnteredFormat.verticalAlignment");
|
|
60
|
+
if (p.wrapStrategy !== undefined)
|
|
61
|
+
fields.push("userEnteredFormat.wrapStrategy");
|
|
62
|
+
if (numberFormat !== undefined)
|
|
63
|
+
fields.push("userEnteredFormat.numberFormat");
|
|
64
|
+
if (fields.length === 0)
|
|
65
|
+
throw new Error("At least one formatting field is required.");
|
|
66
|
+
return { format, fields: fields.join(",") };
|
|
67
|
+
}
|
|
68
|
+
const sourceRange = (range) => ({ sourceRange: { sources: [gridRange(range)] } });
|
|
69
|
+
/**
|
|
70
|
+
* Builds a ChartSpec from the normalized chart vocabulary, or passes a raw
|
|
71
|
+
* `spec` through untouched. PIE maps to pieChart (one domain + one series);
|
|
72
|
+
* every other type maps to basicChart with LEFT_AXIS series.
|
|
73
|
+
*/
|
|
74
|
+
export function buildChartSpec(p) {
|
|
75
|
+
if (p.spec)
|
|
76
|
+
return p.spec;
|
|
77
|
+
if (!p.chartType)
|
|
78
|
+
throw new Error("chart_type is required (or pass a raw spec).");
|
|
79
|
+
if (p.chartType === "PIE") {
|
|
80
|
+
if (!p.domainRange || !p.seriesRanges || p.seriesRanges.length !== 1) {
|
|
81
|
+
throw new Error("A PIE chart needs domain_range (labels) and exactly one series_ranges entry (values).");
|
|
82
|
+
}
|
|
83
|
+
return compact({
|
|
84
|
+
title: p.title,
|
|
85
|
+
pieChart: compact({
|
|
86
|
+
legendPosition: p.legendPosition,
|
|
87
|
+
domain: sourceRange(p.domainRange),
|
|
88
|
+
series: sourceRange(p.seriesRanges[0]),
|
|
89
|
+
}),
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
if (!p.seriesRanges || p.seriesRanges.length === 0) {
|
|
93
|
+
throw new Error("series_ranges is required — one range per data series (or pass a raw spec).");
|
|
94
|
+
}
|
|
95
|
+
return compact({
|
|
96
|
+
title: p.title,
|
|
97
|
+
basicChart: compact({
|
|
98
|
+
chartType: p.chartType,
|
|
99
|
+
legendPosition: p.legendPosition,
|
|
100
|
+
headerCount: p.headerCount ?? 1,
|
|
101
|
+
domains: p.domainRange ? [{ domain: sourceRange(p.domainRange) }] : undefined,
|
|
102
|
+
series: p.seriesRanges.map((range) => ({ series: sourceRange(range), targetAxis: "LEFT_AXIS" })),
|
|
103
|
+
}),
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
/** Builds a booleanRule conditional-format rule from the normalized vocabulary. */
|
|
107
|
+
export function buildConditionalRule(p) {
|
|
108
|
+
if (p.ranges.length === 0)
|
|
109
|
+
throw new Error("At least one range is required.");
|
|
110
|
+
const textFormat = compact({
|
|
111
|
+
bold: p.bold,
|
|
112
|
+
italic: p.italic,
|
|
113
|
+
foregroundColor: p.textColor === undefined ? undefined : hexToColor(p.textColor),
|
|
114
|
+
});
|
|
115
|
+
const format = compact({
|
|
116
|
+
backgroundColor: p.backgroundColor === undefined ? undefined : hexToColor(p.backgroundColor),
|
|
117
|
+
textFormat: Object.keys(textFormat).length > 0 ? textFormat : undefined,
|
|
118
|
+
});
|
|
119
|
+
if (Object.keys(format).length === 0) {
|
|
120
|
+
throw new Error("At least one of background_color, text_color, bold or italic is required.");
|
|
121
|
+
}
|
|
122
|
+
return {
|
|
123
|
+
ranges: p.ranges.map(gridRange),
|
|
124
|
+
booleanRule: {
|
|
125
|
+
condition: buildCondition(p.conditionType, p.conditionValues),
|
|
126
|
+
format,
|
|
127
|
+
},
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
/** Maps a condition type + values to the API's BooleanCondition. */
|
|
131
|
+
function buildCondition(type, values) {
|
|
132
|
+
return compact({
|
|
133
|
+
type,
|
|
134
|
+
values: values && values.length > 0 ? values.map((userEnteredValue) => ({ userEnteredValue })) : undefined,
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
/** Strips undefined index fields so unbounded edges are truly omitted on the wire. */
|
|
138
|
+
function gridRange(range) {
|
|
139
|
+
return compact({
|
|
140
|
+
sheetId: range.sheetId,
|
|
141
|
+
startRowIndex: range.startRowIndex,
|
|
142
|
+
endRowIndex: range.endRowIndex,
|
|
143
|
+
startColumnIndex: range.startColumnIndex,
|
|
144
|
+
endColumnIndex: range.endColumnIndex,
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
export class GoogleSheetsClient {
|
|
148
|
+
config;
|
|
149
|
+
base;
|
|
150
|
+
timeoutMs;
|
|
151
|
+
maxRetries;
|
|
152
|
+
retryBaseMs;
|
|
153
|
+
/** Cached access token from the refresh flow, with its expiry. */
|
|
154
|
+
cachedToken;
|
|
155
|
+
/** In-flight refresh, deduping concurrent token requests. */
|
|
156
|
+
refreshInFlight;
|
|
157
|
+
constructor(config) {
|
|
158
|
+
this.config = config;
|
|
159
|
+
this.base = config.apiBase.endsWith("/") ? config.apiBase : config.apiBase + "/";
|
|
160
|
+
this.timeoutMs = config.timeoutMs ?? 60_000;
|
|
161
|
+
this.maxRetries = config.maxRetries ?? 3;
|
|
162
|
+
this.retryBaseMs = config.retryBaseMs ?? 500;
|
|
163
|
+
}
|
|
164
|
+
canRefresh() {
|
|
165
|
+
return Boolean(this.config.refreshToken && this.config.clientId && this.config.clientSecret);
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Returns a valid Bearer token. With the refresh triple configured, mints an
|
|
169
|
+
* access token from the refresh token and caches it until shortly before it
|
|
170
|
+
* expires (concurrent callers share one in-flight refresh); otherwise the
|
|
171
|
+
* static GOOGLE_SHEETS_ACCESS_TOKEN is used as-is. With neither configured,
|
|
172
|
+
* throws {@link CredentialsError} BEFORE any fetch — a missing setup must
|
|
173
|
+
* never enter the retry/backoff loop or trigger the 401 re-mint, because no
|
|
174
|
+
* amount of retrying mints credentials.
|
|
175
|
+
*/
|
|
176
|
+
async accessToken(forceRefresh = false) {
|
|
177
|
+
if (!this.canRefresh()) {
|
|
178
|
+
if (!this.config.accessToken)
|
|
179
|
+
throw new CredentialsError();
|
|
180
|
+
return this.config.accessToken;
|
|
181
|
+
}
|
|
182
|
+
if (!forceRefresh && this.cachedToken && Date.now() < this.cachedToken.expiresAt) {
|
|
183
|
+
return this.cachedToken.value;
|
|
184
|
+
}
|
|
185
|
+
if (!this.refreshInFlight) {
|
|
186
|
+
this.refreshInFlight = this.refreshAccessToken().finally(() => {
|
|
187
|
+
this.refreshInFlight = undefined;
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
return this.refreshInFlight;
|
|
191
|
+
}
|
|
192
|
+
/** Exchanges the refresh token for a fresh access token at Google's token endpoint. */
|
|
193
|
+
async refreshAccessToken() {
|
|
194
|
+
const body = new URLSearchParams({
|
|
195
|
+
client_id: this.config.clientId,
|
|
196
|
+
client_secret: this.config.clientSecret,
|
|
197
|
+
refresh_token: this.config.refreshToken,
|
|
198
|
+
grant_type: "refresh_token",
|
|
199
|
+
}).toString();
|
|
200
|
+
const { res, text } = await this.fetchWithTimeout(TOKEN_URL, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body }, "oauth2 token refresh");
|
|
201
|
+
let data;
|
|
202
|
+
try {
|
|
203
|
+
data = JSON.parse(text);
|
|
204
|
+
}
|
|
205
|
+
catch {
|
|
206
|
+
data = text;
|
|
207
|
+
}
|
|
208
|
+
if (!res.ok)
|
|
209
|
+
throw new GoogleSheetsError(res.status, data);
|
|
210
|
+
const token = data.access_token;
|
|
211
|
+
if (typeof token !== "string" || !token) {
|
|
212
|
+
throw new Error("OAuth2 token endpoint returned no access_token.");
|
|
213
|
+
}
|
|
214
|
+
const expiresIn = Number(data.expires_in);
|
|
215
|
+
const ttl = Number.isFinite(expiresIn) && expiresIn > 0 ? expiresIn : 3600;
|
|
216
|
+
// Refresh 60s ahead of the real expiry so requests never race a dying token.
|
|
217
|
+
this.cachedToken = { value: token, expiresAt: Date.now() + Math.max(ttl - 60, 30) * 1000 };
|
|
218
|
+
return token;
|
|
219
|
+
}
|
|
220
|
+
/** Verifies the OAuth credentials by minting a fresh access token (refresh flow only). */
|
|
221
|
+
async authCheck() {
|
|
222
|
+
if (!this.canRefresh()) {
|
|
223
|
+
throw new Error("authCheck needs the refresh flow (GOOGLE_SHEETS_CLIENT_ID / _CLIENT_SECRET / _REFRESH_TOKEN); with a static GOOGLE_SHEETS_ACCESS_TOKEN fetch a spreadsheet instead.");
|
|
224
|
+
}
|
|
225
|
+
await this.accessToken(true);
|
|
226
|
+
return { ok: true, auth: "refresh_token" };
|
|
227
|
+
}
|
|
228
|
+
/** Backoff before a retry: honors Retry-After when present, else exponential (capped at 30s). */
|
|
229
|
+
backoffMs(attempt, res) {
|
|
230
|
+
const retryAfter = res ? Number(res.headers.get("Retry-After")) : NaN;
|
|
231
|
+
if (Number.isFinite(retryAfter) && retryAfter > 0)
|
|
232
|
+
return Math.min(retryAfter, 30) * 1000;
|
|
233
|
+
return Math.min(this.retryBaseMs * 2 ** attempt, 30_000);
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* fetch with an AbortController timeout. Reads the response body inside the
|
|
237
|
+
* guarded zone so the timeout also covers a slow or drip-feeding body, not
|
|
238
|
+
* just the initial headers, and returns the text alongside the response.
|
|
239
|
+
*/
|
|
240
|
+
async fetchWithTimeout(url, init, label) {
|
|
241
|
+
const controller = new AbortController();
|
|
242
|
+
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
243
|
+
try {
|
|
244
|
+
const res = await fetch(url, { ...init, signal: controller.signal });
|
|
245
|
+
const text = await res.text();
|
|
246
|
+
return { res, text };
|
|
247
|
+
}
|
|
248
|
+
catch (err) {
|
|
249
|
+
if (err instanceof Error && err.name === "AbortError") {
|
|
250
|
+
throw new Error(`Request to "${label}" timed out after ${this.timeoutMs}ms`);
|
|
251
|
+
}
|
|
252
|
+
throw err;
|
|
253
|
+
}
|
|
254
|
+
finally {
|
|
255
|
+
clearTimeout(timer);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* Low-level request against one of the two API roots. Auth is a Bearer token
|
|
260
|
+
* (refreshed transparently; a 401 forces one re-mint + retry). 429 is always
|
|
261
|
+
* retried with backoff; 5xx and network errors/timeouts are retried only for
|
|
262
|
+
* GET — the Sheets API has real writes, and replaying one after an ambiguous
|
|
263
|
+
* failure could apply it twice (append duplicates rows, batchUpdate re-adds
|
|
264
|
+
* sheets/rules). Any other non-2xx throws a {@link GoogleSheetsError}.
|
|
265
|
+
*/
|
|
266
|
+
async httpRequest(base, method, path, body, query) {
|
|
267
|
+
// Guard method !== "GET" keeps undici from crashing on a GET-with-body.
|
|
268
|
+
const hasBody = body !== undefined && method !== "GET";
|
|
269
|
+
// Resolve the path against the API base, then reject anything that escaped
|
|
270
|
+
// to a foreign origin (an absolute "https://evil/x" or a "\\evil/x" slipped
|
|
271
|
+
// through raw_request) so the Bearer token can never leak to another host.
|
|
272
|
+
const url = new URL(path.replace(/^\//, ""), base);
|
|
273
|
+
if (url.origin !== new URL(base).origin) {
|
|
274
|
+
throw new Error(`the path must be a relative API path (resolved to foreign origin ${url.origin})`);
|
|
275
|
+
}
|
|
276
|
+
if (query) {
|
|
277
|
+
for (const [key, value] of Object.entries(query)) {
|
|
278
|
+
if (value === undefined)
|
|
279
|
+
continue;
|
|
280
|
+
if (Array.isArray(value))
|
|
281
|
+
for (const item of value)
|
|
282
|
+
url.searchParams.append(key, item);
|
|
283
|
+
else
|
|
284
|
+
url.searchParams.set(key, String(value));
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
const target = url.toString();
|
|
288
|
+
// Writes must not be replayed on ambiguous failures (see the retry gate below).
|
|
289
|
+
const idempotent = method === "GET";
|
|
290
|
+
let refreshedOn401 = false;
|
|
291
|
+
for (let attempt = 0;; attempt++) {
|
|
292
|
+
const token = await this.accessToken();
|
|
293
|
+
const headers = { Authorization: `Bearer ${token}` };
|
|
294
|
+
if (hasBody)
|
|
295
|
+
headers["Content-Type"] = "application/json";
|
|
296
|
+
let res;
|
|
297
|
+
let text;
|
|
298
|
+
try {
|
|
299
|
+
({ res, text } = await this.fetchWithTimeout(target, { method, headers, body: hasBody ? JSON.stringify(body) : undefined }, path));
|
|
300
|
+
}
|
|
301
|
+
catch (err) {
|
|
302
|
+
// Network error or timeout: the request may or may not have reached the
|
|
303
|
+
// API, so only reads are retried; writes rethrow immediately.
|
|
304
|
+
if (idempotent && attempt < this.maxRetries) {
|
|
305
|
+
await delay(this.backoffMs(attempt));
|
|
306
|
+
continue;
|
|
307
|
+
}
|
|
308
|
+
throw err;
|
|
309
|
+
}
|
|
310
|
+
// An expired/revoked access token: re-mint once and replay. The request
|
|
311
|
+
// never executed, so this is safe for writes too.
|
|
312
|
+
if (res.status === 401 && this.canRefresh() && !refreshedOn401) {
|
|
313
|
+
refreshedOn401 = true;
|
|
314
|
+
await this.accessToken(true);
|
|
315
|
+
continue;
|
|
316
|
+
}
|
|
317
|
+
// 429 means the request was rejected before executing — safe to retry for
|
|
318
|
+
// any method. 5xx is ambiguous (the write may have committed), so it is
|
|
319
|
+
// gated to idempotent requests.
|
|
320
|
+
const transient = res.status === 429 || (idempotent && res.status >= 500 && res.status < 600);
|
|
321
|
+
if (transient && attempt < this.maxRetries) {
|
|
322
|
+
await delay(this.backoffMs(attempt, res));
|
|
323
|
+
continue;
|
|
324
|
+
}
|
|
325
|
+
let data = undefined;
|
|
326
|
+
if (text) {
|
|
327
|
+
try {
|
|
328
|
+
data = JSON.parse(text);
|
|
329
|
+
}
|
|
330
|
+
catch {
|
|
331
|
+
data = text;
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
if (!res.ok)
|
|
335
|
+
throw new GoogleSheetsError(res.status, data);
|
|
336
|
+
return data;
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
/** Request against the Sheets API root (raw_request and every typed Sheets method). */
|
|
340
|
+
async request(method, path, body, query) {
|
|
341
|
+
return this.httpRequest(this.base, method, path, body, query);
|
|
342
|
+
}
|
|
343
|
+
/** Request against the Drive API root — internal (search, permissions, smoke cleanup). */
|
|
344
|
+
async driveRequest(method, path, body, query) {
|
|
345
|
+
return this.httpRequest(DRIVE_BASE, method, path, body, query);
|
|
346
|
+
}
|
|
347
|
+
// ---- Spreadsheets ----
|
|
348
|
+
/** Creates a spreadsheet, optionally with named sheets (otherwise one default "Sheet1"). */
|
|
349
|
+
async createSpreadsheet(p) {
|
|
350
|
+
return this.request("POST", "v4/spreadsheets", compact({
|
|
351
|
+
properties: compact({ title: p.title, locale: p.locale, timeZone: p.timeZone }),
|
|
352
|
+
sheets: p.sheetTitles?.length ? p.sheetTitles.map((title) => ({ properties: { title } })) : undefined,
|
|
353
|
+
}));
|
|
354
|
+
}
|
|
355
|
+
/** Spreadsheet metadata (and optionally cell data for the given A1 ranges). */
|
|
356
|
+
async getSpreadsheet(p) {
|
|
357
|
+
return this.request("GET", `v4/spreadsheets/${encodeURIComponent(p.spreadsheetId)}`, undefined, compact({ ranges: p.ranges, includeGridData: p.includeGridData, fields: p.fields }));
|
|
358
|
+
}
|
|
359
|
+
/** Finds spreadsheets by name via the Drive API (internal dependency; needs a Drive scope). */
|
|
360
|
+
async searchSpreadsheets(p) {
|
|
361
|
+
const terms = [`mimeType='${SPREADSHEET_MIME}'`, "trashed=false"];
|
|
362
|
+
if (p.nameContains) {
|
|
363
|
+
// Drive query strings escape backslashes and single quotes.
|
|
364
|
+
const escaped = p.nameContains.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
|
|
365
|
+
terms.push(`name contains '${escaped}'`);
|
|
366
|
+
}
|
|
367
|
+
return this.driveRequest("GET", "drive/v3/files", undefined, {
|
|
368
|
+
q: terms.join(" and "),
|
|
369
|
+
pageSize: p.pageSize,
|
|
370
|
+
pageToken: p.pageToken,
|
|
371
|
+
orderBy: p.orderBy ?? "modifiedTime desc",
|
|
372
|
+
fields: "nextPageToken,files(id,name,createdTime,modifiedTime,owners(emailAddress,displayName),webViewLink)",
|
|
373
|
+
supportsAllDrives: true,
|
|
374
|
+
includeItemsFromAllDrives: true,
|
|
375
|
+
corpora: "allDrives",
|
|
376
|
+
});
|
|
377
|
+
}
|
|
378
|
+
/** Low-level batchUpdate — the write channel for every structural change. */
|
|
379
|
+
async batchUpdate(spreadsheetId, requests, opts = {}) {
|
|
380
|
+
return this.request("POST", `v4/spreadsheets/${encodeURIComponent(spreadsheetId)}:batchUpdate`, compact({
|
|
381
|
+
requests,
|
|
382
|
+
includeSpreadsheetInResponse: opts.includeSpreadsheetInResponse,
|
|
383
|
+
}));
|
|
384
|
+
}
|
|
385
|
+
// ---- Values ----
|
|
386
|
+
/** Reads one or more A1 ranges in a single batchGet call. */
|
|
387
|
+
async getValues(p) {
|
|
388
|
+
return this.request("GET", `v4/spreadsheets/${encodeURIComponent(p.spreadsheetId)}/values:batchGet`, undefined, compact({
|
|
389
|
+
ranges: p.ranges,
|
|
390
|
+
valueRenderOption: p.valueRenderOption,
|
|
391
|
+
majorDimension: p.majorDimension,
|
|
392
|
+
dateTimeRenderOption: p.dateTimeRenderOption,
|
|
393
|
+
}));
|
|
394
|
+
}
|
|
395
|
+
/** Overwrites one A1 range with a 2-D values matrix. */
|
|
396
|
+
async updateValues(p) {
|
|
397
|
+
return this.request("PUT", `v4/spreadsheets/${encodeURIComponent(p.spreadsheetId)}/values/${encodeURIComponent(p.range)}`, { values: p.values }, compact({
|
|
398
|
+
valueInputOption: p.valueInputOption ?? "USER_ENTERED",
|
|
399
|
+
includeValuesInResponse: p.includeValuesInResponse,
|
|
400
|
+
}));
|
|
401
|
+
}
|
|
402
|
+
/** Overwrites several A1 ranges in one batchUpdate call (counts as one write against the quota). */
|
|
403
|
+
async batchUpdateValues(p) {
|
|
404
|
+
return this.request("POST", `v4/spreadsheets/${encodeURIComponent(p.spreadsheetId)}/values:batchUpdate`, {
|
|
405
|
+
valueInputOption: p.valueInputOption ?? "USER_ENTERED",
|
|
406
|
+
data: p.data,
|
|
407
|
+
});
|
|
408
|
+
}
|
|
409
|
+
/** Appends rows after the last row of the table that contains the range. */
|
|
410
|
+
async appendValues(p) {
|
|
411
|
+
return this.request("POST", `v4/spreadsheets/${encodeURIComponent(p.spreadsheetId)}/values/${encodeURIComponent(p.range)}:append`, { values: p.values }, compact({
|
|
412
|
+
valueInputOption: p.valueInputOption ?? "USER_ENTERED",
|
|
413
|
+
insertDataOption: p.insertDataOption,
|
|
414
|
+
}));
|
|
415
|
+
}
|
|
416
|
+
/** Clears the values of one or more A1 ranges (formatting, notes and validation survive). */
|
|
417
|
+
async clearValues(p) {
|
|
418
|
+
return this.request("POST", `v4/spreadsheets/${encodeURIComponent(p.spreadsheetId)}/values:batchClear`, {
|
|
419
|
+
ranges: p.ranges,
|
|
420
|
+
});
|
|
421
|
+
}
|
|
422
|
+
// ---- Sheets (tabs) ----
|
|
423
|
+
/** Adds a sheet (tab); index positions it, rowCount/columnCount size the grid. */
|
|
424
|
+
async addSheet(p) {
|
|
425
|
+
const gridProperties = compact({ rowCount: p.rowCount, columnCount: p.columnCount });
|
|
426
|
+
return this.batchUpdate(p.spreadsheetId, [
|
|
427
|
+
{
|
|
428
|
+
addSheet: {
|
|
429
|
+
properties: compact({
|
|
430
|
+
title: p.title,
|
|
431
|
+
index: p.index,
|
|
432
|
+
gridProperties: Object.keys(gridProperties).length > 0 ? gridProperties : undefined,
|
|
433
|
+
}),
|
|
434
|
+
},
|
|
435
|
+
},
|
|
436
|
+
]);
|
|
437
|
+
}
|
|
438
|
+
/** Duplicates a sheet within the same spreadsheet. */
|
|
439
|
+
async duplicateSheet(p) {
|
|
440
|
+
return this.batchUpdate(p.spreadsheetId, [
|
|
441
|
+
{
|
|
442
|
+
duplicateSheet: compact({
|
|
443
|
+
sourceSheetId: p.sheetId,
|
|
444
|
+
newSheetName: p.newTitle,
|
|
445
|
+
insertSheetIndex: p.insertIndex,
|
|
446
|
+
}),
|
|
447
|
+
},
|
|
448
|
+
]);
|
|
449
|
+
}
|
|
450
|
+
/** Renames a sheet (the sheetId never changes; only the visible title does). */
|
|
451
|
+
async renameSheet(p) {
|
|
452
|
+
return this.batchUpdate(p.spreadsheetId, [
|
|
453
|
+
{ updateSheetProperties: { properties: { sheetId: p.sheetId, title: p.title }, fields: "title" } },
|
|
454
|
+
]);
|
|
455
|
+
}
|
|
456
|
+
/** Deletes a sheet and everything on it. Irreversible through the API. */
|
|
457
|
+
async deleteSheet(spreadsheetId, sheetId) {
|
|
458
|
+
return this.batchUpdate(spreadsheetId, [{ deleteSheet: { sheetId } }]);
|
|
459
|
+
}
|
|
460
|
+
/** Copies a sheet into another spreadsheet (returns the new sheet's properties there). */
|
|
461
|
+
async copySheetTo(p) {
|
|
462
|
+
return this.request("POST", `v4/spreadsheets/${encodeURIComponent(p.spreadsheetId)}/sheets/${p.sheetId}:copyTo`, { destinationSpreadsheetId: p.destinationSpreadsheetId });
|
|
463
|
+
}
|
|
464
|
+
// ---- Formatting, dimensions, freeze, borders ----
|
|
465
|
+
/** Applies a partial CellFormat to a range via repeatCell with a computed fields mask. */
|
|
466
|
+
async formatCells(p) {
|
|
467
|
+
const { format, fields } = buildCellFormat(p);
|
|
468
|
+
return this.batchUpdate(p.spreadsheetId, [
|
|
469
|
+
{ repeatCell: { range: gridRange(p.range), cell: { userEnteredFormat: format }, fields } },
|
|
470
|
+
]);
|
|
471
|
+
}
|
|
472
|
+
/** Freezes (or unfreezes with 0) the first N rows/columns of a sheet. */
|
|
473
|
+
async setFrozen(p) {
|
|
474
|
+
const gridProperties = compact({
|
|
475
|
+
frozenRowCount: p.frozenRowCount,
|
|
476
|
+
frozenColumnCount: p.frozenColumnCount,
|
|
477
|
+
});
|
|
478
|
+
const fields = Object.keys(gridProperties)
|
|
479
|
+
.map((key) => `gridProperties.${key}`)
|
|
480
|
+
.join(",");
|
|
481
|
+
if (!fields)
|
|
482
|
+
throw new Error("At least one of frozen_rows or frozen_columns is required.");
|
|
483
|
+
return this.batchUpdate(p.spreadsheetId, [
|
|
484
|
+
{ updateSheetProperties: { properties: { sheetId: p.sheetId, gridProperties }, fields } },
|
|
485
|
+
]);
|
|
486
|
+
}
|
|
487
|
+
/** Sets the borders of a range (outer sides and/or inner grid lines). */
|
|
488
|
+
async setBorders(p) {
|
|
489
|
+
const mapBorder = (b) => b === undefined ? undefined : compact({ style: b.style, color: b.color === undefined ? undefined : hexToColor(b.color) });
|
|
490
|
+
const borders = compact({
|
|
491
|
+
top: mapBorder(p.top),
|
|
492
|
+
bottom: mapBorder(p.bottom),
|
|
493
|
+
left: mapBorder(p.left),
|
|
494
|
+
right: mapBorder(p.right),
|
|
495
|
+
innerHorizontal: mapBorder(p.innerHorizontal),
|
|
496
|
+
innerVertical: mapBorder(p.innerVertical),
|
|
497
|
+
});
|
|
498
|
+
if (Object.keys(borders).length === 0) {
|
|
499
|
+
throw new Error("At least one border side (top/bottom/left/right/inner_horizontal/inner_vertical) is required.");
|
|
500
|
+
}
|
|
501
|
+
return this.batchUpdate(p.spreadsheetId, [{ updateBorders: { range: gridRange(p.range), ...borders } }]);
|
|
502
|
+
}
|
|
503
|
+
/** Sets rows/columns to an exact pixel size. */
|
|
504
|
+
async resizeDimensions(p) {
|
|
505
|
+
return this.batchUpdate(p.spreadsheetId, [
|
|
506
|
+
{
|
|
507
|
+
updateDimensionProperties: {
|
|
508
|
+
range: dimensionRange(p),
|
|
509
|
+
properties: { pixelSize: p.pixelSize },
|
|
510
|
+
fields: "pixelSize",
|
|
511
|
+
},
|
|
512
|
+
},
|
|
513
|
+
]);
|
|
514
|
+
}
|
|
515
|
+
/** Auto-fits rows/columns to their content. */
|
|
516
|
+
async autoResizeDimensions(p) {
|
|
517
|
+
return this.batchUpdate(p.spreadsheetId, [{ autoResizeDimensions: { dimensions: dimensionRange(p) } }]);
|
|
518
|
+
}
|
|
519
|
+
/** Inserts empty rows/columns at startIndex. */
|
|
520
|
+
async insertDimensions(p) {
|
|
521
|
+
return this.batchUpdate(p.spreadsheetId, [
|
|
522
|
+
{ insertDimension: compact({ range: dimensionRange(p), inheritFromBefore: p.inheritFromBefore }) },
|
|
523
|
+
]);
|
|
524
|
+
}
|
|
525
|
+
/** Deletes rows/columns and their data. Irreversible through the API. */
|
|
526
|
+
async deleteDimensions(p) {
|
|
527
|
+
return this.batchUpdate(p.spreadsheetId, [{ deleteDimension: { range: dimensionRange(p) } }]);
|
|
528
|
+
}
|
|
529
|
+
/** Hides or shows rows/columns without touching their data. */
|
|
530
|
+
async setDimensionsHidden(p) {
|
|
531
|
+
return this.batchUpdate(p.spreadsheetId, [
|
|
532
|
+
{
|
|
533
|
+
updateDimensionProperties: {
|
|
534
|
+
range: dimensionRange(p),
|
|
535
|
+
properties: { hiddenByUser: p.hidden },
|
|
536
|
+
fields: "hiddenByUser",
|
|
537
|
+
},
|
|
538
|
+
},
|
|
539
|
+
]);
|
|
540
|
+
}
|
|
541
|
+
/** Groups rows/columns so they collapse/expand together (groups can nest). */
|
|
542
|
+
async groupDimensions(p) {
|
|
543
|
+
return this.batchUpdate(p.spreadsheetId, [{ addDimensionGroup: { range: dimensionRange(p) } }]);
|
|
544
|
+
}
|
|
545
|
+
/** Removes the deepest group over the given rows/columns. */
|
|
546
|
+
async ungroupDimensions(p) {
|
|
547
|
+
return this.batchUpdate(p.spreadsheetId, [{ deleteDimensionGroup: { range: dimensionRange(p) } }]);
|
|
548
|
+
}
|
|
549
|
+
// ---- Data validation, protected ranges, conditional formatting ----
|
|
550
|
+
/**
|
|
551
|
+
* Sets (or, with no condition, clears) a data-validation rule on a range.
|
|
552
|
+
* ONE_OF_LIST turns into an in-cell dropdown when showCustomUi is true.
|
|
553
|
+
*/
|
|
554
|
+
async setDataValidation(p) {
|
|
555
|
+
const rule = p.conditionType === undefined
|
|
556
|
+
? undefined
|
|
557
|
+
: compact({
|
|
558
|
+
condition: buildCondition(p.conditionType, p.conditionValues),
|
|
559
|
+
inputMessage: p.inputMessage,
|
|
560
|
+
strict: p.strict,
|
|
561
|
+
showCustomUi: p.showCustomUi,
|
|
562
|
+
});
|
|
563
|
+
return this.batchUpdate(p.spreadsheetId, [
|
|
564
|
+
{ setDataValidation: compact({ range: gridRange(p.range), rule }) },
|
|
565
|
+
]);
|
|
566
|
+
}
|
|
567
|
+
/** Protects a range or a whole sheet (range without row/column bounds). */
|
|
568
|
+
async addProtectedRange(p) {
|
|
569
|
+
if (!p.range && !p.namedRangeId)
|
|
570
|
+
throw new Error("Either range or named_range_id is required.");
|
|
571
|
+
const editors = p.editorUsers || p.editorGroups
|
|
572
|
+
? compact({ users: p.editorUsers, groups: p.editorGroups })
|
|
573
|
+
: undefined;
|
|
574
|
+
return this.batchUpdate(p.spreadsheetId, [
|
|
575
|
+
{
|
|
576
|
+
addProtectedRange: {
|
|
577
|
+
protectedRange: compact({
|
|
578
|
+
range: p.range ? gridRange(p.range) : undefined,
|
|
579
|
+
namedRangeId: p.namedRangeId,
|
|
580
|
+
description: p.description,
|
|
581
|
+
warningOnly: p.warningOnly,
|
|
582
|
+
editors,
|
|
583
|
+
}),
|
|
584
|
+
},
|
|
585
|
+
},
|
|
586
|
+
]);
|
|
587
|
+
}
|
|
588
|
+
/** Updates a protected range's description/warning mode/editors with a computed fields mask. */
|
|
589
|
+
async updateProtectedRange(p) {
|
|
590
|
+
const editors = p.editorUsers || p.editorGroups
|
|
591
|
+
? compact({ users: p.editorUsers, groups: p.editorGroups })
|
|
592
|
+
: undefined;
|
|
593
|
+
const protectedRange = compact({
|
|
594
|
+
protectedRangeId: p.protectedRangeId,
|
|
595
|
+
description: p.description,
|
|
596
|
+
warningOnly: p.warningOnly,
|
|
597
|
+
editors,
|
|
598
|
+
});
|
|
599
|
+
const fields = Object.keys(protectedRange)
|
|
600
|
+
.filter((key) => key !== "protectedRangeId")
|
|
601
|
+
.join(",");
|
|
602
|
+
if (!fields)
|
|
603
|
+
throw new Error("At least one of description, warning_only or editors is required.");
|
|
604
|
+
return this.batchUpdate(p.spreadsheetId, [{ updateProtectedRange: { protectedRange, fields } }]);
|
|
605
|
+
}
|
|
606
|
+
/** Removes a protection (the cells and their data stay). */
|
|
607
|
+
async deleteProtectedRange(spreadsheetId, protectedRangeId) {
|
|
608
|
+
return this.batchUpdate(spreadsheetId, [{ deleteProtectedRange: { protectedRangeId } }]);
|
|
609
|
+
}
|
|
610
|
+
/** Adds a boolean conditional-format rule at the given per-sheet index (default: first). */
|
|
611
|
+
async addConditionalFormat(p) {
|
|
612
|
+
return this.batchUpdate(p.spreadsheetId, [
|
|
613
|
+
{ addConditionalFormatRule: { rule: buildConditionalRule(p), index: p.index ?? 0 } },
|
|
614
|
+
]);
|
|
615
|
+
}
|
|
616
|
+
/** Replaces the rule at a per-sheet index with a new boolean rule. */
|
|
617
|
+
async updateConditionalFormat(p) {
|
|
618
|
+
return this.batchUpdate(p.spreadsheetId, [
|
|
619
|
+
{ updateConditionalFormatRule: { sheetId: p.sheetId, index: p.index, rule: buildConditionalRule(p) } },
|
|
620
|
+
]);
|
|
621
|
+
}
|
|
622
|
+
/** Deletes the conditional-format rule at a per-sheet index (later rules shift down). */
|
|
623
|
+
async deleteConditionalFormat(spreadsheetId, sheetId, index) {
|
|
624
|
+
return this.batchUpdate(spreadsheetId, [{ deleteConditionalFormatRule: { sheetId, index } }]);
|
|
625
|
+
}
|
|
626
|
+
// ---- Tables ----
|
|
627
|
+
/** Adds a structured table over a range. */
|
|
628
|
+
async addTable(p) {
|
|
629
|
+
return this.batchUpdate(p.spreadsheetId, [
|
|
630
|
+
{
|
|
631
|
+
addTable: {
|
|
632
|
+
table: compact({ name: p.name, range: gridRange(p.range), columnProperties: p.columnProperties }),
|
|
633
|
+
},
|
|
634
|
+
},
|
|
635
|
+
]);
|
|
636
|
+
}
|
|
637
|
+
/** Renames and/or re-ranges a table with a computed fields mask. */
|
|
638
|
+
async updateTable(p) {
|
|
639
|
+
const table = compact({
|
|
640
|
+
tableId: p.tableId,
|
|
641
|
+
name: p.name,
|
|
642
|
+
range: p.range ? gridRange(p.range) : undefined,
|
|
643
|
+
});
|
|
644
|
+
const fields = Object.keys(table)
|
|
645
|
+
.filter((key) => key !== "tableId")
|
|
646
|
+
.join(",");
|
|
647
|
+
if (!fields)
|
|
648
|
+
throw new Error("At least one of name or range is required.");
|
|
649
|
+
return this.batchUpdate(p.spreadsheetId, [{ updateTable: { table, fields } }]);
|
|
650
|
+
}
|
|
651
|
+
/** Deletes a table definition (the underlying cell data stays). */
|
|
652
|
+
async deleteTable(spreadsheetId, tableId) {
|
|
653
|
+
return this.batchUpdate(spreadsheetId, [{ deleteTable: { tableId } }]);
|
|
654
|
+
}
|
|
655
|
+
// ---- Charts ----
|
|
656
|
+
/** Adds an embedded chart, anchored over the grid or on its own new sheet. */
|
|
657
|
+
async addChart(p) {
|
|
658
|
+
if (!p.anchor && !p.newSheet) {
|
|
659
|
+
throw new Error("Either anchor (sheet_id + row_index + column_index) or new_sheet=true is required.");
|
|
660
|
+
}
|
|
661
|
+
const position = p.newSheet ? { newSheet: true } : { overlayPosition: { anchorCell: p.anchor } };
|
|
662
|
+
return this.batchUpdate(p.spreadsheetId, [
|
|
663
|
+
{ addChart: { chart: { spec: buildChartSpec(p), position } } },
|
|
664
|
+
]);
|
|
665
|
+
}
|
|
666
|
+
/** Replaces a chart's entire spec (updateChartSpec has no partial mask). */
|
|
667
|
+
async updateChart(p) {
|
|
668
|
+
return this.batchUpdate(p.spreadsheetId, [
|
|
669
|
+
{ updateChartSpec: { chartId: p.chartId, spec: buildChartSpec(p) } },
|
|
670
|
+
]);
|
|
671
|
+
}
|
|
672
|
+
/** Deletes an embedded chart by its chartId. */
|
|
673
|
+
async deleteChart(spreadsheetId, chartId) {
|
|
674
|
+
return this.batchUpdate(spreadsheetId, [{ deleteEmbeddedObject: { objectId: chartId } }]);
|
|
675
|
+
}
|
|
676
|
+
// ---- Sharing (Drive permissions — internal dependency) ----
|
|
677
|
+
/**
|
|
678
|
+
* Lists who can access the spreadsheet — one page per call. Shared-drive
|
|
679
|
+
* files cap a page at 100 permissions, so the fields mask must keep
|
|
680
|
+
* `nextPageToken` or a long list is truncated silently.
|
|
681
|
+
*/
|
|
682
|
+
async listPermissions(p) {
|
|
683
|
+
return this.driveRequest("GET", `drive/v3/files/${encodeURIComponent(p.spreadsheetId)}/permissions`, undefined, {
|
|
684
|
+
fields: "nextPageToken,permissions(id,type,role,emailAddress,domain,displayName,deleted)",
|
|
685
|
+
pageSize: p.pageSize,
|
|
686
|
+
pageToken: p.pageToken,
|
|
687
|
+
supportsAllDrives: true,
|
|
688
|
+
});
|
|
689
|
+
}
|
|
690
|
+
/** Grants reader/commenter/writer access to a user, group, domain or anyone. */
|
|
691
|
+
async grantPermission(p) {
|
|
692
|
+
if ((p.type === "user" || p.type === "group") && !p.emailAddress) {
|
|
693
|
+
throw new Error(`type "${p.type}" requires email_address.`);
|
|
694
|
+
}
|
|
695
|
+
if (p.type === "domain" && !p.domain)
|
|
696
|
+
throw new Error('type "domain" requires domain.');
|
|
697
|
+
return this.driveRequest("POST", `drive/v3/files/${encodeURIComponent(p.spreadsheetId)}/permissions`, compact({
|
|
698
|
+
role: p.role,
|
|
699
|
+
type: p.type,
|
|
700
|
+
emailAddress: p.emailAddress,
|
|
701
|
+
domain: p.domain,
|
|
702
|
+
allowFileDiscovery: p.allowFileDiscovery,
|
|
703
|
+
}), compact({
|
|
704
|
+
sendNotificationEmail: p.sendNotificationEmail,
|
|
705
|
+
emailMessage: p.emailMessage,
|
|
706
|
+
supportsAllDrives: true,
|
|
707
|
+
}));
|
|
708
|
+
}
|
|
709
|
+
/** Changes an existing permission's role. */
|
|
710
|
+
async updatePermission(p) {
|
|
711
|
+
return this.driveRequest("PATCH", `drive/v3/files/${encodeURIComponent(p.spreadsheetId)}/permissions/${encodeURIComponent(p.permissionId)}`, { role: p.role }, { supportsAllDrives: true });
|
|
712
|
+
}
|
|
713
|
+
/** Revokes a permission by its id. */
|
|
714
|
+
async revokePermission(spreadsheetId, permissionId) {
|
|
715
|
+
return this.driveRequest("DELETE", `drive/v3/files/${encodeURIComponent(spreadsheetId)}/permissions/${encodeURIComponent(permissionId)}`, undefined, { supportsAllDrives: true });
|
|
716
|
+
}
|
|
717
|
+
/**
|
|
718
|
+
* Trashes the spreadsheet's Drive file. NOT exposed as a tool — deleting
|
|
719
|
+
* spreadsheets is outside the functional contour; this exists only so the
|
|
720
|
+
* opt-in live smoke can clean up the disposable spreadsheet it created.
|
|
721
|
+
*/
|
|
722
|
+
async deleteSpreadsheetFile(spreadsheetId) {
|
|
723
|
+
return this.driveRequest("DELETE", `drive/v3/files/${encodeURIComponent(spreadsheetId)}`, undefined, { supportsAllDrives: true });
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
/** Maps a DimensionRangeParams (plus extras) to the wire DimensionRange. */
|
|
727
|
+
function dimensionRange(p) {
|
|
728
|
+
return { sheetId: p.sheetId, dimension: p.dimension, startIndex: p.startIndex, endIndex: p.endIndex };
|
|
729
|
+
}
|
|
730
|
+
/** Drops keys whose value is `undefined` so they are not sent to the API. */
|
|
731
|
+
function compact(obj) {
|
|
732
|
+
return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined));
|
|
733
|
+
}
|
|
734
|
+
function delay(ms) {
|
|
735
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
736
|
+
}
|