@n24q02m/workspace 0.9.0-beta.1 → 0.9.1-beta.1
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/NOTICE +11 -5
- package/bin/cli.mjs +52 -52
- package/build/src/cli/tools.integration.test.js +26 -5
- package/build/src/cli/tools.integration.test.js.map +1 -1
- package/build/src/docs/docs.md +5 -1
- package/build/src/docs/overview.md +14 -0
- package/build/src/services/FormsService.d.ts +4 -4
- package/build/src/services/FormsService.js +4 -4
- package/build/src/services/FormsService.test.js +3 -3
- package/build/src/services/FormsService.test.js.map +1 -1
- package/build/src/tools/domains/error-payload.test.d.ts +2 -0
- package/build/src/tools/domains/error-payload.test.d.ts.map +1 -0
- package/build/src/tools/domains/error-payload.test.js +94 -0
- package/build/src/tools/domains/error-payload.test.js.map +1 -0
- package/build/src/tools/domains/factory.d.ts.map +1 -1
- package/build/src/tools/domains/factory.js +27 -1
- package/build/src/tools/domains/factory.js.map +1 -1
- package/build/src/tools/domains/factory.test.js +41 -0
- package/build/src/tools/domains/factory.test.js.map +1 -1
- package/build/src/vendored/services/CalendarService.d.ts.map +1 -1
- package/build/src/vendored/services/CalendarService.js +19 -15
- package/build/src/vendored/services/CalendarService.js.map +1 -1
- package/build/src/vendored/services/CalendarService.test.d.ts +2 -0
- package/build/src/vendored/services/CalendarService.test.d.ts.map +1 -0
- package/build/src/vendored/services/CalendarService.test.js +1227 -0
- package/build/src/vendored/services/CalendarService.test.js.map +1 -0
- package/build/src/vendored/services/CalendarValidation.test.d.ts +2 -0
- package/build/src/vendored/services/CalendarValidation.test.d.ts.map +1 -0
- package/build/src/vendored/services/CalendarValidation.test.js +312 -0
- package/build/src/vendored/services/CalendarValidation.test.js.map +1 -0
- package/build/src/vendored/services/ChatService.test.d.ts +2 -0
- package/build/src/vendored/services/ChatService.test.d.ts.map +1 -0
- package/build/src/vendored/services/ChatService.test.js +505 -0
- package/build/src/vendored/services/ChatService.test.js.map +1 -0
- package/build/src/vendored/services/DocsService.d.ts.map +1 -1
- package/build/src/vendored/services/DocsService.js +6 -1
- package/build/src/vendored/services/DocsService.js.map +1 -1
- package/build/src/vendored/services/DocsService.test.js +943 -5
- package/build/src/vendored/services/DocsService.test.js.map +1 -1
- package/build/src/vendored/services/DriveService.test.js +797 -9
- package/build/src/vendored/services/DriveService.test.js.map +1 -1
- package/build/src/vendored/services/SheetsService.test.js +328 -0
- package/build/src/vendored/services/SheetsService.test.js.map +1 -1
- package/build/src/vendored/utils/MimeHelper.test.js +329 -0
- package/build/src/vendored/utils/MimeHelper.test.js.map +1 -1
- package/build/src/vendored/utils/validation.d.ts.map +1 -1
- package/build/src/vendored/utils/validation.js +10 -1
- package/build/src/vendored/utils/validation.js.map +1 -1
- package/build/src/vendored/utils/validation.test.d.ts +2 -0
- package/build/src/vendored/utils/validation.test.d.ts.map +1 -0
- package/build/src/vendored/utils/validation.test.js +260 -0
- package/build/src/vendored/utils/validation.test.js.map +1 -0
- package/build/tsconfig.tsbuildinfo +1 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
|
@@ -1,13 +1,34 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
1
3
|
import path from 'node:path';
|
|
2
|
-
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
3
|
-
const { filesGet, filesList, mkdir, writeFile } = vi.hoisted(() =>
|
|
4
|
-
filesGet
|
|
5
|
-
filesList
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
4
|
+
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
5
|
+
const { filesGet, filesList, filesCreate, filesUpdate, commentsList, driveFactory, getAuthenticatedClient, authClient, projectRoot, mkdir, writeFile } = vi.hoisted(() => {
|
|
6
|
+
const filesGet = vi.fn();
|
|
7
|
+
const filesList = vi.fn();
|
|
8
|
+
const filesCreate = vi.fn();
|
|
9
|
+
const filesUpdate = vi.fn();
|
|
10
|
+
const commentsList = vi.fn();
|
|
11
|
+
const authClient = { tag: 'oauth-client' };
|
|
12
|
+
return {
|
|
13
|
+
filesGet,
|
|
14
|
+
filesList,
|
|
15
|
+
filesCreate,
|
|
16
|
+
filesUpdate,
|
|
17
|
+
commentsList,
|
|
18
|
+
authClient,
|
|
19
|
+
driveFactory: vi.fn(() => ({
|
|
20
|
+
files: { get: filesGet, list: filesList, create: filesCreate, update: filesUpdate },
|
|
21
|
+
comments: { list: commentsList }
|
|
22
|
+
})),
|
|
23
|
+
getAuthenticatedClient: vi.fn(async () => authClient),
|
|
24
|
+
// `undefined` keeps the real PROJECT_ROOT; the real-filesystem tests point it at a mkdtemp directory.
|
|
25
|
+
projectRoot: { override: undefined },
|
|
26
|
+
mkdir: vi.fn(),
|
|
27
|
+
writeFile: vi.fn()
|
|
28
|
+
};
|
|
29
|
+
});
|
|
9
30
|
vi.mock('../../auth/credential-state.js', () => ({
|
|
10
|
-
getAuth: () => ({ getAuthenticatedClient
|
|
31
|
+
getAuth: () => ({ getAuthenticatedClient })
|
|
11
32
|
}));
|
|
12
33
|
vi.mock('node:fs', async () => {
|
|
13
34
|
const actual = await vi.importActual('node:fs');
|
|
@@ -16,13 +37,41 @@ vi.mock('node:fs', async () => {
|
|
|
16
37
|
promises: { ...actual.promises, mkdir, writeFile }
|
|
17
38
|
};
|
|
18
39
|
});
|
|
40
|
+
vi.mock('../utils/paths.js', async (importOriginal) => {
|
|
41
|
+
const actual = await importOriginal();
|
|
42
|
+
return {
|
|
43
|
+
...actual,
|
|
44
|
+
get PROJECT_ROOT() {
|
|
45
|
+
return projectRoot.override ?? actual.PROJECT_ROOT;
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
});
|
|
19
49
|
vi.mock('googleapis', () => ({
|
|
20
|
-
google: { drive:
|
|
50
|
+
google: { drive: driveFactory }
|
|
21
51
|
}));
|
|
22
52
|
import { AuthManager } from '../auth/AuthManager.js';
|
|
23
53
|
import { PROJECT_ROOT } from '../utils/paths.js';
|
|
24
54
|
import { DriveService } from './DriveService.js';
|
|
25
55
|
const fileId = 'local-contract-file-id-12345';
|
|
56
|
+
const textOf = (result) => result.content[0].text;
|
|
57
|
+
const jsonOf = (result) => JSON.parse(textOf(result));
|
|
58
|
+
const isErrorOf = (result) => result.isError;
|
|
59
|
+
const newService = () => new DriveService(new AuthManager(['scope']));
|
|
60
|
+
function resetMocks() {
|
|
61
|
+
for (const mock of [
|
|
62
|
+
filesGet,
|
|
63
|
+
filesList,
|
|
64
|
+
filesCreate,
|
|
65
|
+
filesUpdate,
|
|
66
|
+
commentsList,
|
|
67
|
+
driveFactory,
|
|
68
|
+
getAuthenticatedClient,
|
|
69
|
+
mkdir,
|
|
70
|
+
writeFile
|
|
71
|
+
]) {
|
|
72
|
+
mock.mockReset();
|
|
73
|
+
}
|
|
74
|
+
}
|
|
26
75
|
describe('DriveService downloadFile local filesystem contract', () => {
|
|
27
76
|
beforeEach(() => {
|
|
28
77
|
filesGet.mockReset();
|
|
@@ -112,4 +161,743 @@ describe('DriveService search URL hostname validation', () => {
|
|
|
112
161
|
expect(filesList).not.toHaveBeenCalled();
|
|
113
162
|
});
|
|
114
163
|
});
|
|
164
|
+
const FOLDER_MIME = 'application/vnd.google-apps.folder';
|
|
165
|
+
const LIST_FIELDS = 'nextPageToken, files(id, name, modifiedTime, viewedByMeTime, mimeType, parents)';
|
|
166
|
+
const GET_FIELDS = 'id, name, modifiedTime, viewedByMeTime, mimeType, parents';
|
|
167
|
+
// Exactly MIN_DRIVE_ID_LENGTH (25) characters.
|
|
168
|
+
const DRIVE_ID = 'abcdefghijklmnopqrstuvwxy';
|
|
169
|
+
const URL_ID = 'url-file-id-1234567890abcde';
|
|
170
|
+
describe('DriveService client construction', () => {
|
|
171
|
+
beforeEach(resetMocks);
|
|
172
|
+
it('builds a v3 client from the authenticated OAuth client with the shared retry and timeout options', async () => {
|
|
173
|
+
getAuthenticatedClient.mockResolvedValue(authClient);
|
|
174
|
+
filesList.mockResolvedValue({ data: { files: [] } });
|
|
175
|
+
await newService().findFolder({ folderName: 'Reports' });
|
|
176
|
+
expect(driveFactory).toHaveBeenCalledWith(expect.objectContaining({
|
|
177
|
+
version: 'v3',
|
|
178
|
+
auth: authClient,
|
|
179
|
+
timeout: 30000,
|
|
180
|
+
retryConfig: expect.objectContaining({ retry: 3, noResponseRetries: 3 })
|
|
181
|
+
}));
|
|
182
|
+
});
|
|
183
|
+
it('reports an authentication failure as an error result instead of throwing', async () => {
|
|
184
|
+
getAuthenticatedClient.mockRejectedValue(new Error('token revoked'));
|
|
185
|
+
const result = await newService().findFolder({ folderName: 'Reports' });
|
|
186
|
+
expect(isErrorOf(result)).toBe(true);
|
|
187
|
+
expect(jsonOf(result)).toEqual({ error: 'token revoked' });
|
|
188
|
+
expect(filesList).not.toHaveBeenCalled();
|
|
189
|
+
});
|
|
190
|
+
});
|
|
191
|
+
describe('DriveService.findFolder', () => {
|
|
192
|
+
beforeEach(() => {
|
|
193
|
+
resetMocks();
|
|
194
|
+
});
|
|
195
|
+
it('searches folders by name with quote and backslash escaping and returns the matches', async () => {
|
|
196
|
+
const folders = [{ id: 'folder-1', name: "O'Brien\\docs" }];
|
|
197
|
+
filesList.mockResolvedValue({ data: { files: folders } });
|
|
198
|
+
const result = await newService().findFolder({ folderName: "O'Brien\\docs" });
|
|
199
|
+
expect(filesList).toHaveBeenCalledWith({
|
|
200
|
+
q: String.raw `mimeType='application/vnd.google-apps.folder' and name = 'O\'Brien\\docs'`,
|
|
201
|
+
fields: 'files(id, name)',
|
|
202
|
+
spaces: 'drive',
|
|
203
|
+
supportsAllDrives: true,
|
|
204
|
+
includeItemsFromAllDrives: true
|
|
205
|
+
});
|
|
206
|
+
expect(jsonOf(result)).toEqual(folders);
|
|
207
|
+
expect(isErrorOf(result)).toBeUndefined();
|
|
208
|
+
});
|
|
209
|
+
it('returns an empty list when the API response has no files field', async () => {
|
|
210
|
+
filesList.mockResolvedValue({ data: {} });
|
|
211
|
+
const result = await newService().findFolder({ folderName: 'Missing' });
|
|
212
|
+
expect(jsonOf(result)).toEqual([]);
|
|
213
|
+
});
|
|
214
|
+
it('returns the API error message as an error result', async () => {
|
|
215
|
+
filesList.mockRejectedValue(new Error('quota exceeded'));
|
|
216
|
+
const result = await newService().findFolder({ folderName: 'Reports' });
|
|
217
|
+
expect(isErrorOf(result)).toBe(true);
|
|
218
|
+
expect(jsonOf(result)).toEqual({ error: 'quota exceeded' });
|
|
219
|
+
});
|
|
220
|
+
it('stringifies a non-Error rejection into the error result', async () => {
|
|
221
|
+
filesList.mockRejectedValue('plain failure');
|
|
222
|
+
const result = await newService().findFolder({ folderName: 'Reports' });
|
|
223
|
+
expect(isErrorOf(result)).toBe(true);
|
|
224
|
+
expect(jsonOf(result)).toEqual({ error: 'plain failure' });
|
|
225
|
+
});
|
|
226
|
+
});
|
|
227
|
+
describe('DriveService.createFolder', () => {
|
|
228
|
+
beforeEach(() => {
|
|
229
|
+
resetMocks();
|
|
230
|
+
});
|
|
231
|
+
it('creates a top-level folder without a parents field', async () => {
|
|
232
|
+
filesCreate.mockResolvedValue({ data: { id: 'new-1', name: 'Reports', extra: 'ignored' } });
|
|
233
|
+
const result = await newService().createFolder({ name: 'Reports' });
|
|
234
|
+
expect(filesCreate).toHaveBeenCalledWith({
|
|
235
|
+
requestBody: { name: 'Reports', mimeType: FOLDER_MIME },
|
|
236
|
+
fields: 'id, name',
|
|
237
|
+
supportsAllDrives: true
|
|
238
|
+
});
|
|
239
|
+
expect(filesCreate.mock.calls[0][0].requestBody).not.toHaveProperty('parents');
|
|
240
|
+
expect(jsonOf(result)).toEqual({ id: 'new-1', name: 'Reports' });
|
|
241
|
+
});
|
|
242
|
+
it('places the folder under the given parent', async () => {
|
|
243
|
+
filesCreate.mockResolvedValue({ data: { id: 'new-2', name: 'Q4' } });
|
|
244
|
+
const result = await newService().createFolder({ name: 'Q4', parentId: 'parent-9' });
|
|
245
|
+
expect(filesCreate).toHaveBeenCalledWith({
|
|
246
|
+
requestBody: { name: 'Q4', mimeType: FOLDER_MIME, parents: ['parent-9'] },
|
|
247
|
+
fields: 'id, name',
|
|
248
|
+
supportsAllDrives: true
|
|
249
|
+
});
|
|
250
|
+
expect(jsonOf(result)).toEqual({ id: 'new-2', name: 'Q4' });
|
|
251
|
+
});
|
|
252
|
+
it('returns the API error message when creation fails', async () => {
|
|
253
|
+
filesCreate.mockRejectedValue(new Error('insufficient permissions'));
|
|
254
|
+
const result = await newService().createFolder({ name: 'Reports' });
|
|
255
|
+
expect(jsonOf(result)).toEqual({ error: 'insufficient permissions' });
|
|
256
|
+
});
|
|
257
|
+
it('stringifies a non-Error rejection when creation fails', async () => {
|
|
258
|
+
filesCreate.mockRejectedValue(503);
|
|
259
|
+
const result = await newService().createFolder({ name: 'Reports' });
|
|
260
|
+
expect(jsonOf(result)).toEqual({ error: '503' });
|
|
261
|
+
});
|
|
262
|
+
});
|
|
263
|
+
describe('DriveService.search query building', () => {
|
|
264
|
+
beforeEach(() => {
|
|
265
|
+
resetMocks();
|
|
266
|
+
filesList.mockResolvedValue({ data: { files: [{ id: 'f1', name: 'one' }] } });
|
|
267
|
+
});
|
|
268
|
+
const listedQuery = () => filesList.mock.calls[0][0].q;
|
|
269
|
+
it('lists with the default page size and no filter when called without a query', async () => {
|
|
270
|
+
const result = await newService().search({});
|
|
271
|
+
expect(filesList).toHaveBeenCalledWith({
|
|
272
|
+
q: undefined,
|
|
273
|
+
pageSize: 10,
|
|
274
|
+
pageToken: undefined,
|
|
275
|
+
corpus: undefined,
|
|
276
|
+
fields: LIST_FIELDS,
|
|
277
|
+
supportsAllDrives: true,
|
|
278
|
+
includeItemsFromAllDrives: true
|
|
279
|
+
});
|
|
280
|
+
expect(jsonOf(result)).toEqual({ files: [{ id: 'f1', name: 'one' }] });
|
|
281
|
+
expect(filesGet).not.toHaveBeenCalled();
|
|
282
|
+
});
|
|
283
|
+
it('forwards pageSize, pageToken and corpus to the list call', async () => {
|
|
284
|
+
await newService().search({ query: 'trashed = false', pageSize: 3, pageToken: 'tok-1', corpus: 'domain' });
|
|
285
|
+
expect(filesList).toHaveBeenCalledWith(expect.objectContaining({ q: 'trashed = false', pageSize: 3, pageToken: 'tok-1', corpus: 'domain' }));
|
|
286
|
+
});
|
|
287
|
+
it.each([
|
|
288
|
+
["title: 'My Report'", "name contains 'My Report'"],
|
|
289
|
+
['title:"My Report"', "name contains 'My Report'"],
|
|
290
|
+
[' title: Plain Name ', "name contains 'Plain Name'"],
|
|
291
|
+
["title: it's here", "name contains 'it\\'s here'"],
|
|
292
|
+
['title:\'mismatched"', "name contains '\\'mismatched\"'"]
|
|
293
|
+
])('turns the title query %j into a name-contains query', async (query, expected) => {
|
|
294
|
+
await newService().search({ query });
|
|
295
|
+
expect(listedQuery()).toBe(expected);
|
|
296
|
+
});
|
|
297
|
+
it('lists the contents of a folder when the query is a bare Drive ID', async () => {
|
|
298
|
+
await newService().search({ query: ` ${DRIVE_ID} ` });
|
|
299
|
+
expect(listedQuery()).toBe(`'${DRIVE_ID}' in parents`);
|
|
300
|
+
});
|
|
301
|
+
it('treats a 24-character token as free text, not as a Drive ID', async () => {
|
|
302
|
+
await newService().search({ query: DRIVE_ID.slice(0, 24) });
|
|
303
|
+
expect(listedQuery()).toBe(`fullText contains '${DRIVE_ID.slice(0, 24)}'`);
|
|
304
|
+
});
|
|
305
|
+
it.each([
|
|
306
|
+
"name contains 'budget'",
|
|
307
|
+
"mimeType = 'application/pdf' and trashed = false",
|
|
308
|
+
"'a' in parents or 'b' in parents",
|
|
309
|
+
'starred not trashed',
|
|
310
|
+
'trashed=false'
|
|
311
|
+
])('passes the Drive query %j through unchanged', async (query) => {
|
|
312
|
+
await newService().search({ query });
|
|
313
|
+
expect(listedQuery()).toBe(query);
|
|
314
|
+
});
|
|
315
|
+
it('wraps free text in a full-text query and escapes quotes and backslashes', async () => {
|
|
316
|
+
await newService().search({ query: " it's a C:\\temp plan " });
|
|
317
|
+
expect(listedQuery()).toBe(String.raw `fullText contains 'it\'s a C:\\temp plan'`);
|
|
318
|
+
});
|
|
319
|
+
it('appends the shared-with-me filter to an existing query', async () => {
|
|
320
|
+
await newService().search({ query: 'budget', sharedWithMe: true });
|
|
321
|
+
expect(listedQuery()).toBe("fullText contains 'budget' and sharedWithMe");
|
|
322
|
+
});
|
|
323
|
+
it('uses the shared-with-me filter alone when there is no query', async () => {
|
|
324
|
+
await newService().search({ sharedWithMe: true });
|
|
325
|
+
expect(listedQuery()).toBe('sharedWithMe');
|
|
326
|
+
});
|
|
327
|
+
it('keeps only never-viewed files when unreadOnly is set', async () => {
|
|
328
|
+
filesList.mockResolvedValue({
|
|
329
|
+
data: {
|
|
330
|
+
files: [
|
|
331
|
+
{ id: 'seen', name: 'seen', viewedByMeTime: '2025-01-01T00:00:00Z' },
|
|
332
|
+
{ id: 'unseen', name: 'unseen' }
|
|
333
|
+
]
|
|
334
|
+
}
|
|
335
|
+
});
|
|
336
|
+
const result = await newService().search({ unreadOnly: true, corpus: 'user' });
|
|
337
|
+
expect(jsonOf(result).files).toEqual([{ id: 'unseen', name: 'unseen' }]);
|
|
338
|
+
});
|
|
339
|
+
it('returns every file when unreadOnly is not set', async () => {
|
|
340
|
+
filesList.mockResolvedValue({
|
|
341
|
+
data: { files: [{ id: 'seen', viewedByMeTime: '2025-01-01T00:00:00Z' }, { id: 'unseen' }] }
|
|
342
|
+
});
|
|
343
|
+
const result = await newService().search({});
|
|
344
|
+
expect(jsonOf(result).files.map((file) => file.id)).toEqual(['seen', 'unseen']);
|
|
345
|
+
});
|
|
346
|
+
it('returns the next page cursor so the caller can continue', async () => {
|
|
347
|
+
filesList.mockResolvedValue({ data: { files: [{ id: 'f1' }], nextPageToken: 'cursor-2' } });
|
|
348
|
+
const result = await newService().search({ query: 'budget' });
|
|
349
|
+
expect(jsonOf(result)).toEqual({ files: [{ id: 'f1' }], nextPageToken: 'cursor-2' });
|
|
350
|
+
});
|
|
351
|
+
it('returns an empty file list when the API response has no files field', async () => {
|
|
352
|
+
filesList.mockResolvedValue({ data: {} });
|
|
353
|
+
const result = await newService().search({ query: 'budget' });
|
|
354
|
+
expect(jsonOf(result)).toEqual({ files: [] });
|
|
355
|
+
});
|
|
356
|
+
it('returns the API error message when listing fails', async () => {
|
|
357
|
+
filesList.mockRejectedValue(new Error('rate limited'));
|
|
358
|
+
const result = await newService().search({ query: 'budget' });
|
|
359
|
+
expect(jsonOf(result)).toEqual({ error: 'rate limited' });
|
|
360
|
+
});
|
|
361
|
+
it('stringifies a non-Error rejection when listing fails', async () => {
|
|
362
|
+
filesList.mockRejectedValue('offline');
|
|
363
|
+
const result = await newService().search({ query: 'budget' });
|
|
364
|
+
expect(jsonOf(result)).toEqual({ error: 'offline' });
|
|
365
|
+
});
|
|
366
|
+
});
|
|
367
|
+
describe('DriveService.search Drive URLs', () => {
|
|
368
|
+
beforeEach(() => {
|
|
369
|
+
resetMocks();
|
|
370
|
+
filesList.mockResolvedValue({ data: { files: [] } });
|
|
371
|
+
});
|
|
372
|
+
it.each([
|
|
373
|
+
`https://drive.google.com/drive/folders/${URL_ID}?usp=sharing`,
|
|
374
|
+
`https://drive.google.com/drive/u/0/folders/${URL_ID}`
|
|
375
|
+
])('lists the contents of the folder behind %s without a files.get lookup', async (query) => {
|
|
376
|
+
await newService().search({ query });
|
|
377
|
+
expect(filesGet).not.toHaveBeenCalled();
|
|
378
|
+
expect(filesList).toHaveBeenCalledWith(expect.objectContaining({ q: `'${URL_ID}' in parents` }));
|
|
379
|
+
});
|
|
380
|
+
it('combines a folder URL with the shared-with-me filter', async () => {
|
|
381
|
+
await newService().search({
|
|
382
|
+
query: `https://drive.google.com/drive/folders/${URL_ID}`,
|
|
383
|
+
sharedWithMe: true
|
|
384
|
+
});
|
|
385
|
+
expect(filesList).toHaveBeenCalledWith(expect.objectContaining({ q: `'${URL_ID}' in parents and sharedWithMe` }));
|
|
386
|
+
});
|
|
387
|
+
it.each([
|
|
388
|
+
`https://drive.google.com/file/d/${URL_ID}/view?usp=sharing`,
|
|
389
|
+
`https://docs.google.com/document/d/${URL_ID}/edit`,
|
|
390
|
+
`https://docs.google.com/spreadsheets/d/${URL_ID}/edit#gid=0`,
|
|
391
|
+
`https://docs.google.com/presentation/d/${URL_ID}/edit`,
|
|
392
|
+
`https://docs.google.com/forms/d/${URL_ID}/edit`
|
|
393
|
+
])('fetches the single file behind %s with files.get', async (query) => {
|
|
394
|
+
filesGet.mockResolvedValue({ data: { id: URL_ID, name: 'Target' } });
|
|
395
|
+
const result = await newService().search({ query });
|
|
396
|
+
expect(filesGet).toHaveBeenCalledTimes(1);
|
|
397
|
+
expect(filesGet).toHaveBeenCalledWith({ fileId: URL_ID, fields: GET_FIELDS, supportsAllDrives: true });
|
|
398
|
+
expect(filesList).not.toHaveBeenCalled();
|
|
399
|
+
expect(jsonOf(result)).toEqual({ files: [{ id: URL_ID, name: 'Target' }], nextPageToken: null });
|
|
400
|
+
});
|
|
401
|
+
it('looks up the type of an id= URL and lists the folder when it is a folder', async () => {
|
|
402
|
+
filesGet.mockResolvedValue({ data: { mimeType: FOLDER_MIME } });
|
|
403
|
+
await newService().search({ query: `https://drive.google.com/open?id=${URL_ID}` });
|
|
404
|
+
expect(filesGet).toHaveBeenCalledTimes(1);
|
|
405
|
+
expect(filesGet).toHaveBeenCalledWith({ fileId: URL_ID, fields: 'mimeType', supportsAllDrives: true });
|
|
406
|
+
expect(filesList).toHaveBeenCalledWith(expect.objectContaining({ q: `'${URL_ID}' in parents` }));
|
|
407
|
+
});
|
|
408
|
+
it('fetches the file after an id= URL turns out not to be a folder', async () => {
|
|
409
|
+
filesGet
|
|
410
|
+
.mockResolvedValueOnce({ data: { mimeType: 'application/pdf' } })
|
|
411
|
+
.mockResolvedValueOnce({ data: { id: URL_ID, name: 'Doc' } });
|
|
412
|
+
const result = await newService().search({ query: `https://drive.google.com/open?id=${URL_ID}` });
|
|
413
|
+
expect(filesGet).toHaveBeenNthCalledWith(2, { fileId: URL_ID, fields: GET_FIELDS, supportsAllDrives: true });
|
|
414
|
+
expect(filesList).not.toHaveBeenCalled();
|
|
415
|
+
expect(jsonOf(result)).toEqual({ files: [{ id: URL_ID, name: 'Doc' }], nextPageToken: null });
|
|
416
|
+
});
|
|
417
|
+
it('treats an id= URL as a file when its type lookup fails', async () => {
|
|
418
|
+
filesGet
|
|
419
|
+
.mockRejectedValueOnce(new Error('type lookup failed'))
|
|
420
|
+
.mockResolvedValueOnce({ data: { id: URL_ID, name: 'Doc' } });
|
|
421
|
+
const result = await newService().search({ query: `https://docs.google.com/open?id=${URL_ID}` });
|
|
422
|
+
expect(filesGet).toHaveBeenCalledTimes(2);
|
|
423
|
+
expect(jsonOf(result)).toEqual({ files: [{ id: URL_ID, name: 'Doc' }], nextPageToken: null });
|
|
424
|
+
});
|
|
425
|
+
it('returns the API error message when fetching the file behind a URL fails', async () => {
|
|
426
|
+
filesGet.mockRejectedValue(new Error('File not found'));
|
|
427
|
+
const result = await newService().search({ query: `https://drive.google.com/file/d/${URL_ID}/view` });
|
|
428
|
+
expect(jsonOf(result)).toEqual({ error: 'File not found' });
|
|
429
|
+
expect(filesList).not.toHaveBeenCalled();
|
|
430
|
+
});
|
|
431
|
+
it('stringifies a non-Error rejection when fetching the file behind a URL fails', async () => {
|
|
432
|
+
filesGet.mockRejectedValue('gone');
|
|
433
|
+
const result = await newService().search({ query: `https://drive.google.com/file/d/${URL_ID}/view` });
|
|
434
|
+
expect(jsonOf(result)).toEqual({ error: 'gone' });
|
|
435
|
+
});
|
|
436
|
+
it('rejects a Drive URL that carries no file or folder ID without calling the API', async () => {
|
|
437
|
+
const result = await newService().search({ query: 'https://drive.google.com/drive/my-drive' });
|
|
438
|
+
expect(jsonOf(result)).toEqual({
|
|
439
|
+
error: 'Invalid Drive URL. Please provide a valid Google Drive URL or a search query.',
|
|
440
|
+
details: 'Could not extract file or folder ID from the provided URL.'
|
|
441
|
+
});
|
|
442
|
+
expect(filesGet).not.toHaveBeenCalled();
|
|
443
|
+
expect(filesList).not.toHaveBeenCalled();
|
|
444
|
+
});
|
|
445
|
+
it('searches for text that is not a URL as full text even if it contains a Drive hostname', async () => {
|
|
446
|
+
await newService().search({ query: 'notes about drive.google.com' });
|
|
447
|
+
expect(filesList).toHaveBeenCalledWith(expect.objectContaining({ q: "fullText contains 'notes about drive.google.com'" }));
|
|
448
|
+
expect(filesGet).not.toHaveBeenCalled();
|
|
449
|
+
});
|
|
450
|
+
});
|
|
451
|
+
describe('DriveService.trashFile and renameFile', () => {
|
|
452
|
+
beforeEach(() => {
|
|
453
|
+
resetMocks();
|
|
454
|
+
});
|
|
455
|
+
it('trashes a file by ID and reports it as trashed', async () => {
|
|
456
|
+
filesUpdate.mockResolvedValue({ data: { id: 'doc-1', name: 'Old plan' } });
|
|
457
|
+
const result = await newService().trashFile({ fileId: 'doc-1' });
|
|
458
|
+
expect(filesUpdate).toHaveBeenCalledWith({
|
|
459
|
+
fileId: 'doc-1',
|
|
460
|
+
requestBody: { trashed: true },
|
|
461
|
+
fields: 'id, name',
|
|
462
|
+
supportsAllDrives: true
|
|
463
|
+
});
|
|
464
|
+
expect(jsonOf(result)).toEqual({ id: 'doc-1', name: 'Old plan', trashed: true });
|
|
465
|
+
expect(isErrorOf(result)).toBeUndefined();
|
|
466
|
+
});
|
|
467
|
+
it('extracts the file ID from a Docs URL before trashing', async () => {
|
|
468
|
+
filesUpdate.mockResolvedValue({ data: { id: URL_ID, name: 'Doc' } });
|
|
469
|
+
await newService().trashFile({ fileId: `https://docs.google.com/document/d/${URL_ID}/edit` });
|
|
470
|
+
expect(filesUpdate).toHaveBeenCalledWith(expect.objectContaining({ fileId: URL_ID }));
|
|
471
|
+
});
|
|
472
|
+
it('refuses an invalid file ID without calling the API', async () => {
|
|
473
|
+
const result = await newService().trashFile({ fileId: 'not a valid id!' });
|
|
474
|
+
expect(isErrorOf(result)).toBe(true);
|
|
475
|
+
expect(jsonOf(result)).toEqual({ error: 'Invalid document ID or URL' });
|
|
476
|
+
expect(filesUpdate).not.toHaveBeenCalled();
|
|
477
|
+
});
|
|
478
|
+
it('returns the API error message when trashing fails', async () => {
|
|
479
|
+
filesUpdate.mockRejectedValue(new Error('forbidden'));
|
|
480
|
+
const result = await newService().trashFile({ fileId: 'doc-1' });
|
|
481
|
+
expect(isErrorOf(result)).toBe(true);
|
|
482
|
+
expect(jsonOf(result)).toEqual({ error: 'forbidden' });
|
|
483
|
+
});
|
|
484
|
+
it('renames a file and returns its new name', async () => {
|
|
485
|
+
filesUpdate.mockResolvedValue({ data: { id: 'doc-1', name: 'New name' } });
|
|
486
|
+
const result = await newService().renameFile({ fileId: 'doc-1', newName: 'New name' });
|
|
487
|
+
expect(filesUpdate).toHaveBeenCalledWith({
|
|
488
|
+
fileId: 'doc-1',
|
|
489
|
+
requestBody: { name: 'New name' },
|
|
490
|
+
fields: 'id, name',
|
|
491
|
+
supportsAllDrives: true
|
|
492
|
+
});
|
|
493
|
+
expect(jsonOf(result)).toEqual({ id: 'doc-1', name: 'New name' });
|
|
494
|
+
});
|
|
495
|
+
it('extracts the file ID from a URL before renaming', async () => {
|
|
496
|
+
filesUpdate.mockResolvedValue({ data: { id: URL_ID, name: 'Renamed' } });
|
|
497
|
+
await newService().renameFile({
|
|
498
|
+
fileId: `https://docs.google.com/spreadsheets/d/${URL_ID}/edit`,
|
|
499
|
+
newName: 'Renamed'
|
|
500
|
+
});
|
|
501
|
+
expect(filesUpdate).toHaveBeenCalledWith(expect.objectContaining({ fileId: URL_ID }));
|
|
502
|
+
});
|
|
503
|
+
it('refuses to rename an invalid file ID without calling the API', async () => {
|
|
504
|
+
const result = await newService().renameFile({ fileId: 'bad id', newName: 'x' });
|
|
505
|
+
expect(isErrorOf(result)).toBe(true);
|
|
506
|
+
expect(jsonOf(result)).toEqual({ error: 'Invalid document ID or URL' });
|
|
507
|
+
expect(filesUpdate).not.toHaveBeenCalled();
|
|
508
|
+
});
|
|
509
|
+
it('returns the API error message when renaming fails', async () => {
|
|
510
|
+
filesUpdate.mockRejectedValue(new Error('name conflict'));
|
|
511
|
+
const result = await newService().renameFile({ fileId: 'doc-1', newName: 'x' });
|
|
512
|
+
expect(isErrorOf(result)).toBe(true);
|
|
513
|
+
expect(jsonOf(result)).toEqual({ error: 'name conflict' });
|
|
514
|
+
});
|
|
515
|
+
});
|
|
516
|
+
describe('DriveService.getComments pagination', () => {
|
|
517
|
+
const comment = (id) => ({
|
|
518
|
+
id,
|
|
519
|
+
content: `comment ${id}`,
|
|
520
|
+
author: { displayName: 'Alice', emailAddress: 'alice@example.com' },
|
|
521
|
+
createdTime: '2025-01-01T00:00:00Z',
|
|
522
|
+
resolved: false
|
|
523
|
+
});
|
|
524
|
+
beforeEach(() => {
|
|
525
|
+
resetMocks();
|
|
526
|
+
});
|
|
527
|
+
it('forwards pageSize and pageToken and returns the next page cursor with the comments', async () => {
|
|
528
|
+
commentsList.mockResolvedValue({ data: { comments: [comment('c1')], nextPageToken: 'tok-2' } });
|
|
529
|
+
const result = await newService().getComments({ fileId: 'doc-1', pageSize: 1, pageToken: 'tok-1' });
|
|
530
|
+
expect(commentsList).toHaveBeenCalledWith(expect.objectContaining({ fileId: 'doc-1', pageSize: 1, pageToken: 'tok-1' }));
|
|
531
|
+
expect(jsonOf(result)).toEqual({ comments: [comment('c1')], nextPageToken: 'tok-2' });
|
|
532
|
+
});
|
|
533
|
+
it('returns an object with the cursor, never a bare comment array', async () => {
|
|
534
|
+
commentsList.mockResolvedValue({ data: { comments: [comment('c1')], nextPageToken: 'tok-2' } });
|
|
535
|
+
const parsed = jsonOf(await newService().getComments({ fileId: 'doc-1' }));
|
|
536
|
+
expect(Array.isArray(parsed)).toBe(false);
|
|
537
|
+
expect(parsed).toHaveProperty('nextPageToken', 'tok-2');
|
|
538
|
+
});
|
|
539
|
+
it('requests the cursor in the fields mask so the API can return it', async () => {
|
|
540
|
+
commentsList.mockResolvedValue({ data: { comments: [] } });
|
|
541
|
+
await newService().getComments({ fileId: 'doc-1' });
|
|
542
|
+
const { fields } = commentsList.mock.calls[0][0];
|
|
543
|
+
expect(fields).toMatch(/^nextPageToken, comments\(/);
|
|
544
|
+
expect(fields).toContain('replies(');
|
|
545
|
+
expect(fields).toContain('quotedFileContent(value)');
|
|
546
|
+
});
|
|
547
|
+
it('leaves pageSize and pageToken out of the request when the caller omits them', async () => {
|
|
548
|
+
commentsList.mockResolvedValue({ data: { comments: [] } });
|
|
549
|
+
await newService().getComments({ fileId: 'doc-1' });
|
|
550
|
+
const request = commentsList.mock.calls[0][0];
|
|
551
|
+
expect(request.fileId).toBe('doc-1');
|
|
552
|
+
expect(request).not.toHaveProperty('pageSize');
|
|
553
|
+
expect(request).not.toHaveProperty('pageToken');
|
|
554
|
+
});
|
|
555
|
+
it('forwards only the pageToken when pageSize is omitted', async () => {
|
|
556
|
+
commentsList.mockResolvedValue({ data: { comments: [] } });
|
|
557
|
+
await newService().getComments({ fileId: 'doc-1', pageToken: 'tok-9' });
|
|
558
|
+
const request = commentsList.mock.calls[0][0];
|
|
559
|
+
expect(request.pageToken).toBe('tok-9');
|
|
560
|
+
expect(request).not.toHaveProperty('pageSize');
|
|
561
|
+
});
|
|
562
|
+
it('reports a null cursor on the last page', async () => {
|
|
563
|
+
commentsList.mockResolvedValue({ data: { comments: [comment('c2')] } });
|
|
564
|
+
const parsed = jsonOf(await newService().getComments({ fileId: 'doc-1' }));
|
|
565
|
+
expect(parsed).toEqual({ comments: [comment('c2')], nextPageToken: null });
|
|
566
|
+
});
|
|
567
|
+
it('returns an empty comment list when the API response has no comments field', async () => {
|
|
568
|
+
commentsList.mockResolvedValue({ data: {} });
|
|
569
|
+
const parsed = jsonOf(await newService().getComments({ fileId: 'doc-1' }));
|
|
570
|
+
expect(parsed).toEqual({ comments: [], nextPageToken: null });
|
|
571
|
+
});
|
|
572
|
+
it('serializes the page as pretty-printed JSON', async () => {
|
|
573
|
+
commentsList.mockResolvedValue({ data: { comments: [comment('c1')], nextPageToken: 'tok-2' } });
|
|
574
|
+
const result = await newService().getComments({ fileId: 'doc-1' });
|
|
575
|
+
expect(textOf(result)).toBe(JSON.stringify({ comments: [comment('c1')], nextPageToken: 'tok-2' }, null, 2));
|
|
576
|
+
});
|
|
577
|
+
it('walks every page by feeding each returned cursor into the next request', async () => {
|
|
578
|
+
commentsList
|
|
579
|
+
.mockResolvedValueOnce({ data: { comments: [comment('c1')], nextPageToken: 'tok-2' } })
|
|
580
|
+
.mockResolvedValueOnce({ data: { comments: [comment('c2')] } });
|
|
581
|
+
const service = newService();
|
|
582
|
+
const first = jsonOf(await service.getComments({ fileId: 'doc-1', pageSize: 1 }));
|
|
583
|
+
const second = jsonOf(await service.getComments({ fileId: 'doc-1', pageSize: 1, pageToken: first.nextPageToken }));
|
|
584
|
+
expect(commentsList).toHaveBeenNthCalledWith(2, expect.objectContaining({ pageSize: 1, pageToken: 'tok-2' }));
|
|
585
|
+
expect([...first.comments, ...second.comments]).toEqual([comment('c1'), comment('c2')]);
|
|
586
|
+
expect(second.nextPageToken).toBeNull();
|
|
587
|
+
});
|
|
588
|
+
it('extracts the file ID from a URL before listing comments', async () => {
|
|
589
|
+
commentsList.mockResolvedValue({ data: { comments: [] } });
|
|
590
|
+
await newService().getComments({ fileId: `https://docs.google.com/document/d/${URL_ID}/edit` });
|
|
591
|
+
expect(commentsList).toHaveBeenCalledWith(expect.objectContaining({ fileId: URL_ID }));
|
|
592
|
+
});
|
|
593
|
+
it('refuses an invalid file ID without calling the API', async () => {
|
|
594
|
+
const result = await newService().getComments({ fileId: 'bad id' });
|
|
595
|
+
expect(isErrorOf(result)).toBe(true);
|
|
596
|
+
expect(jsonOf(result)).toEqual({ error: 'Invalid document ID or URL' });
|
|
597
|
+
expect(commentsList).not.toHaveBeenCalled();
|
|
598
|
+
});
|
|
599
|
+
it('returns the API error message when listing comments fails', async () => {
|
|
600
|
+
commentsList.mockRejectedValue(new Error('comments disabled'));
|
|
601
|
+
const result = await newService().getComments({ fileId: 'doc-1' });
|
|
602
|
+
expect(isErrorOf(result)).toBe(true);
|
|
603
|
+
expect(jsonOf(result)).toEqual({ error: 'comments disabled' });
|
|
604
|
+
});
|
|
605
|
+
});
|
|
606
|
+
describe('DriveService.moveFile', () => {
|
|
607
|
+
beforeEach(() => {
|
|
608
|
+
resetMocks();
|
|
609
|
+
filesGet.mockResolvedValue({ data: { parents: ['old-1', 'old-2'] } });
|
|
610
|
+
filesUpdate.mockResolvedValue({ data: { id: 'doc-1', name: 'Plan', parents: ['dest-1'] } });
|
|
611
|
+
});
|
|
612
|
+
it('moves a file to the given folder ID and drops every previous parent', async () => {
|
|
613
|
+
const result = await newService().moveFile({ fileId: 'doc-1', folderId: 'dest-1' });
|
|
614
|
+
expect(filesGet).toHaveBeenCalledWith({ fileId: 'doc-1', fields: 'parents', supportsAllDrives: true });
|
|
615
|
+
expect(filesUpdate).toHaveBeenCalledWith({
|
|
616
|
+
fileId: 'doc-1',
|
|
617
|
+
addParents: 'dest-1',
|
|
618
|
+
removeParents: 'old-1,old-2',
|
|
619
|
+
fields: 'id, name, parents',
|
|
620
|
+
supportsAllDrives: true
|
|
621
|
+
});
|
|
622
|
+
expect(filesList).not.toHaveBeenCalled();
|
|
623
|
+
expect(jsonOf(result)).toEqual({ id: 'doc-1', name: 'Plan', parents: ['dest-1'] });
|
|
624
|
+
});
|
|
625
|
+
it('does not ask to remove parents when the file has none', async () => {
|
|
626
|
+
filesGet.mockResolvedValue({ data: {} });
|
|
627
|
+
await newService().moveFile({ fileId: 'doc-1', folderId: 'dest-1' });
|
|
628
|
+
expect(filesUpdate.mock.calls[0][0].removeParents).toBeUndefined();
|
|
629
|
+
expect(filesUpdate.mock.calls[0][0].addParents).toBe('dest-1');
|
|
630
|
+
});
|
|
631
|
+
it('prefers folderId over folderName and never searches for the name', async () => {
|
|
632
|
+
await newService().moveFile({ fileId: 'doc-1', folderId: 'dest-1', folderName: 'Other' });
|
|
633
|
+
expect(filesList).not.toHaveBeenCalled();
|
|
634
|
+
expect(filesUpdate).toHaveBeenCalledWith(expect.objectContaining({ addParents: 'dest-1' }));
|
|
635
|
+
});
|
|
636
|
+
it('resolves a unique folder name to its ID before moving', async () => {
|
|
637
|
+
filesList.mockResolvedValue({ data: { files: [{ id: 'dest-7', name: 'Reports' }] } });
|
|
638
|
+
await newService().moveFile({ fileId: 'doc-1', folderName: 'Reports' });
|
|
639
|
+
expect(filesList).toHaveBeenCalledWith(expect.objectContaining({ q: `mimeType='${FOLDER_MIME}' and name = 'Reports'` }));
|
|
640
|
+
expect(filesUpdate).toHaveBeenCalledWith(expect.objectContaining({ addParents: 'dest-7' }));
|
|
641
|
+
});
|
|
642
|
+
it('uses the first folder when several share the requested name', async () => {
|
|
643
|
+
filesList.mockResolvedValue({
|
|
644
|
+
data: {
|
|
645
|
+
files: [
|
|
646
|
+
{ id: 'first', name: 'Reports' },
|
|
647
|
+
{ id: 'second', name: 'Reports' }
|
|
648
|
+
]
|
|
649
|
+
}
|
|
650
|
+
});
|
|
651
|
+
await newService().moveFile({ fileId: 'doc-1', folderName: 'Reports' });
|
|
652
|
+
expect(filesUpdate).toHaveBeenCalledWith(expect.objectContaining({ addParents: 'first' }));
|
|
653
|
+
});
|
|
654
|
+
it('fails without moving anything when no folder has the requested name', async () => {
|
|
655
|
+
filesList.mockResolvedValue({ data: { files: [] } });
|
|
656
|
+
const result = await newService().moveFile({ fileId: 'doc-1', folderName: 'Ghost' });
|
|
657
|
+
expect(isErrorOf(result)).toBe(true);
|
|
658
|
+
expect(jsonOf(result)).toEqual({ error: 'Folder not found: Ghost' });
|
|
659
|
+
expect(filesUpdate).not.toHaveBeenCalled();
|
|
660
|
+
});
|
|
661
|
+
it('surfaces the folder lookup error instead of moving the file', async () => {
|
|
662
|
+
filesList.mockRejectedValue(new Error('quota exceeded'));
|
|
663
|
+
const result = await newService().moveFile({ fileId: 'doc-1', folderName: 'Reports' });
|
|
664
|
+
expect(isErrorOf(result)).toBe(true);
|
|
665
|
+
expect(jsonOf(result)).toEqual({ error: 'quota exceeded' });
|
|
666
|
+
expect(filesUpdate).not.toHaveBeenCalled();
|
|
667
|
+
});
|
|
668
|
+
it.each([[{}], [{ folderName: '' }]])('requires a folder ID or a folder name (%j)', async (target) => {
|
|
669
|
+
const result = await newService().moveFile({ fileId: 'doc-1', ...target });
|
|
670
|
+
expect(isErrorOf(result)).toBe(true);
|
|
671
|
+
expect(jsonOf(result)).toEqual({ error: 'Either folderId or folderName must be provided.' });
|
|
672
|
+
expect(filesGet).not.toHaveBeenCalled();
|
|
673
|
+
expect(filesUpdate).not.toHaveBeenCalled();
|
|
674
|
+
});
|
|
675
|
+
it('refuses an invalid file ID without calling the API', async () => {
|
|
676
|
+
const result = await newService().moveFile({ fileId: 'bad id', folderId: 'dest-1' });
|
|
677
|
+
expect(jsonOf(result)).toEqual({ error: 'Invalid document ID or URL' });
|
|
678
|
+
expect(filesUpdate).not.toHaveBeenCalled();
|
|
679
|
+
});
|
|
680
|
+
it('returns the API error message when reading the current parents fails', async () => {
|
|
681
|
+
filesGet.mockRejectedValue(new Error('file not found'));
|
|
682
|
+
const result = await newService().moveFile({ fileId: 'doc-1', folderId: 'dest-1' });
|
|
683
|
+
expect(isErrorOf(result)).toBe(true);
|
|
684
|
+
expect(jsonOf(result)).toEqual({ error: 'file not found' });
|
|
685
|
+
expect(filesUpdate).not.toHaveBeenCalled();
|
|
686
|
+
});
|
|
687
|
+
it('returns the API error message when the move itself fails', async () => {
|
|
688
|
+
filesUpdate.mockRejectedValue(new Error('move denied'));
|
|
689
|
+
const result = await newService().moveFile({ fileId: 'doc-1', folderId: 'dest-1' });
|
|
690
|
+
expect(isErrorOf(result)).toBe(true);
|
|
691
|
+
expect(jsonOf(result)).toEqual({ error: 'move denied' });
|
|
692
|
+
});
|
|
693
|
+
});
|
|
694
|
+
describe('DriveService.downloadFile Google-native and failure handling', () => {
|
|
695
|
+
const pdfBytes = new Uint8Array([1, 2, 3]).buffer;
|
|
696
|
+
beforeEach(() => {
|
|
697
|
+
resetMocks();
|
|
698
|
+
mkdir.mockResolvedValue(undefined);
|
|
699
|
+
writeFile.mockResolvedValue(undefined);
|
|
700
|
+
});
|
|
701
|
+
it.each([
|
|
702
|
+
['application/vnd.google-apps.document', 'Google Doc', 'docs.getText', 'documentId'],
|
|
703
|
+
['application/vnd.google-apps.spreadsheet', 'Google Sheet', 'sheets.getText', 'spreadsheetId'],
|
|
704
|
+
['application/vnd.google-apps.presentation', 'Google Slide', 'slides.getText', 'presentationId']
|
|
705
|
+
])('points %s at the %s text tool instead of downloading', async (mimeType, type, tool, idName) => {
|
|
706
|
+
filesGet.mockResolvedValue({ data: { id: 'doc-1', name: 'Native', mimeType } });
|
|
707
|
+
const result = await newService().downloadFile({ fileId: 'doc-1', localPath: 'out/native.bin' });
|
|
708
|
+
expect(textOf(result)).toBe(`This is a ${type}. Direct download is not supported. Please use the '${tool}' tool with ${idName}: doc-1`);
|
|
709
|
+
expect(filesGet).toHaveBeenCalledTimes(1);
|
|
710
|
+
expect(filesGet).toHaveBeenCalledWith({ fileId: 'doc-1', fields: 'id, name, mimeType', supportsAllDrives: true });
|
|
711
|
+
expect(writeFile).not.toHaveBeenCalled();
|
|
712
|
+
});
|
|
713
|
+
it.each([
|
|
714
|
+
'application/vnd.google-apps.form',
|
|
715
|
+
'application/vnd.google-apps.folder',
|
|
716
|
+
'application/vnd.google-apps.drawing'
|
|
717
|
+
])('explains that the Google Workspace type %s cannot be downloaded as media', async (mimeType) => {
|
|
718
|
+
filesGet.mockResolvedValue({ data: { id: 'doc-1', name: 'Native', mimeType } });
|
|
719
|
+
const result = await newService().downloadFile({ fileId: 'doc-1', localPath: 'out/native.bin' });
|
|
720
|
+
expect(textOf(result)).toBe(`This is a Google Workspace file type (${mimeType}). Direct media download is not supported. Please use specific tools (docs.getText, slides.getText, etc.) or export it if supported.`);
|
|
721
|
+
expect(filesGet).toHaveBeenCalledTimes(1);
|
|
722
|
+
expect(writeFile).not.toHaveBeenCalled();
|
|
723
|
+
});
|
|
724
|
+
it('downloads the media as an arraybuffer and writes the exact bytes', async () => {
|
|
725
|
+
filesGet
|
|
726
|
+
.mockResolvedValueOnce({ data: { id: 'doc-1', name: 'report.pdf', mimeType: 'application/pdf' } })
|
|
727
|
+
.mockResolvedValueOnce({ data: pdfBytes });
|
|
728
|
+
const expectedPath = path.resolve(PROJECT_ROOT, 'out', 'report.pdf');
|
|
729
|
+
const result = await newService().downloadFile({ fileId: 'doc-1', localPath: 'out/report.pdf' });
|
|
730
|
+
expect(filesGet).toHaveBeenNthCalledWith(2, { fileId: 'doc-1', alt: 'media', supportsAllDrives: true }, { responseType: 'arraybuffer' });
|
|
731
|
+
expect(mkdir).toHaveBeenCalledWith(path.dirname(expectedPath), { recursive: true });
|
|
732
|
+
expect(writeFile).toHaveBeenCalledWith(expectedPath, Buffer.from([1, 2, 3]));
|
|
733
|
+
expect(textOf(result)).toBe(`Successfully downloaded file report.pdf to ${expectedPath}`);
|
|
734
|
+
});
|
|
735
|
+
it('downloads a file whose metadata has no mimeType as plain media', async () => {
|
|
736
|
+
filesGet.mockResolvedValueOnce({ data: { id: 'doc-1', name: 'blob' } }).mockResolvedValueOnce({ data: pdfBytes });
|
|
737
|
+
const result = await newService().downloadFile({ fileId: 'doc-1', localPath: 'blob.bin' });
|
|
738
|
+
expect(writeFile).toHaveBeenCalledWith(path.resolve(PROJECT_ROOT, 'blob.bin'), Buffer.from([1, 2, 3]));
|
|
739
|
+
expect(textOf(result)).toContain('Successfully downloaded file blob');
|
|
740
|
+
});
|
|
741
|
+
it('extracts the file ID from a URL before downloading', async () => {
|
|
742
|
+
filesGet.mockResolvedValue({ data: { id: URL_ID, name: 'Doc', mimeType: 'application/vnd.google-apps.document' } });
|
|
743
|
+
const result = await newService().downloadFile({
|
|
744
|
+
fileId: `https://docs.google.com/document/d/${URL_ID}/edit`,
|
|
745
|
+
localPath: 'doc.txt'
|
|
746
|
+
});
|
|
747
|
+
expect(filesGet).toHaveBeenCalledWith(expect.objectContaining({ fileId: URL_ID }));
|
|
748
|
+
expect(textOf(result)).toContain(`documentId: ${URL_ID}`);
|
|
749
|
+
});
|
|
750
|
+
it('refuses an invalid file ID without calling the API', async () => {
|
|
751
|
+
const result = await newService().downloadFile({ fileId: 'bad id', localPath: 'x.bin' });
|
|
752
|
+
expect(jsonOf(result)).toEqual({ error: 'Invalid document ID or URL' });
|
|
753
|
+
expect(filesGet).not.toHaveBeenCalled();
|
|
754
|
+
});
|
|
755
|
+
it('returns the API error message when the metadata lookup fails', async () => {
|
|
756
|
+
filesGet.mockRejectedValue(new Error('file not found'));
|
|
757
|
+
const result = await newService().downloadFile({ fileId: 'doc-1', localPath: 'x.bin' });
|
|
758
|
+
expect(jsonOf(result)).toEqual({ error: 'file not found' });
|
|
759
|
+
expect(writeFile).not.toHaveBeenCalled();
|
|
760
|
+
});
|
|
761
|
+
it('returns the API error message when the media download fails and writes nothing', async () => {
|
|
762
|
+
filesGet
|
|
763
|
+
.mockResolvedValueOnce({ data: { id: 'doc-1', name: 'report.pdf', mimeType: 'application/pdf' } })
|
|
764
|
+
.mockRejectedValueOnce(new Error('download interrupted'));
|
|
765
|
+
const result = await newService().downloadFile({ fileId: 'doc-1', localPath: 'x.bin' });
|
|
766
|
+
expect(jsonOf(result)).toEqual({ error: 'download interrupted' });
|
|
767
|
+
expect(mkdir).not.toHaveBeenCalled();
|
|
768
|
+
expect(writeFile).not.toHaveBeenCalled();
|
|
769
|
+
});
|
|
770
|
+
it('stringifies a non-Error rejection from the metadata lookup', async () => {
|
|
771
|
+
filesGet.mockRejectedValue('network down');
|
|
772
|
+
const result = await newService().downloadFile({ fileId: 'doc-1', localPath: 'x.bin' });
|
|
773
|
+
expect(jsonOf(result)).toEqual({ error: 'network down' });
|
|
774
|
+
});
|
|
775
|
+
it('returns the filesystem error when the destination directory cannot be created', async () => {
|
|
776
|
+
filesGet
|
|
777
|
+
.mockResolvedValueOnce({ data: { id: 'doc-1', name: 'report.pdf', mimeType: 'application/pdf' } })
|
|
778
|
+
.mockResolvedValueOnce({ data: pdfBytes });
|
|
779
|
+
mkdir.mockRejectedValue(new Error('EACCES: permission denied'));
|
|
780
|
+
const result = await newService().downloadFile({ fileId: 'doc-1', localPath: 'locked/x.bin' });
|
|
781
|
+
expect(jsonOf(result)).toEqual({ error: 'EACCES: permission denied' });
|
|
782
|
+
expect(writeFile).not.toHaveBeenCalled();
|
|
783
|
+
});
|
|
784
|
+
it('returns the filesystem error when the file cannot be written', async () => {
|
|
785
|
+
filesGet
|
|
786
|
+
.mockResolvedValueOnce({ data: { id: 'doc-1', name: 'report.pdf', mimeType: 'application/pdf' } })
|
|
787
|
+
.mockResolvedValueOnce({ data: pdfBytes });
|
|
788
|
+
writeFile.mockRejectedValue(new Error('ENOSPC: no space left on device'));
|
|
789
|
+
const result = await newService().downloadFile({ fileId: 'doc-1', localPath: 'x.bin' });
|
|
790
|
+
expect(jsonOf(result)).toEqual({ error: 'ENOSPC: no space left on device' });
|
|
791
|
+
});
|
|
792
|
+
});
|
|
793
|
+
describe('DriveService.downloadFile path traversal guard', () => {
|
|
794
|
+
const pdfMetadata = { data: { id: 'doc-1', name: 'report.pdf', mimeType: 'application/pdf' } };
|
|
795
|
+
const sep = path.sep;
|
|
796
|
+
beforeEach(() => {
|
|
797
|
+
resetMocks();
|
|
798
|
+
mkdir.mockResolvedValue(undefined);
|
|
799
|
+
writeFile.mockResolvedValue(undefined);
|
|
800
|
+
filesGet.mockResolvedValueOnce(pdfMetadata).mockResolvedValueOnce({ data: new Uint8Array([9]).buffer });
|
|
801
|
+
});
|
|
802
|
+
it.each([
|
|
803
|
+
['a parent-directory segment', () => ['..', 'escape.bin'].join(sep)],
|
|
804
|
+
['a traversal hidden behind a subdirectory', () => ['sub', '..', '..', 'escape.bin'].join(sep)],
|
|
805
|
+
['a traversal that climbs well past the filesystem root', () => [...Array(40).fill('..'), 'escape.bin'].join(sep)],
|
|
806
|
+
['an absolute path beside the project root', () => path.resolve(PROJECT_ROOT, '..', 'escape.bin')],
|
|
807
|
+
[
|
|
808
|
+
'an absolute sibling that shares the root directory name as a prefix',
|
|
809
|
+
() => `${PROJECT_ROOT}-sibling${sep}escape.bin`
|
|
810
|
+
],
|
|
811
|
+
['the parent of the project root', () => path.dirname(PROJECT_ROOT)]
|
|
812
|
+
])('rejects %s before touching the filesystem', async (_label, makePath) => {
|
|
813
|
+
const result = await newService().downloadFile({ fileId: 'doc-1', localPath: makePath() });
|
|
814
|
+
expect(jsonOf(result)).toEqual({ error: 'localPath must be within the project root.' });
|
|
815
|
+
expect(mkdir).not.toHaveBeenCalled();
|
|
816
|
+
expect(writeFile).not.toHaveBeenCalled();
|
|
817
|
+
});
|
|
818
|
+
it('allows a relative path whose dot-dot segments stay inside the project root', async () => {
|
|
819
|
+
const result = await newService().downloadFile({
|
|
820
|
+
fileId: 'doc-1',
|
|
821
|
+
localPath: ['a', '..', 'kept.bin'].join(sep)
|
|
822
|
+
});
|
|
823
|
+
const expectedPath = path.join(PROJECT_ROOT, 'kept.bin');
|
|
824
|
+
expect(writeFile).toHaveBeenCalledWith(expectedPath, Buffer.from([9]));
|
|
825
|
+
expect(textOf(result)).toBe(`Successfully downloaded file report.pdf to ${expectedPath}`);
|
|
826
|
+
});
|
|
827
|
+
it('creates nested destination directories recursively under the project root', async () => {
|
|
828
|
+
await newService().downloadFile({ fileId: 'doc-1', localPath: ['deep', 'er', 'file.bin'].join(sep) });
|
|
829
|
+
const expectedDir = path.join(PROJECT_ROOT, 'deep', 'er');
|
|
830
|
+
expect(mkdir).toHaveBeenCalledWith(expectedDir, { recursive: true });
|
|
831
|
+
expect(writeFile).toHaveBeenCalledWith(path.join(expectedDir, 'file.bin'), expect.any(Buffer));
|
|
832
|
+
});
|
|
833
|
+
it('treats the project root itself as inside the boundary', async () => {
|
|
834
|
+
await newService().downloadFile({ fileId: 'doc-1', localPath: PROJECT_ROOT });
|
|
835
|
+
expect(writeFile).toHaveBeenCalledWith(PROJECT_ROOT, expect.any(Buffer));
|
|
836
|
+
});
|
|
837
|
+
});
|
|
838
|
+
describe('DriveService.downloadFile on a real filesystem', () => {
|
|
839
|
+
// The project root is a subdirectory of a mkdtemp container, so even a broken guard can only
|
|
840
|
+
// spill into the container, which afterEach removes together with the project root.
|
|
841
|
+
let container;
|
|
842
|
+
let tmpRoot;
|
|
843
|
+
let realPromises;
|
|
844
|
+
beforeAll(async () => {
|
|
845
|
+
realPromises = (await vi.importActual('node:fs')).promises;
|
|
846
|
+
});
|
|
847
|
+
beforeEach(() => {
|
|
848
|
+
resetMocks();
|
|
849
|
+
container = fs.mkdtempSync(path.join(os.tmpdir(), 'drive-download-'));
|
|
850
|
+
tmpRoot = path.join(container, 'project');
|
|
851
|
+
fs.mkdirSync(tmpRoot);
|
|
852
|
+
projectRoot.override = tmpRoot;
|
|
853
|
+
mkdir.mockImplementation((dir, options) => realPromises.mkdir(dir, options));
|
|
854
|
+
writeFile.mockImplementation((file, data) => realPromises.writeFile(file, data));
|
|
855
|
+
filesGet
|
|
856
|
+
.mockResolvedValueOnce({ data: { id: 'doc-1', name: 'report.pdf', mimeType: 'application/pdf' } })
|
|
857
|
+
.mockResolvedValueOnce({ data: new Uint8Array([1, 2, 3, 250]).buffer });
|
|
858
|
+
});
|
|
859
|
+
afterEach(() => {
|
|
860
|
+
projectRoot.override = undefined;
|
|
861
|
+
fs.rmSync(container, { recursive: true, force: true });
|
|
862
|
+
});
|
|
863
|
+
it('writes the downloaded bytes to a nested relative path, creating the missing directories', async () => {
|
|
864
|
+
const localPath = ['out', 'nested', 'report.pdf'].join(path.sep);
|
|
865
|
+
const expectedPath = path.join(tmpRoot, 'out', 'nested', 'report.pdf');
|
|
866
|
+
const result = await newService().downloadFile({ fileId: 'doc-1', localPath });
|
|
867
|
+
expect(textOf(result)).toBe(`Successfully downloaded file report.pdf to ${expectedPath}`);
|
|
868
|
+
expect(fs.readFileSync(expectedPath)).toEqual(Buffer.from([1, 2, 3, 250]));
|
|
869
|
+
});
|
|
870
|
+
it('writes to an absolute destination inside the project root', async () => {
|
|
871
|
+
const expectedPath = path.join(tmpRoot, 'absolute.bin');
|
|
872
|
+
await newService().downloadFile({ fileId: 'doc-1', localPath: expectedPath });
|
|
873
|
+
expect(fs.readFileSync(expectedPath)).toEqual(Buffer.from([1, 2, 3, 250]));
|
|
874
|
+
});
|
|
875
|
+
it('overwrites a file that already exists at the destination', async () => {
|
|
876
|
+
const expectedPath = path.join(tmpRoot, 'existing.bin');
|
|
877
|
+
fs.writeFileSync(expectedPath, 'previous content that is much longer than the new payload');
|
|
878
|
+
await newService().downloadFile({ fileId: 'doc-1', localPath: 'existing.bin' });
|
|
879
|
+
expect(fs.readFileSync(expectedPath)).toEqual(Buffer.from([1, 2, 3, 250]));
|
|
880
|
+
});
|
|
881
|
+
it('does not write outside the project root when the path escapes it', async () => {
|
|
882
|
+
const escaped = path.join(container, 'escape.bin');
|
|
883
|
+
const result = await newService().downloadFile({
|
|
884
|
+
fileId: 'doc-1',
|
|
885
|
+
localPath: ['..', 'escape.bin'].join(path.sep)
|
|
886
|
+
});
|
|
887
|
+
expect(jsonOf(result)).toEqual({ error: 'localPath must be within the project root.' });
|
|
888
|
+
expect(fs.existsSync(escaped)).toBe(false);
|
|
889
|
+
expect(fs.readdirSync(tmpRoot)).toEqual([]);
|
|
890
|
+
});
|
|
891
|
+
it('returns an error result and keeps the blocking file when a parent directory is a regular file', async () => {
|
|
892
|
+
const blocker = path.join(tmpRoot, 'blocker');
|
|
893
|
+
fs.writeFileSync(blocker, 'not a directory');
|
|
894
|
+
const result = await newService().downloadFile({
|
|
895
|
+
fileId: 'doc-1',
|
|
896
|
+
localPath: ['blocker', 'child.bin'].join(path.sep)
|
|
897
|
+
});
|
|
898
|
+
expect(typeof jsonOf(result).error).toBe('string');
|
|
899
|
+
expect(jsonOf(result).error).not.toContain('within the project root');
|
|
900
|
+
expect(fs.readFileSync(blocker, 'utf8')).toBe('not a directory');
|
|
901
|
+
});
|
|
902
|
+
});
|
|
115
903
|
//# sourceMappingURL=DriveService.test.js.map
|