@mindstone/mcp-server-google-workspace 0.4.2 → 0.5.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/README.md +43 -5
- package/dist/modules/docs/service.d.ts +76 -6
- package/dist/modules/docs/service.js +791 -103
- package/dist/modules/docs/tabCopy.d.ts +266 -0
- package/dist/modules/docs/tabCopy.js +794 -0
- package/dist/modules/docs/tabs.d.ts +161 -0
- package/dist/modules/docs/tabs.js +416 -0
- package/dist/modules/docs/types.d.ts +141 -1
- package/dist/modules/drive/service.d.ts +15 -0
- package/dist/modules/drive/service.js +77 -2
- package/dist/modules/drive/types.d.ts +1 -1
- package/dist/modules/sheets/a1Utils.d.ts +13 -0
- package/dist/modules/sheets/a1Utils.js +33 -7
- package/dist/modules/sheets/formatters.d.ts +33 -2
- package/dist/modules/sheets/formatters.js +84 -5
- package/dist/modules/sheets/service.d.ts +26 -1
- package/dist/modules/sheets/service.js +264 -8
- package/dist/modules/sheets/types.d.ts +71 -0
- package/dist/modules/sheets/types.js +12 -1
- package/dist/modules/sheets/writeGuards.js +2 -2
- package/dist/tools/definitions/destructive-overrides.json +8 -0
- package/dist/tools/definitions/docs.js +395 -9
- package/dist/tools/definitions/drive.js +9 -4
- package/dist/tools/definitions/open-world-overrides.json +8 -0
- package/dist/tools/definitions/sheets.js +177 -1
- package/dist/tools/docs-handlers.d.ts +125 -0
- package/dist/tools/docs-handlers.js +397 -15
- package/dist/tools/param-normalizer.js +16 -0
- package/dist/tools/server.js +35 -3
- package/dist/tools/sheets-handlers.d.ts +54 -1
- package/dist/tools/sheets-handlers.js +107 -13
- package/dist/tools/type-guards.d.ts +89 -0
- package/dist/tools/type-guards.js +190 -6
- package/dist/tools/types.d.ts +1 -1
- package/dist/utils/apiError.d.ts +6 -0
- package/dist/utils/apiError.js +12 -0
- package/dist/utils/tabPosition.d.ts +20 -0
- package/dist/utils/tabPosition.js +19 -0
- package/package.json +1 -1
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { docs_v1 } from 'googleapis';
|
|
2
|
+
import type { ChipFallback, CopyVerification } from './tabCopy.js';
|
|
2
3
|
export type DocsDocument = docs_v1.Schema$Document;
|
|
3
4
|
export type DocsRequest = docs_v1.Schema$Request;
|
|
4
5
|
export type DocsBatchUpdateResponse = docs_v1.Schema$BatchUpdateDocumentResponse;
|
|
@@ -16,6 +17,7 @@ export interface BatchUpdateDocumentOptions {
|
|
|
16
17
|
}
|
|
17
18
|
export interface ReadDocumentOptions {
|
|
18
19
|
tabId?: string;
|
|
20
|
+
allTabs?: boolean;
|
|
19
21
|
maxChars?: number;
|
|
20
22
|
includeMetadata?: boolean;
|
|
21
23
|
returnJson?: boolean;
|
|
@@ -46,6 +48,15 @@ export interface TabInfo {
|
|
|
46
48
|
title: string;
|
|
47
49
|
index: number;
|
|
48
50
|
wordCount?: number;
|
|
51
|
+
parentTabId: string | null;
|
|
52
|
+
nestingLevel: number;
|
|
53
|
+
path: string;
|
|
54
|
+
childCount: number;
|
|
55
|
+
}
|
|
56
|
+
export interface TabListResponse {
|
|
57
|
+
documentId: string;
|
|
58
|
+
title: string;
|
|
59
|
+
tabs: TabInfo[];
|
|
49
60
|
}
|
|
50
61
|
export interface DocumentResponse {
|
|
51
62
|
title: string;
|
|
@@ -56,10 +67,118 @@ export interface DocumentResponse {
|
|
|
56
67
|
tabCount?: number;
|
|
57
68
|
tabs?: TabInfo[];
|
|
58
69
|
revisionId?: string;
|
|
70
|
+
shownTab?: {
|
|
71
|
+
tabId: string;
|
|
72
|
+
title: string;
|
|
73
|
+
};
|
|
74
|
+
requestedTab?: {
|
|
75
|
+
tabId: string;
|
|
76
|
+
title: string;
|
|
77
|
+
path: string;
|
|
78
|
+
childCount?: number;
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
export interface AddTabOptions {
|
|
82
|
+
documentId: string;
|
|
83
|
+
title: string;
|
|
84
|
+
parentTabId?: string;
|
|
85
|
+
position?: number;
|
|
86
|
+
}
|
|
87
|
+
export interface UpdateTabOptions {
|
|
88
|
+
documentId: string;
|
|
89
|
+
tabId: string;
|
|
90
|
+
title?: string;
|
|
91
|
+
parentTabId?: string;
|
|
92
|
+
position?: number;
|
|
93
|
+
}
|
|
94
|
+
export interface DeleteTabOptions {
|
|
95
|
+
documentId: string;
|
|
96
|
+
tabId: string;
|
|
97
|
+
deleteSubTabs?: boolean;
|
|
98
|
+
}
|
|
99
|
+
export type InsertTextPosition = 'after' | 'before' | 'next_paragraph_start';
|
|
100
|
+
export interface InsertTextOptions {
|
|
101
|
+
documentId: string;
|
|
102
|
+
tabId?: string;
|
|
103
|
+
anchorText: string;
|
|
104
|
+
position: InsertTextPosition;
|
|
105
|
+
text: string;
|
|
106
|
+
matchCase: boolean;
|
|
107
|
+
expectEmptyParagraph?: boolean;
|
|
108
|
+
}
|
|
109
|
+
export interface TabRef {
|
|
110
|
+
tabId: string;
|
|
111
|
+
title: string;
|
|
112
|
+
path: string;
|
|
113
|
+
}
|
|
114
|
+
/** Result of add / update: the tab as the document reports it after the write. */
|
|
115
|
+
export interface TabWriteResponse {
|
|
116
|
+
documentId: string;
|
|
117
|
+
tab: TabInfo;
|
|
118
|
+
/** The tab's parent after the write; null = top level. */
|
|
119
|
+
parent: TabRef | null;
|
|
120
|
+
/** Update only: false when nothing would change, so no write was sent. */
|
|
121
|
+
changed: boolean;
|
|
122
|
+
/** The position the caller asked for, or the default that was applied. */
|
|
123
|
+
requestedPosition: number;
|
|
124
|
+
/** The parent the caller asked for (null = top level). */
|
|
125
|
+
requestedParentTabId: string | null;
|
|
126
|
+
}
|
|
127
|
+
export interface TabDeleteResponse {
|
|
128
|
+
documentId: string;
|
|
129
|
+
deleted: TabRef;
|
|
130
|
+
/** Sub-tabs deleted with it, in tree order. */
|
|
131
|
+
descendants: TabRef[];
|
|
132
|
+
}
|
|
133
|
+
export interface InsertTextResponse {
|
|
134
|
+
documentId: string;
|
|
135
|
+
tab: TabRef;
|
|
136
|
+
position: InsertTextPosition;
|
|
137
|
+
index: number;
|
|
138
|
+
/** Characters inserted, as Docs stores them (after normalisation). */
|
|
139
|
+
insertedChars: number;
|
|
140
|
+
/** Control or private-use characters left out because Docs would strip them. */
|
|
141
|
+
removedChars: number;
|
|
142
|
+
newParagraphs: number;
|
|
143
|
+
/** The paragraph the text landed in, as read before the write. */
|
|
144
|
+
targetParagraph: {
|
|
145
|
+
wasEmpty: boolean;
|
|
146
|
+
namedStyleType: string;
|
|
147
|
+
bulleted: boolean;
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
export interface CopyTabOptions {
|
|
151
|
+
documentId: string;
|
|
152
|
+
sourceTabId: string;
|
|
153
|
+
targetTabId?: string;
|
|
154
|
+
overwriteExisting?: boolean;
|
|
155
|
+
newTabTitle?: string;
|
|
156
|
+
newTabParentId?: string;
|
|
157
|
+
newTabPosition?: number;
|
|
158
|
+
}
|
|
159
|
+
/** Result of copy_workspace_document_tab. */
|
|
160
|
+
export interface TabCopyResponse {
|
|
161
|
+
documentId: string;
|
|
162
|
+
mode: 'new' | 'overwrite';
|
|
163
|
+
source: TabRef;
|
|
164
|
+
target: TabRef;
|
|
165
|
+
requests: number;
|
|
166
|
+
rounds: number;
|
|
167
|
+
durationMs: number;
|
|
168
|
+
chipsCopied: number;
|
|
169
|
+
chipFallbacks: ChipFallback[];
|
|
170
|
+
convertedToText: {
|
|
171
|
+
people: number;
|
|
172
|
+
dates: number;
|
|
173
|
+
};
|
|
174
|
+
namedStylesCopied: number;
|
|
175
|
+
notCopied: Record<string, number>;
|
|
176
|
+
notes: string[];
|
|
177
|
+
verification: CopyVerification;
|
|
59
178
|
}
|
|
60
179
|
export interface DocsOperationResult {
|
|
61
180
|
success: boolean;
|
|
62
|
-
data?: DocumentResponse | DocsDocument |
|
|
181
|
+
data?: DocumentResponse | DocsDocument | TabListResponse | TabJsonResponse | DocsBatchUpdateResponse | TabWriteResponse | TabDeleteResponse | InsertTextResponse | TabCopyResponse;
|
|
63
182
|
error?: string;
|
|
64
183
|
occurrencesChanged?: number;
|
|
65
184
|
}
|
|
@@ -67,6 +186,27 @@ export interface ListTabsOptions {
|
|
|
67
186
|
documentId: string;
|
|
68
187
|
includeWordCount?: boolean;
|
|
69
188
|
}
|
|
189
|
+
/**
|
|
190
|
+
* A documentTab as Google returns it, except `namedRanges`: Google keys that
|
|
191
|
+
* map by the author-chosen range name, and JSON keys are not enveloped, so it
|
|
192
|
+
* is returned as a list (each entry still carries its `name`).
|
|
193
|
+
*/
|
|
194
|
+
export type TabJsonDocumentTab = Omit<docs_v1.Schema$DocumentTab, 'namedRanges'> & {
|
|
195
|
+
namedRanges?: docs_v1.Schema$NamedRanges[];
|
|
196
|
+
};
|
|
197
|
+
export interface TabJsonResponse {
|
|
198
|
+
documentId: string;
|
|
199
|
+
title: string;
|
|
200
|
+
revisionId?: string;
|
|
201
|
+
tab: {
|
|
202
|
+
tabProperties?: docs_v1.Schema$TabProperties;
|
|
203
|
+
documentTab?: TabJsonDocumentTab;
|
|
204
|
+
};
|
|
205
|
+
childTabs: Array<{
|
|
206
|
+
tabId: string;
|
|
207
|
+
title: string;
|
|
208
|
+
}>;
|
|
209
|
+
}
|
|
70
210
|
export interface ExtractIdResult {
|
|
71
211
|
success: boolean;
|
|
72
212
|
documentId?: string;
|
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
import { google } from 'googleapis';
|
|
2
2
|
import { BaseGoogleService } from '../../services/base/BaseGoogleService.js';
|
|
3
3
|
import { DriveOperationResult, FileDownloadOptions, FileListOptions, FileSearchOptions, FileUploadOptions, PermissionOptions, SharedDriveListOptions } from './types.js';
|
|
4
|
+
/**
|
|
5
|
+
* Drive's own `orderBy` is a comma-separated string; callers may pass that
|
|
6
|
+
* string or an array of keys. Returns undefined when nothing usable is left.
|
|
7
|
+
*/
|
|
8
|
+
export declare function normalizeOrderBy(value: string | string[] | undefined): string | undefined;
|
|
4
9
|
export declare class DriveService extends BaseGoogleService<ReturnType<typeof google.drive>> {
|
|
5
10
|
private initialized;
|
|
6
11
|
constructor();
|
|
@@ -17,6 +22,16 @@ export declare class DriveService extends BaseGoogleService<ReturnType<typeof go
|
|
|
17
22
|
*/
|
|
18
23
|
private checkInitialized;
|
|
19
24
|
listFiles(email: string, options?: FileListOptions): Promise<DriveOperationResult>;
|
|
25
|
+
/**
|
|
26
|
+
* Whether the account can open a file. Used before inserting a smart chip:
|
|
27
|
+
* the Docs API fails a whole batch for a chip the caller can't open. A 404
|
|
28
|
+
* or a plain permission 403 means "no"; a 403 for a missing OAuth scope, an
|
|
29
|
+
* auth handoff or any other failure is rethrown, so a scope or sign-in
|
|
30
|
+
* problem is never mistaken for "can't open this file". A rate limit (a 429,
|
|
31
|
+
* or a 403 with a quota reason) throws a DriveRateLimitError: the copy stops
|
|
32
|
+
* before writing anything instead of turning an openable chip into a link.
|
|
33
|
+
*/
|
|
34
|
+
checkFileAccess(email: string, fileId: string): Promise<boolean>;
|
|
20
35
|
listSharedDrives(email: string, options?: SharedDriveListOptions): Promise<DriveOperationResult>;
|
|
21
36
|
uploadFile(email: string, options: FileUploadOptions): Promise<DriveOperationResult>;
|
|
22
37
|
downloadFile(email: string, options: FileDownloadOptions): Promise<DriveOperationResult>;
|
|
@@ -2,7 +2,39 @@ import { google } from 'googleapis';
|
|
|
2
2
|
import { BaseGoogleService } from '../../services/base/BaseGoogleService.js';
|
|
3
3
|
import { Readable } from 'stream';
|
|
4
4
|
import { DRIVE_SCOPES } from './scopes.js';
|
|
5
|
+
import { extractHttpStatus } from '../../utils/apiError.js';
|
|
5
6
|
const MAX_INLINE_BINARY_BYTES = 500 * 1024; // 500KB
|
|
7
|
+
/** A 403 caused by a missing OAuth scope (not by the file's sharing settings). */
|
|
8
|
+
const INSUFFICIENT_SCOPE = /insufficient.*scope|insufficientPermissions|ACCESS_TOKEN_SCOPE_INSUFFICIENT/i;
|
|
9
|
+
/** The error's message plus its response body, where Google puts the structured reason. */
|
|
10
|
+
function errorText(error) {
|
|
11
|
+
const message = error instanceof Error ? error.message : '';
|
|
12
|
+
const data = error?.response?.data;
|
|
13
|
+
return `${message}\n${typeof data === 'string' ? data : JSON.stringify(data ?? '')}`;
|
|
14
|
+
}
|
|
15
|
+
function isInsufficientScopeError(error) {
|
|
16
|
+
return INSUFFICIENT_SCOPE.test(errorText(error));
|
|
17
|
+
}
|
|
18
|
+
/** Drive's quota reasons; Google sends these with a 403, so they look like a permission denial. */
|
|
19
|
+
const RATE_LIMIT_REASON = /\b(?:userRateLimitExceeded|rateLimitExceeded|dailyLimitExceeded)\b/;
|
|
20
|
+
/** The rate-limit reason of a 429, or of a 403 whose structured reason is a quota limit; undefined otherwise. */
|
|
21
|
+
function rateLimitReason(error, status) {
|
|
22
|
+
if (status !== 403 && status !== 429)
|
|
23
|
+
return undefined;
|
|
24
|
+
const reason = RATE_LIMIT_REASON.exec(errorText(error))?.[0];
|
|
25
|
+
if (reason)
|
|
26
|
+
return reason;
|
|
27
|
+
return status === 429 ? 'too many requests' : undefined;
|
|
28
|
+
}
|
|
29
|
+
/** A Drive rate limit hit while checking file access. Carries the HTTP status so error descriptions keep it. */
|
|
30
|
+
class DriveRateLimitError extends Error {
|
|
31
|
+
status;
|
|
32
|
+
constructor(status, reason, options) {
|
|
33
|
+
super(`Google rate limit reached while checking access to a linked file (${reason}); try again shortly`, options);
|
|
34
|
+
this.status = status;
|
|
35
|
+
this.name = 'DriveRateLimitError';
|
|
36
|
+
}
|
|
37
|
+
}
|
|
6
38
|
const TEXT_APPLICATION_TYPES = new Set([
|
|
7
39
|
'application/json',
|
|
8
40
|
'application/xml',
|
|
@@ -37,6 +69,17 @@ function decodeContent(data, mimeType) {
|
|
|
37
69
|
function escapeDriveQueryValue(value) {
|
|
38
70
|
return value.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
|
|
39
71
|
}
|
|
72
|
+
/**
|
|
73
|
+
* Drive's own `orderBy` is a comma-separated string; callers may pass that
|
|
74
|
+
* string or an array of keys. Returns undefined when nothing usable is left.
|
|
75
|
+
*/
|
|
76
|
+
export function normalizeOrderBy(value) {
|
|
77
|
+
if (value === undefined)
|
|
78
|
+
return undefined;
|
|
79
|
+
const joined = Array.isArray(value) ? value.join(',') : value;
|
|
80
|
+
const trimmed = joined.trim();
|
|
81
|
+
return trimmed === '' ? undefined : trimmed;
|
|
82
|
+
}
|
|
40
83
|
export class DriveService extends BaseGoogleService {
|
|
41
84
|
initialized = false;
|
|
42
85
|
constructor() {
|
|
@@ -91,7 +134,7 @@ export class DriveService extends BaseGoogleService {
|
|
|
91
134
|
q: query.join(' and ') || undefined,
|
|
92
135
|
pageSize: options.pageSize,
|
|
93
136
|
pageToken: options.pageToken,
|
|
94
|
-
orderBy: options.orderBy
|
|
137
|
+
orderBy: normalizeOrderBy(options.orderBy),
|
|
95
138
|
fields: options.fields?.join(',') || 'files(id, name, mimeType, modifiedTime, size)',
|
|
96
139
|
// Google rejects driveId unless corpora is 'drive', so force the pairing.
|
|
97
140
|
driveId: options.driveId || undefined,
|
|
@@ -108,6 +151,38 @@ export class DriveService extends BaseGoogleService {
|
|
|
108
151
|
throw this.handleError(error, 'Failed to list Drive files');
|
|
109
152
|
}
|
|
110
153
|
}
|
|
154
|
+
/**
|
|
155
|
+
* Whether the account can open a file. Used before inserting a smart chip:
|
|
156
|
+
* the Docs API fails a whole batch for a chip the caller can't open. A 404
|
|
157
|
+
* or a plain permission 403 means "no"; a 403 for a missing OAuth scope, an
|
|
158
|
+
* auth handoff or any other failure is rethrown, so a scope or sign-in
|
|
159
|
+
* problem is never mistaken for "can't open this file". A rate limit (a 429,
|
|
160
|
+
* or a 403 with a quota reason) throws a DriveRateLimitError: the copy stops
|
|
161
|
+
* before writing anything instead of turning an openable chip into a link.
|
|
162
|
+
*/
|
|
163
|
+
async checkFileAccess(email, fileId) {
|
|
164
|
+
await this.ensureInitialized();
|
|
165
|
+
this.checkInitialized();
|
|
166
|
+
await this.validateScopes(email, [DRIVE_SCOPES.READONLY]);
|
|
167
|
+
const client = await this.getAuthenticatedClient(email, (auth) => google.drive({ version: 'v3', auth }));
|
|
168
|
+
try {
|
|
169
|
+
await client.files.get({ fileId, fields: 'id', supportsAllDrives: true });
|
|
170
|
+
return true;
|
|
171
|
+
}
|
|
172
|
+
catch (error) {
|
|
173
|
+
const status = extractHttpStatus(error);
|
|
174
|
+
const limited = rateLimitReason(error, status);
|
|
175
|
+
if (limited && status !== undefined)
|
|
176
|
+
throw new DriveRateLimitError(status, limited, { cause: error });
|
|
177
|
+
if (status === 404)
|
|
178
|
+
return false;
|
|
179
|
+
if (status === 403 && !isInsufficientScopeError(error))
|
|
180
|
+
return false;
|
|
181
|
+
// Rethrown as is: the copy reports the Google message and status, and
|
|
182
|
+
// auth-handoff errors keep their reconnect signal.
|
|
183
|
+
throw error;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
111
186
|
async listSharedDrives(email, options = {}) {
|
|
112
187
|
try {
|
|
113
188
|
await this.ensureInitialized();
|
|
@@ -286,7 +361,7 @@ export class DriveService extends BaseGoogleService {
|
|
|
286
361
|
q: query.join(' and ') || undefined,
|
|
287
362
|
pageSize: options.pageSize,
|
|
288
363
|
pageToken: options.pageToken,
|
|
289
|
-
orderBy: options.orderBy
|
|
364
|
+
orderBy: normalizeOrderBy(options.orderBy),
|
|
290
365
|
fields: options.fields?.join(',') || 'files(id, name, mimeType, modifiedTime, size)',
|
|
291
366
|
// Google rejects driveId unless corpora is 'drive', so force the pairing.
|
|
292
367
|
driveId: options.driveId || undefined,
|
|
@@ -13,7 +13,20 @@ export declare class ActionableA1Error extends Error {
|
|
|
13
13
|
constructor(message: string, suggestion: string);
|
|
14
14
|
}
|
|
15
15
|
export declare function parseA1Range(range: string): ParsedA1 | null;
|
|
16
|
+
/**
|
|
17
|
+
* Sheet name part of an A1 reference for a sheet title exactly as Google
|
|
18
|
+
* reports it: quoted when needed, with any apostrophe doubled. Unlike
|
|
19
|
+
* quoteSheetNameIfNeeded, it does not trim the title or read surrounding
|
|
20
|
+
* apostrophes as quotes, so a title such as `'Archive'` stays that title.
|
|
21
|
+
*/
|
|
22
|
+
export declare function quoteSheetTitle(title: string): string;
|
|
16
23
|
export declare function quoteSheetNameIfNeeded(name: string): string;
|
|
24
|
+
/**
|
|
25
|
+
* Sheet row number of the first row in an A1 range ("Sheet1!B20:F35" → 20;
|
|
26
|
+
* a column or whole-sheet range starts at row 1). Undefined when the range
|
|
27
|
+
* can't be parsed, for example a named range.
|
|
28
|
+
*/
|
|
29
|
+
export declare function firstRowOfA1(range: string | undefined): number | undefined;
|
|
17
30
|
export declare function normaliseA1Range(range: string): string;
|
|
18
31
|
export declare function isLikelyUnbounded(range: string, maxBoundedRows?: number): boolean;
|
|
19
32
|
export declare function rowCountFromA1(range: string): number | null;
|
|
@@ -187,17 +187,40 @@ export function parseA1Range(range) {
|
|
|
187
187
|
raw: range,
|
|
188
188
|
};
|
|
189
189
|
}
|
|
190
|
+
/**
|
|
191
|
+
* Sheet name part of an A1 reference for a sheet title exactly as Google
|
|
192
|
+
* reports it: quoted when needed, with any apostrophe doubled. Unlike
|
|
193
|
+
* quoteSheetNameIfNeeded, it does not trim the title or read surrounding
|
|
194
|
+
* apostrophes as quotes, so a title such as `'Archive'` stays that title.
|
|
195
|
+
*/
|
|
196
|
+
export function quoteSheetTitle(title) {
|
|
197
|
+
const needsQuotes = !SIMPLE_SHEET_NAME_REGEX.test(title) ||
|
|
198
|
+
isBareA1LikeReference(title) ||
|
|
199
|
+
looksLikeR1C1Reference(title);
|
|
200
|
+
return needsQuotes ? `'${title.replace(/'/g, '\'\'')}'` : title;
|
|
201
|
+
}
|
|
190
202
|
export function quoteSheetNameIfNeeded(name) {
|
|
191
203
|
const trimmed = name.trim();
|
|
192
204
|
if (!trimmed) {
|
|
193
205
|
return '\'\'';
|
|
194
206
|
}
|
|
195
207
|
const unquoted = tryUnquoteSheetName(trimmed) ?? trimmed;
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
208
|
+
return quoteSheetTitle(unquoted);
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Sheet row number of the first row in an A1 range ("Sheet1!B20:F35" → 20;
|
|
212
|
+
* a column or whole-sheet range starts at row 1). Undefined when the range
|
|
213
|
+
* can't be parsed, for example a named range.
|
|
214
|
+
*/
|
|
215
|
+
export function firstRowOfA1(range) {
|
|
216
|
+
if (range === undefined) {
|
|
217
|
+
return undefined;
|
|
218
|
+
}
|
|
219
|
+
const parsed = parseA1Range(range);
|
|
220
|
+
if (!parsed) {
|
|
221
|
+
return undefined;
|
|
222
|
+
}
|
|
223
|
+
return parsed.startRow ?? 1;
|
|
201
224
|
}
|
|
202
225
|
export function normaliseA1Range(range) {
|
|
203
226
|
const trimmed = range.trim();
|
|
@@ -210,7 +233,10 @@ export function normaliseA1Range(range) {
|
|
|
210
233
|
if (!sheetName) {
|
|
211
234
|
return trimmed;
|
|
212
235
|
}
|
|
213
|
-
|
|
236
|
+
// sheetName is already unquoted, so quote the literal title: running it
|
|
237
|
+
// through quoteSheetNameIfNeeded would unquote it again and turn
|
|
238
|
+
// '''Archive'''!A1 into Archive!A1.
|
|
239
|
+
const normalisedSheet = quoteSheetTitle(sheetName);
|
|
214
240
|
const normalisedRangePart = split.rangePart.trim();
|
|
215
241
|
if (!normalisedRangePart) {
|
|
216
242
|
return `${normalisedSheet}!`;
|
|
@@ -225,7 +251,7 @@ export function normaliseA1Range(range) {
|
|
|
225
251
|
if (!sheetName) {
|
|
226
252
|
return trimmed;
|
|
227
253
|
}
|
|
228
|
-
return
|
|
254
|
+
return quoteSheetTitle(sheetName);
|
|
229
255
|
}
|
|
230
256
|
export function isLikelyUnbounded(range, maxBoundedRows = 1000) {
|
|
231
257
|
const parsed = parseA1Range(range);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Utilities for formatting Google Sheets content and parsing URLs.
|
|
3
3
|
*/
|
|
4
|
-
import type { AnchorReadResponse, SheetInfo, ShapedReadResponse, SpreadsheetResponse, SuspiciousWriteWarning } from './types.js';
|
|
4
|
+
import type { AnchorReadResponse, DimensionInsertResponse, SheetDuplicateResponse, SheetInfo, SheetUpdateResponse, ShapedReadResponse, SpreadsheetResponse, SuspiciousWriteWarning } from './types.js';
|
|
5
5
|
/**
|
|
6
6
|
* Construct a Google Sheets URL from spreadsheet ID
|
|
7
7
|
*/
|
|
@@ -30,8 +30,17 @@ export declare function formatSpreadsheetHeader(title: string, spreadsheetId: st
|
|
|
30
30
|
export declare function formatValuesAsTable(values: (string | number | boolean | null)[][] | undefined, options?: {
|
|
31
31
|
maxColWidth?: number;
|
|
32
32
|
includeRowNumbers?: boolean;
|
|
33
|
+
/** Number shown for the first row: the sheet row the values start at (default 1). */
|
|
34
|
+
firstRowNumber?: number;
|
|
35
|
+
}): string;
|
|
36
|
+
/**
|
|
37
|
+
* Sheet row number to show for the first row of values read from `range`.
|
|
38
|
+
* Values grouped by COLUMNS, or a range that can't be parsed, are numbered from 1.
|
|
39
|
+
*/
|
|
40
|
+
export declare function firstSheetRowNumber(range: string | undefined, majorDimension?: 'ROWS' | 'COLUMNS'): number;
|
|
41
|
+
export declare function formatShapedReadResponse(response: ShapedReadResponse, options?: {
|
|
42
|
+
majorDimension?: 'ROWS' | 'COLUMNS';
|
|
33
43
|
}): string;
|
|
34
|
-
export declare function formatShapedReadResponse(response: ShapedReadResponse): string;
|
|
35
44
|
export declare function formatAnchorReadResponse(response: AnchorReadResponse): string;
|
|
36
45
|
/**
|
|
37
46
|
* Format sheet info list as text
|
|
@@ -51,4 +60,26 @@ export declare function formatOperationResult(operation: string, spreadsheetId:
|
|
|
51
60
|
sheetTitle?: string;
|
|
52
61
|
warnings?: SuspiciousWriteWarning[];
|
|
53
62
|
}): string;
|
|
63
|
+
/**
|
|
64
|
+
* Result of list_workspace_spreadsheet_sheets: header + one line per sheet,
|
|
65
|
+
* enveloped (spreadsheet and sheet titles are authored in Google).
|
|
66
|
+
*/
|
|
67
|
+
export declare function formatSheetListResultAsText(response: SpreadsheetResponse): string;
|
|
68
|
+
/**
|
|
69
|
+
* Result of add_workspace_spreadsheet_sheet (title enveloped).
|
|
70
|
+
*/
|
|
71
|
+
export declare function formatSheetAddedAsText(spreadsheetId: string, sheet: SheetInfo): string;
|
|
72
|
+
/**
|
|
73
|
+
* Result of duplicate_workspace_spreadsheet_sheet (title enveloped).
|
|
74
|
+
*/
|
|
75
|
+
export declare function formatSheetDuplicatedAsText(data: SheetDuplicateResponse): string;
|
|
76
|
+
/**
|
|
77
|
+
* Result of update_workspace_spreadsheet_sheet (title enveloped).
|
|
78
|
+
*/
|
|
79
|
+
export declare function formatSheetUpdatedAsText(data: SheetUpdateResponse): string;
|
|
80
|
+
/**
|
|
81
|
+
* Result of insert_workspace_spreadsheet_dimension: the inserted range in A1
|
|
82
|
+
* notation and what moved (sheet title enveloped).
|
|
83
|
+
*/
|
|
84
|
+
export declare function formatDimensionInsertedAsText(data: DimensionInsertResponse): string;
|
|
54
85
|
//# sourceMappingURL=formatters.d.ts.map
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
* Utilities for formatting Google Sheets content and parsing URLs.
|
|
3
3
|
*/
|
|
4
4
|
import { wrapUntrustedContent } from '../../utils/untrusted-content.js';
|
|
5
|
+
import { firstRowOfA1 } from './a1Utils.js';
|
|
5
6
|
/**
|
|
6
7
|
* Construct a Google Sheets URL from spreadsheet ID
|
|
7
8
|
*/
|
|
@@ -73,6 +74,7 @@ export function formatValuesAsTable(values, options) {
|
|
|
73
74
|
}
|
|
74
75
|
const maxColWidth = options?.maxColWidth ?? 30;
|
|
75
76
|
const includeRowNumbers = options?.includeRowNumbers ?? true;
|
|
77
|
+
const firstRowNumber = options?.firstRowNumber ?? 1;
|
|
76
78
|
// Find the maximum width for each column
|
|
77
79
|
const colWidths = [];
|
|
78
80
|
const numCols = Math.max(...values.map(row => row.length));
|
|
@@ -86,14 +88,14 @@ export function formatValuesAsTable(values, options) {
|
|
|
86
88
|
colWidths.push(maxWidth || 1);
|
|
87
89
|
}
|
|
88
90
|
// Calculate row number width
|
|
89
|
-
const rowNumWidth = includeRowNumbers ? String(values.length).length + 1 : 0;
|
|
91
|
+
const rowNumWidth = includeRowNumbers ? String(firstRowNumber + values.length - 1).length + 1 : 0;
|
|
90
92
|
// Build the table
|
|
91
93
|
const lines = [];
|
|
92
94
|
for (let rowIdx = 0; rowIdx < values.length; rowIdx++) {
|
|
93
95
|
const row = values[rowIdx];
|
|
94
96
|
const cells = [];
|
|
95
97
|
if (includeRowNumbers) {
|
|
96
|
-
cells.push(String(
|
|
98
|
+
cells.push(String(firstRowNumber + rowIdx).padStart(rowNumWidth - 1) + '|');
|
|
97
99
|
}
|
|
98
100
|
for (let col = 0; col < numCols; col++) {
|
|
99
101
|
const cellValue = row[col];
|
|
@@ -125,7 +127,17 @@ function formatAnchorRows(rows, startRow) {
|
|
|
125
127
|
]);
|
|
126
128
|
return formatValuesAsTable(tableRows, { includeRowNumbers: false });
|
|
127
129
|
}
|
|
128
|
-
|
|
130
|
+
/**
|
|
131
|
+
* Sheet row number to show for the first row of values read from `range`.
|
|
132
|
+
* Values grouped by COLUMNS, or a range that can't be parsed, are numbered from 1.
|
|
133
|
+
*/
|
|
134
|
+
export function firstSheetRowNumber(range, majorDimension) {
|
|
135
|
+
if (majorDimension === 'COLUMNS') {
|
|
136
|
+
return 1;
|
|
137
|
+
}
|
|
138
|
+
return firstRowOfA1(range) ?? 1;
|
|
139
|
+
}
|
|
140
|
+
export function formatShapedReadResponse(response, options) {
|
|
129
141
|
const lines = [
|
|
130
142
|
`Range: ${response.range}`,
|
|
131
143
|
`Rows: ${response.rowCount}, Columns: ${response.columnCount}`,
|
|
@@ -139,7 +151,9 @@ export function formatShapedReadResponse(response) {
|
|
|
139
151
|
}
|
|
140
152
|
lines.push('---');
|
|
141
153
|
const tableRows = response.cells.map((row) => row.map((cell) => formatShapedCell(cell)));
|
|
142
|
-
lines.push(formatValuesAsTable(tableRows
|
|
154
|
+
lines.push(formatValuesAsTable(tableRows, {
|
|
155
|
+
firstRowNumber: firstSheetRowNumber(response.range, options?.majorDimension),
|
|
156
|
+
}));
|
|
143
157
|
if (response.warnings && response.warnings.length > 0) {
|
|
144
158
|
lines.push('');
|
|
145
159
|
lines.push('Warnings:');
|
|
@@ -233,7 +247,7 @@ export function formatSpreadsheetAsText(response) {
|
|
|
233
247
|
parts.push(''); // Add blank line separator
|
|
234
248
|
parts.push('Data:');
|
|
235
249
|
}
|
|
236
|
-
parts.push(formatValuesAsTable(response.values));
|
|
250
|
+
parts.push(formatValuesAsTable(response.values, { firstRowNumber: firstSheetRowNumber(response.valuesRange) }));
|
|
237
251
|
}
|
|
238
252
|
return wrapUntrustedContent(parts.join('\n'), `google-workspace:sheets:spreadsheet/${response.spreadsheetId}`);
|
|
239
253
|
}
|
|
@@ -267,4 +281,69 @@ export function formatOperationResult(operation, spreadsheetId, details) {
|
|
|
267
281
|
}
|
|
268
282
|
return lines.join('\n');
|
|
269
283
|
}
|
|
284
|
+
function spreadsheetSource(spreadsheetId) {
|
|
285
|
+
return `google-workspace:sheets:spreadsheet/${spreadsheetId}`;
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* Result of list_workspace_spreadsheet_sheets: header + one line per sheet,
|
|
289
|
+
* enveloped (spreadsheet and sheet titles are authored in Google).
|
|
290
|
+
*/
|
|
291
|
+
export function formatSheetListResultAsText(response) {
|
|
292
|
+
const header = `Spreadsheet: ${response.title}\nURL: ${response.spreadsheetUrl}\n---\n`;
|
|
293
|
+
return wrapUntrustedContent(header + formatSheetsListAsText(response.sheets || []), spreadsheetSource(response.spreadsheetId));
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* Result of add_workspace_spreadsheet_sheet (title enveloped).
|
|
297
|
+
*/
|
|
298
|
+
export function formatSheetAddedAsText(spreadsheetId, sheet) {
|
|
299
|
+
const text = formatOperationResult('Add sheet', spreadsheetId, { sheetTitle: sheet.title }) + `\nSheet ID: ${sheet.sheetId}`;
|
|
300
|
+
return wrapUntrustedContent(text, spreadsheetSource(spreadsheetId));
|
|
301
|
+
}
|
|
302
|
+
function sheetPositionMismatch(actual, requested) {
|
|
303
|
+
return actual !== requested
|
|
304
|
+
? `WARNING: the requested position was ${requested}, but the spreadsheet reports position ${actual}. Check list_workspace_spreadsheet_sheets before going on.`
|
|
305
|
+
: undefined;
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* Result of duplicate_workspace_spreadsheet_sheet (title enveloped).
|
|
309
|
+
*/
|
|
310
|
+
export function formatSheetDuplicatedAsText(data) {
|
|
311
|
+
const lines = [
|
|
312
|
+
`Duplicated sheet ${data.sourceSheetId} as "${data.sheet.title}" [sheetId: ${data.sheet.sheetId}] at position ${data.sheet.index} (0 = first).`,
|
|
313
|
+
];
|
|
314
|
+
const mismatch = sheetPositionMismatch(data.sheet.index, data.requestedPosition);
|
|
315
|
+
if (mismatch)
|
|
316
|
+
lines.push(mismatch);
|
|
317
|
+
return wrapUntrustedContent(lines.join('\n'), spreadsheetSource(data.spreadsheetId));
|
|
318
|
+
}
|
|
319
|
+
/**
|
|
320
|
+
* Result of update_workspace_spreadsheet_sheet (title enveloped).
|
|
321
|
+
*/
|
|
322
|
+
export function formatSheetUpdatedAsText(data) {
|
|
323
|
+
if (!data.changed) {
|
|
324
|
+
return wrapUntrustedContent(`No change: sheet "${data.sheet.title}" [sheetId: ${data.sheet.sheetId}] already has that title and position (${data.sheet.index}, 0 = first).`, spreadsheetSource(data.spreadsheetId));
|
|
325
|
+
}
|
|
326
|
+
const lines = [
|
|
327
|
+
`Sheet updated: "${data.sheet.title}" [sheetId: ${data.sheet.sheetId}] at position ${data.sheet.index} (0 = first).`,
|
|
328
|
+
];
|
|
329
|
+
const mismatch = sheetPositionMismatch(data.sheet.index, data.requestedPosition);
|
|
330
|
+
if (mismatch)
|
|
331
|
+
lines.push(mismatch);
|
|
332
|
+
return wrapUntrustedContent(lines.join('\n'), spreadsheetSource(data.spreadsheetId));
|
|
333
|
+
}
|
|
334
|
+
/**
|
|
335
|
+
* Result of insert_workspace_spreadsheet_dimension: the inserted range in A1
|
|
336
|
+
* notation and what moved (sheet title enveloped).
|
|
337
|
+
*/
|
|
338
|
+
export function formatDimensionInsertedAsText(data) {
|
|
339
|
+
const isRows = data.dimension === 'ROWS';
|
|
340
|
+
const unit = isRows ? 'row' : 'column';
|
|
341
|
+
const units = `${data.count} ${unit}${data.count !== 1 ? 's' : ''}`;
|
|
342
|
+
const side = data.inheritFromBefore ? 'before' : 'after';
|
|
343
|
+
const lines = [
|
|
344
|
+
`Inserted ${units} in "${data.sheet.title}" [sheetId: ${data.sheet.sheetId}]: ${data.a1Range}, formatted like the ${unit} ${side} them.`,
|
|
345
|
+
`Cells that were at ${unit} index ${data.startIndex} (0-based) and beyond moved ${isRows ? 'down' : 'right'} by ${data.count}; formulas that refer to them were adjusted by Google. Re-read before writing to cell addresses noted earlier.`,
|
|
346
|
+
];
|
|
347
|
+
return wrapUntrustedContent(lines.join('\n'), spreadsheetSource(data.spreadsheetId));
|
|
348
|
+
}
|
|
270
349
|
//# sourceMappingURL=formatters.js.map
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { sheets_v4 } from 'googleapis';
|
|
2
2
|
import { BaseGoogleService } from '../../services/base/BaseGoogleService.js';
|
|
3
|
-
import { SheetsOperationResult, ReadSpreadsheetOptions, ReadValuesOptions, CreateSpreadsheetOptions, AppendValuesOptions, UpdateValuesOptions, ClearValuesOptions, AddSheetOptions, DeleteSheetOptions, ListSheetsOptions, BatchGetValuesOptions, BatchUpdateValuesOptions, BatchOperationResult, FindReplaceOptions, FindReplaceResult, FormatCellsOptions, FormatResult } from './types.js';
|
|
3
|
+
import { SheetsOperationResult, ReadSpreadsheetOptions, ReadValuesOptions, CreateSpreadsheetOptions, AppendValuesOptions, UpdateValuesOptions, ClearValuesOptions, AddSheetOptions, DeleteSheetOptions, ListSheetsOptions, BatchGetValuesOptions, BatchUpdateValuesOptions, BatchOperationResult, FindReplaceOptions, FindReplaceResult, FormatCellsOptions, FormatResult, DuplicateSheetOptions, UpdateSheetOptions, InsertDimensionOptions, SheetDuplicateResponse, SheetUpdateResponse, DimensionInsertResponse, SheetTabOperationResult } from './types.js';
|
|
4
|
+
/** Most rows/columns insert_workspace_spreadsheet_dimension adds in one call. */
|
|
5
|
+
export declare const MAX_INSERT_DIMENSION_COUNT = 100;
|
|
4
6
|
export declare class SheetsService extends BaseGoogleService<sheets_v4.Sheets> {
|
|
5
7
|
private initialized;
|
|
6
8
|
constructor();
|
|
@@ -81,6 +83,29 @@ export declare class SheetsService extends BaseGoogleService<sheets_v4.Sheets> {
|
|
|
81
83
|
* List all sheets in a spreadsheet
|
|
82
84
|
*/
|
|
83
85
|
listSheets(email: string, options: ListSheetsOptions): Promise<SheetsOperationResult>;
|
|
86
|
+
/**
|
|
87
|
+
* Duplicate a sheet (tab) inside the same spreadsheet. Google copies values,
|
|
88
|
+
* formulas, formatting, merges and validation. `position` is the 0-based
|
|
89
|
+
* position of the copy; it defaults to right after the source.
|
|
90
|
+
*/
|
|
91
|
+
duplicateSheet(email: string, options: DuplicateSheetOptions): Promise<SheetTabOperationResult<SheetDuplicateResponse>>;
|
|
92
|
+
/**
|
|
93
|
+
* Rename and/or reorder a sheet. `position` is the 0-based position the sheet
|
|
94
|
+
* should end up at; the API's before-removal index is computed here. A call
|
|
95
|
+
* that changes nothing makes no write. Reports the actual title and position
|
|
96
|
+
* after the write.
|
|
97
|
+
*/
|
|
98
|
+
updateSheet(email: string, options: UpdateSheetOptions): Promise<SheetTabOperationResult<SheetUpdateResponse>>;
|
|
99
|
+
/**
|
|
100
|
+
* Insert empty rows or columns into a sheet. Cells at and after `startIndex`
|
|
101
|
+
* move down (rows) or right (columns); Google adjusts formulas that refer to
|
|
102
|
+
* them. The new rows/columns copy the formatting of the row/column before
|
|
103
|
+
* them (default) or after them.
|
|
104
|
+
*/
|
|
105
|
+
insertDimension(email: string, options: InsertDimensionOptions): Promise<SheetTabOperationResult<DimensionInsertResponse>>;
|
|
106
|
+
private getWriteClient;
|
|
107
|
+
/** Every sheet's properties, in tab order. */
|
|
108
|
+
private readSheetList;
|
|
84
109
|
/**
|
|
85
110
|
* Batch read values from multiple ranges in a single API call
|
|
86
111
|
*/
|