@ultrst-armada/kloks 1.26.5 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/package.json +3 -7
  2. package/packages/backend/dist/{chunk-BVXGUHLZ.js → chunk-AOZSDRNY.js} +1 -1
  3. package/packages/backend/dist/{chunk-HF5SGQ5V.js → chunk-FK3OAUXM.js} +2 -4
  4. package/packages/backend/dist/chunk-G4EDIAHW.js +0 -0
  5. package/packages/backend/dist/{chunk-RIOYKF3X.js → chunk-KPLDYX5Z.js} +2 -4
  6. package/packages/backend/dist/{chunk-MZK362U4.js → chunk-LMOM7CST.js} +3 -3
  7. package/packages/backend/dist/chunk-OQRQCDS6.js +109 -0
  8. package/packages/backend/dist/chunk-OWMQLML7.js +451 -0
  9. package/packages/backend/dist/{chunk-Y5ENDXU2.js → chunk-SQKG3S6P.js} +2 -10
  10. package/packages/backend/dist/{chunk-NGEB3CF5.js → chunk-Z6G32NQQ.js} +8 -3
  11. package/packages/backend/dist/core/SrklStorageService.test.d.ts +1 -0
  12. package/packages/backend/dist/krnl-services.js +6 -5
  13. package/packages/backend/dist/node.js +14 -26
  14. package/packages/backend/dist/services/node.js +4 -3
  15. package/packages/backend/dist/srkl/SrklClient.d.ts +1 -1
  16. package/packages/backend/dist/srkl/index.js +2 -2
  17. package/packages/backend/dist/storage/GoogleDriveStorageService.d.ts +31 -9
  18. package/packages/backend/dist/storage/GoogleDriveWorkspaceService.d.ts +23 -6
  19. package/packages/backend/dist/storage/StorageAdapterFactory.d.ts +2 -2
  20. package/packages/backend/dist/storage/node.d.ts +0 -2
  21. package/packages/backend/dist/storage/node.js +5 -17
  22. package/packages/backend/dist/storage-workspace.js +4 -335
  23. package/packages/backend/dist/workspace/node.js +3 -2
  24. package/packages/backend/package.json +3 -7
  25. package/packages/backend/dist/chunk-3FZSYSJC.js +0 -86
  26. package/packages/backend/dist/chunk-G7PPVOFP.js +0 -369
  27. package/packages/backend/dist/storage/GoogleDriveAdapter.d.ts +0 -41
  28. package/packages/backend/dist/storage/GoogleDriveOAuth.d.ts +0 -34
  29. package/packages/backend/dist/storage/googleDriveSdk.d.ts +0 -1
@@ -1,338 +1,7 @@
1
- // src/storage/GoogleDriveWorkspaceService.ts
2
- var GOOGLE_DRIVE_WORKSPACE_SCOPE = "https://www.googleapis.com/auth/drive";
3
- var GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token";
4
- var GOOGLE_API_URL = "https://www.googleapis.com/drive/v3";
5
- var GOOGLE_UPLOAD_URL = "https://www.googleapis.com/upload/drive/v3";
6
- var FOLDER_MIME_TYPE = "application/vnd.google-apps.folder";
7
- function encodeBytes(parts) {
8
- const encoder = new TextEncoder();
9
- const buffers = parts.map((part) => typeof part === "string" ? encoder.encode(part) : part);
10
- const output = new Uint8Array(buffers.reduce((sum, item) => sum + item.length, 0));
11
- let offset = 0;
12
- for (const item of buffers) {
13
- output.set(item, offset);
14
- offset += item.length;
15
- }
16
- return output;
17
- }
18
- function quoteDriveQuery(value) {
19
- return value.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
20
- }
21
- async function parseJson(response) {
22
- return response.json().catch(() => ({}));
23
- }
24
- var GoogleDriveWorkspaceService = class _GoogleDriveWorkspaceService {
25
- options;
26
- fetcher;
27
- tokens;
28
- refreshPromise;
29
- constructor(options) {
30
- if (!options.clientId?.trim()) throw new Error("Google Drive OAuth client ID is required.");
31
- if (!options.redirectUri?.trim()) throw new Error("Google Drive OAuth redirect URI is required.");
32
- this.options = options;
33
- this.fetcher = options.fetcher || fetch;
34
- this.tokens = { ...options.tokens || { accessToken: "" } };
35
- }
36
- static createAuthorizationUrl(options, state, scopes = [GOOGLE_DRIVE_WORKSPACE_SCOPE]) {
37
- if (!options.clientId?.trim() || !options.redirectUri?.trim()) {
38
- throw new Error("Google Drive OAuth client ID and redirect URI are required.");
39
- }
40
- if (!state?.trim()) throw new Error("A non-empty Google Drive OAuth state is required.");
41
- const url = new URL("https://accounts.google.com/o/oauth2/v2/auth");
42
- url.searchParams.set("client_id", options.clientId);
43
- url.searchParams.set("redirect_uri", options.redirectUri);
44
- url.searchParams.set("response_type", "code");
45
- url.searchParams.set("access_type", "offline");
46
- url.searchParams.set("prompt", "consent");
47
- url.searchParams.set("include_granted_scopes", "true");
48
- url.searchParams.set("scope", scopes.join(" "));
49
- url.searchParams.set("state", state);
50
- return url.toString();
51
- }
52
- static async exchangeAuthorizationCode(options, code, existingRefreshToken, codeVerifier) {
53
- if (!code?.trim()) throw new Error("Google Drive authorization code is required.");
54
- return _GoogleDriveWorkspaceService.requestTokens(
55
- options.fetcher || fetch,
56
- {
57
- client_id: options.clientId,
58
- client_secret: options.clientSecret || "",
59
- redirect_uri: options.redirectUri,
60
- grant_type: "authorization_code",
61
- code,
62
- ...codeVerifier ? { code_verifier: codeVerifier } : {}
63
- },
64
- existingRefreshToken
65
- );
66
- }
67
- static async requestTokens(fetcher, fields, existingRefreshToken) {
68
- const response = await fetcher(GOOGLE_TOKEN_URL, {
69
- method: "POST",
70
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
71
- body: new URLSearchParams(fields),
72
- cache: "no-store"
73
- });
74
- const data = await parseJson(response);
75
- if (!response.ok || typeof data.access_token !== "string" || !data.access_token) {
76
- const reason = typeof data.error === "string" ? data.error : "token_exchange_failed";
77
- throw new Error(`Google Drive OAuth token request failed (${reason}).`);
78
- }
79
- return {
80
- accessToken: data.access_token,
81
- ...data.refresh_token || existingRefreshToken ? { refreshToken: data.refresh_token || existingRefreshToken } : {},
82
- ...Number.isFinite(Number(data.expires_in)) ? { expiresAt: Date.now() + Number(data.expires_in) * 1e3 } : {},
83
- ...typeof data.token_type === "string" ? { tokenType: data.token_type } : {}
84
- };
85
- }
86
- async getAccessToken(forceRefresh = false) {
87
- const expiresSoon = Boolean(this.tokens.expiresAt && this.tokens.expiresAt <= Date.now() + 6e4);
88
- if (!forceRefresh && this.tokens.accessToken && !expiresSoon) return this.tokens.accessToken;
89
- if (!this.tokens.refreshToken || !this.options.clientSecret) {
90
- throw new Error("Google Drive credentials are missing or expired. Reconnect the Google account.");
91
- }
92
- if (!this.refreshPromise) {
93
- this.refreshPromise = _GoogleDriveWorkspaceService.requestTokens(
94
- this.fetcher,
95
- {
96
- client_id: this.options.clientId,
97
- client_secret: this.options.clientSecret,
98
- refresh_token: this.tokens.refreshToken,
99
- grant_type: "refresh_token"
100
- },
101
- this.tokens.refreshToken
102
- ).then(async (tokens) => {
103
- this.tokens = tokens;
104
- await this.options.persistTokens?.(tokens);
105
- return tokens;
106
- }).finally(() => {
107
- this.refreshPromise = void 0;
108
- });
109
- }
110
- const refreshed = await this.refreshPromise;
111
- return refreshed.accessToken;
112
- }
113
- async api(path, init = {}, retry = true) {
114
- const token = await this.getAccessToken();
115
- const response = await this.fetcher(
116
- path.startsWith("https://") ? path : `${GOOGLE_API_URL}/${path.replace(/^\/+/, "")}`,
117
- {
118
- ...init,
119
- headers: {
120
- ...init.headers || {},
121
- Authorization: `Bearer ${token}`
122
- },
123
- cache: "no-store"
124
- }
125
- );
126
- if (response.status === 401 && retry && this.tokens.refreshToken) {
127
- await this.getAccessToken(true);
128
- return this.api(path, init, false);
129
- }
130
- if (!response.ok) {
131
- const data = await parseJson(response);
132
- const message = typeof data.error?.message === "string" ? data.error.message : `Google Drive request failed with HTTP ${response.status}.`;
133
- throw new Error(message);
134
- }
135
- return response;
136
- }
137
- async listFiles(parentId, query = "trashed = false") {
138
- const files = [];
139
- let pageToken = "";
140
- do {
141
- const url = new URL(`${GOOGLE_API_URL}/files`);
142
- url.searchParams.set("q", `'${quoteDriveQuery(parentId)}' in parents and ${query}`);
143
- url.searchParams.set("fields", "nextPageToken,files(id,name,mimeType,size,modifiedTime,parents)");
144
- url.searchParams.set("pageSize", "1000");
145
- url.searchParams.set("supportsAllDrives", "true");
146
- url.searchParams.set("includeItemsFromAllDrives", "true");
147
- if (pageToken) url.searchParams.set("pageToken", pageToken);
148
- const data = await parseJson(await this.api(url.toString()));
149
- if (Array.isArray(data.files)) files.push(...data.files);
150
- pageToken = typeof data.nextPageToken === "string" ? data.nextPageToken : "";
151
- } while (pageToken);
152
- return files;
153
- }
154
- async findChild(parentId, name) {
155
- const matches = await this.listFiles(
156
- parentId,
157
- `name = '${quoteDriveQuery(name)}' and trashed = false`
158
- );
159
- return matches.find((item) => Boolean(item.id));
160
- }
161
- async resolveParent(relativePath, create = false) {
162
- let parent = this.options.rootFolderId || "root";
163
- for (const segment of relativePath.replace(/\\/g, "/").split("/").filter(Boolean)) {
164
- let child = await this.findChild(parent, segment);
165
- if (!child && create) {
166
- const data = await parseJson(await this.api("files", {
167
- method: "POST",
168
- headers: { "Content-Type": "application/json" },
169
- body: JSON.stringify({
170
- name: segment,
171
- mimeType: FOLDER_MIME_TYPE,
172
- parents: [parent]
173
- })
174
- }));
175
- child = data;
176
- }
177
- if (!child?.id || child.mimeType !== FOLDER_MIME_TYPE) {
178
- throw new Error(`Google Drive folder not found: ${segment}`);
179
- }
180
- parent = child.id;
181
- }
182
- return parent;
183
- }
184
- splitPath(value) {
185
- const normalized = value.replace(/\\/g, "/").replace(/^\/+|\/+$/g, "");
186
- const index = normalized.lastIndexOf("/");
187
- return index < 0 ? { parent: "", name: normalized } : { parent: normalized.slice(0, index), name: normalized.slice(index + 1) };
188
- }
189
- async getAccountIdentity() {
190
- const url = new URL(`${GOOGLE_API_URL}/about`);
191
- url.searchParams.set("fields", "user(permissionId,emailAddress)");
192
- const data = await parseJson(await this.api(url.toString()));
193
- const accountId = data.user?.permissionId || data.user?.emailAddress;
194
- if (typeof accountId !== "string" || !accountId) {
195
- throw new Error("Google Drive did not return a stable account identity.");
196
- }
197
- return {
198
- accountId,
199
- ...typeof data.user?.emailAddress === "string" ? { email: data.user.emailAddress } : {}
200
- };
201
- }
202
- async listFolders(parentFolderId = this.options.rootFolderId || "root") {
203
- const files = await this.listFiles(
204
- parentFolderId,
205
- `mimeType = '${FOLDER_MIME_TYPE}' and trashed = false`
206
- );
207
- return files.flatMap((file) => file.id && file.name ? [{
208
- id: file.id,
209
- name: file.name,
210
- mimeType: FOLDER_MIME_TYPE,
211
- parentIds: file.parents || [],
212
- modifiedAt: file.modifiedTime ? Date.parse(file.modifiedTime) : 0
213
- }] : []);
214
- }
215
- async resolveFolder(folderId) {
216
- if (!folderId?.trim()) throw new Error("A Google Drive folder ID is required.");
217
- const url = new URL(`${GOOGLE_API_URL}/files/${encodeURIComponent(folderId)}`);
218
- url.searchParams.set("fields", "id,name,mimeType,parents,modifiedTime");
219
- url.searchParams.set("supportsAllDrives", "true");
220
- const file = await parseJson(await this.api(url.toString()));
221
- if (!file.id || !file.name || file.mimeType !== FOLDER_MIME_TYPE) {
222
- throw new Error("The selected Google Drive item is not a folder.");
223
- }
224
- return {
225
- id: file.id,
226
- name: file.name,
227
- mimeType: file.mimeType,
228
- parentIds: file.parents || [],
229
- modifiedAt: file.modifiedTime ? Date.parse(file.modifiedTime) : 0
230
- };
231
- }
232
- async selectRootFolder(folderId) {
233
- const folder = await this.resolveFolder(folderId);
234
- this.options.rootFolderId = folder.id;
235
- return folder;
236
- }
237
- async read(path) {
238
- const { parent, name } = this.splitPath(path);
239
- if (!name) throw new Error("A Google Drive file path is required.");
240
- const parentId = await this.resolveParent(parent);
241
- const file = await this.findChild(parentId, name);
242
- if (!file?.id || file.mimeType === FOLDER_MIME_TYPE) throw new Error(`Google Drive file not found: ${path}`);
243
- const url = new URL(`${GOOGLE_API_URL}/files/${encodeURIComponent(file.id)}`);
244
- url.searchParams.set("alt", "media");
245
- return new Uint8Array(await (await this.api(url.toString())).arrayBuffer());
246
- }
247
- async write(path, bytes, contentType = "application/octet-stream") {
248
- const { parent, name } = this.splitPath(path);
249
- if (!name) throw new Error("A Google Drive file name is required.");
250
- const parentId = await this.resolveParent(parent, true);
251
- const existing = await this.findChild(parentId, name);
252
- if (existing?.mimeType === FOLDER_MIME_TYPE) throw new Error(`Google Drive path is a folder: ${path}`);
253
- const data = typeof bytes === "string" ? new TextEncoder().encode(bytes) : bytes;
254
- const boundary = `kloks-drive-${crypto.randomUUID()}`;
255
- const body = encodeBytes([
256
- `--${boundary}\\r\\nContent-Type: application/json; charset=UTF-8\\r\\n\\r\\n`,
257
- JSON.stringify({
258
- name,
259
- mimeType: contentType,
260
- ...!existing?.id ? { parents: [parentId] } : {}
261
- }),
262
- `\\r\\n--${boundary}\\r\\nContent-Type: ${contentType}\\r\\n\\r\\n`,
263
- data,
264
- `\\r\\n--${boundary}--`
265
- ]);
266
- const endpoint = existing?.id ? `${GOOGLE_UPLOAD_URL}/files/${encodeURIComponent(existing.id)}?uploadType=multipart&supportsAllDrives=true` : `${GOOGLE_UPLOAD_URL}/files?uploadType=multipart&supportsAllDrives=true`;
267
- await this.api(endpoint, {
268
- method: existing?.id ? "PATCH" : "POST",
269
- headers: { "Content-Type": `multipart/related; boundary=${boundary}` },
270
- body: body.buffer
271
- });
272
- }
273
- async delete(path) {
274
- const { parent, name } = this.splitPath(path);
275
- const parentId = await this.resolveParent(parent);
276
- const file = await this.findChild(parentId, name);
277
- if (!file?.id) return;
278
- await this.api(`files/${encodeURIComponent(file.id)}?supportsAllDrives=true`, { method: "DELETE" });
279
- }
280
- async exists(path) {
281
- try {
282
- await this.stat(path);
283
- return true;
284
- } catch (error) {
285
- if (error instanceof Error && /not found|404/i.test(error.message)) return false;
286
- throw error;
287
- }
288
- }
289
- async list(path = "") {
290
- const parentId = await this.resolveParent(path);
291
- const files = await this.listFiles(parentId);
292
- return files.flatMap((file) => file.name ? [{
293
- path: path ? `${path.replace(/\/+$/, "")}/${file.name}` : file.name,
294
- size: Number(file.size || 0),
295
- modifiedAt: file.modifiedTime ? Date.parse(file.modifiedTime) : 0
296
- }] : []);
297
- }
298
- async stat(path) {
299
- const { parent, name } = this.splitPath(path);
300
- const parentId = await this.resolveParent(parent);
301
- const file = await this.findChild(parentId, name);
302
- if (!file?.id) throw new Error(`Google Drive file not found: ${path}`);
303
- return {
304
- path,
305
- size: Number(file.size || 0),
306
- modifiedAt: file.modifiedTime ? Date.parse(file.modifiedTime) : 0
307
- };
308
- }
309
- async mkdir(path) {
310
- await this.resolveParent(path, true);
311
- }
312
- async testConnection() {
313
- const started = Date.now();
314
- try {
315
- const identity = await this.getAccountIdentity();
316
- return {
317
- ok: true,
318
- latencyMs: Date.now() - started,
319
- details: { accountId: identity.accountId, email: identity.email, rootFolderId: this.options.rootFolderId || "root" }
320
- };
321
- } catch (error) {
322
- return {
323
- ok: false,
324
- latencyMs: Date.now() - started,
325
- error: error instanceof Error ? error.message : "Google Drive connection failed."
326
- };
327
- }
328
- }
329
- getConnectionMetadata() {
330
- return {
331
- provider: "google_drive",
332
- ...this.options.rootFolderId ? { googleRootFolderId: this.options.rootFolderId } : {}
333
- };
334
- }
335
- };
1
+ import {
2
+ GOOGLE_DRIVE_WORKSPACE_SCOPE,
3
+ GoogleDriveWorkspaceService
4
+ } from "./chunk-OWMQLML7.js";
336
5
  export {
337
6
  GOOGLE_DRIVE_WORKSPACE_SCOPE,
338
7
  GoogleDriveWorkspaceService
@@ -5,7 +5,7 @@ import {
5
5
  WorkspaceFS,
6
6
  remoteWorkspaceService,
7
7
  workingWorkspaceService
8
- } from "../chunk-NGEB3CF5.js";
8
+ } from "../chunk-Z6G32NQQ.js";
9
9
  import {
10
10
  WorkspaceCloneSyncEngine
11
11
  } from "../chunk-NY2SQOXI.js";
@@ -14,9 +14,10 @@ import {
14
14
  sanitizeWorkspaceName
15
15
  } from "../chunk-FZKBTF34.js";
16
16
  import "../chunk-JGUWYVOL.js";
17
- import "../chunk-G7PPVOFP.js";
17
+ import "../chunk-OQRQCDS6.js";
18
18
  import "../chunk-JCMB7BIM.js";
19
19
  import "../chunk-5F5V7NAG.js";
20
+ import "../chunk-OWMQLML7.js";
20
21
  export {
21
22
  RemoteWorkspaceService,
22
23
  SyncEngine,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kloks/backend",
3
3
  "version": "1.2.0",
4
- "description": "Kloks Backend Services — Auth, Storage, Workspace, Control Plane, API, Connectivity & Execution built on KrnlTS",
4
+ "description": "Kloks Backend Services \u2014 Auth, Storage, Workspace, Control Plane, API, Connectivity & Execution built on KrnlTS",
5
5
  "type": "module",
6
6
  "private": false,
7
7
  "publishConfig": {
@@ -145,7 +145,7 @@
145
145
  "clean": "rm -rf dist"
146
146
  },
147
147
  "dependencies": {
148
- "@dinilmusick/gutts": "^2.0.2",
148
+ "@dinilmusick/gutts": "^2.1.0",
149
149
  "@kloks/functions": "workspace:*",
150
150
  "@kloks/state-graph": "workspace:*",
151
151
  "@webcontainer/api": "^1.6.4",
@@ -157,8 +157,7 @@
157
157
  "react": "^18.0.0 || ^19.0.0",
158
158
  "zod": "^3.22.0",
159
159
  "@ultrst-armada/krnl": "^1.0.9",
160
- "@aws-sdk/client-s3": "^3.1164.0",
161
- "googleapis": "^189.0.0"
160
+ "@aws-sdk/client-s3": "^3.1164.0"
162
161
  },
163
162
  "peerDependenciesMeta": {
164
163
  "@supabase/supabase-js": {
@@ -178,9 +177,6 @@
178
177
  },
179
178
  "@aws-sdk/client-s3": {
180
179
  "optional": true
181
- },
182
- "googleapis": {
183
- "optional": true
184
180
  }
185
181
  },
186
182
  "devDependencies": {
@@ -1,86 +0,0 @@
1
- import {
2
- getGoogleSdk
3
- } from "./chunk-G7PPVOFP.js";
4
-
5
- // src/storage/GoogleDriveOAuth.ts
6
- var GOOGLE_DRIVE_STORAGE_SCOPE = "https://www.googleapis.com/auth/drive";
7
- var GOOGLE_DRIVE_FILE_SCOPE = "https://www.googleapis.com/auth/drive.file";
8
- async function createOAuthClient(config) {
9
- if (!config.clientId?.trim()) throw new Error("Google OAuth client ID is required.");
10
- if (!config.redirectUri?.trim()) throw new Error("Google OAuth redirect URI is required.");
11
- const google = await getGoogleSdk();
12
- return new google.auth.OAuth2(config.clientId, config.clientSecret, config.redirectUri);
13
- }
14
- function createGoogleDriveAuthorizationUrl(config, state, codeChallenge) {
15
- if (!config.clientId?.trim()) throw new Error("Google OAuth client ID is required.");
16
- if (!config.redirectUri?.trim()) throw new Error("Google OAuth redirect URI is required.");
17
- if (!state?.trim()) throw new Error("A non-empty OAuth state value is required.");
18
- if (codeChallenge !== void 0 && !codeChallenge.trim()) {
19
- throw new Error("PKCE code challenge cannot be empty.");
20
- }
21
- const params = new URLSearchParams({
22
- client_id: config.clientId,
23
- redirect_uri: config.redirectUri,
24
- response_type: "code",
25
- scope: (config.scopes?.length ? config.scopes : [GOOGLE_DRIVE_STORAGE_SCOPE]).join(" "),
26
- state,
27
- access_type: "offline",
28
- prompt: "consent",
29
- include_granted_scopes: "true",
30
- ...codeChallenge ? { code_challenge: codeChallenge, code_challenge_method: "S256" } : {}
31
- });
32
- return `https://accounts.google.com/o/oauth2/v2/auth?${params.toString()}`;
33
- }
34
- async function exchangeGoogleDriveCode(config, code, codeVerifier, existingRefreshToken) {
35
- if (!code?.trim()) throw new Error("Google OAuth authorization code is required.");
36
- const client = await createOAuthClient(config);
37
- try {
38
- const { tokens } = await client.getToken({
39
- code,
40
- ...codeVerifier ? { codeVerifier } : {}
41
- });
42
- if (!tokens.access_token) {
43
- throw new Error("Google OAuth token exchange returned no access token.");
44
- }
45
- return {
46
- accessToken: tokens.access_token,
47
- ...tokens.refresh_token || existingRefreshToken ? { refreshToken: tokens.refresh_token || existingRefreshToken } : {},
48
- ...tokens.expiry_date ? { expiresAt: tokens.expiry_date } : {},
49
- ...tokens.token_type ? { tokenType: tokens.token_type } : {}
50
- };
51
- } catch (error) {
52
- if (error instanceof Error && error.message === "Google OAuth token exchange returned no access token.") {
53
- throw error;
54
- }
55
- throw new Error("Google OAuth authorization-code exchange failed.");
56
- }
57
- }
58
- async function refreshGoogleDriveAccessToken(clientId, refreshToken, clientSecret, redirectUri = "http://localhost") {
59
- if (!clientId?.trim() || !refreshToken?.trim()) {
60
- throw new Error("Google Drive refresh credentials are incomplete.");
61
- }
62
- const google = await getGoogleSdk();
63
- const client = new google.auth.OAuth2(clientId, clientSecret, redirectUri);
64
- client.setCredentials({ refresh_token: refreshToken });
65
- try {
66
- const { token } = await client.getAccessToken();
67
- const credentials = client.credentials;
68
- if (!token) throw new Error("Google OAuth refresh returned no access token.");
69
- return {
70
- accessToken: token,
71
- refreshToken: credentials.refresh_token || refreshToken,
72
- ...credentials.expiry_date ? { expiresAt: credentials.expiry_date } : {},
73
- ...credentials.token_type ? { tokenType: credentials.token_type } : {}
74
- };
75
- } catch {
76
- throw new Error("Google Drive access-token refresh failed. Reauthorize the Google account if the refresh credential is invalid or revoked.");
77
- }
78
- }
79
-
80
- export {
81
- GOOGLE_DRIVE_STORAGE_SCOPE,
82
- GOOGLE_DRIVE_FILE_SCOPE,
83
- createGoogleDriveAuthorizationUrl,
84
- exchangeGoogleDriveCode,
85
- refreshGoogleDriveAccessToken
86
- };