@ultrst-armada/kloks 1.26.6 → 2.0.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.
Files changed (35) 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-G4EDIAHW.js +0 -0
  4. package/packages/backend/dist/{chunk-T6BJHFWZ.js → chunk-LMOM7CST.js} +2 -2
  5. package/packages/backend/dist/chunk-OQRQCDS6.js +109 -0
  6. package/packages/backend/dist/chunk-OWMQLML7.js +451 -0
  7. package/packages/backend/dist/{chunk-Y5ENDXU2.js → chunk-SQKG3S6P.js} +2 -10
  8. package/packages/backend/dist/{chunk-NGEB3CF5.js → chunk-Z6G32NQQ.js} +8 -3
  9. package/packages/backend/dist/core/SrklStorageService.test.d.ts +1 -0
  10. package/packages/backend/dist/krnl-services.js +5 -4
  11. package/packages/backend/dist/node.js +9 -21
  12. package/packages/backend/dist/services/node.js +4 -3
  13. package/packages/backend/dist/storage/GoogleDriveStorageService.d.ts +31 -9
  14. package/packages/backend/dist/storage/GoogleDriveWorkspaceService.d.ts +23 -6
  15. package/packages/backend/dist/storage/StorageAdapterFactory.d.ts +2 -2
  16. package/packages/backend/dist/storage/node.d.ts +0 -2
  17. package/packages/backend/dist/storage/node.js +5 -17
  18. package/packages/backend/dist/storage-workspace.js +4 -335
  19. package/packages/backend/dist/workspace/node.js +3 -2
  20. package/packages/backend/package.json +3 -7
  21. package/packages/client/dist/auth.d.ts +20 -1
  22. package/packages/client/dist/auth.js +13 -3
  23. package/packages/client/dist/chunk-5JMYSB7L.js +133 -0
  24. package/packages/client/dist/index.d.ts +1 -1
  25. package/packages/client/dist/index.js +13 -3
  26. package/packages/client/package.json +1 -1
  27. package/packages/state-graph/dist/browser.js +24 -24
  28. package/packages/state-graph/dist/index.js +24 -24
  29. package/packages/backend/dist/chunk-3FZSYSJC.js +0 -86
  30. package/packages/backend/dist/chunk-G7PPVOFP.js +0 -369
  31. package/packages/backend/dist/storage/GoogleDriveAdapter.d.ts +0 -41
  32. package/packages/backend/dist/storage/GoogleDriveOAuth.d.ts +0 -34
  33. package/packages/backend/dist/storage/googleDriveSdk.d.ts +0 -1
  34. package/packages/client/dist/chunk-B4WOPCRZ.js +0 -26
  35. package/packages/state-graph/dist/{chunk-YUJC367F.js → chunk-UKTICGGV.js} +3 -3
@@ -252,7 +252,7 @@ import {
252
252
  validateProjectGraph,
253
253
  validateUniversalConnection,
254
254
  zoomAtPoint
255
- } from "./chunk-YUJC367F.js";
255
+ } from "./chunk-UKTICGGV.js";
256
256
  import {
257
257
  BaseHandle,
258
258
  DataHandle,
@@ -263,20 +263,14 @@ import {
263
263
  } from "./chunk-OXUDG6HE.js";
264
264
  import "./chunk-RHRXPY2U.js";
265
265
  import {
266
- AttractionEngine,
267
- GhostInferenceEngine,
268
- GhostLayoutResolver,
269
- GhostTracePathBuilder,
270
- calculateSocketCoordinates,
271
- getBeamPoints,
272
- useMagneticTraces
273
- } from "./chunk-JXDJZSFW.js";
274
- import {
275
- ConnectionRuleStore,
276
- HandleTypeRegistry,
277
- WireTypeRegistry,
278
- initializeDefaultGraphRules
279
- } from "./chunk-TZOL3RN7.js";
266
+ LifecycleCycleError,
267
+ LifecycleGraph,
268
+ SKIPO_STATE,
269
+ SkipoStateEngine,
270
+ useLifecycleScope,
271
+ useSkipoBind,
272
+ useSkipoState
273
+ } from "./chunk-EW4ACSZB.js";
280
274
  import {
281
275
  CommandApi,
282
276
  GhostStore,
@@ -291,6 +285,21 @@ import {
291
285
  CustomViewWindow,
292
286
  DEFAULT_GRAPH_SETTINGS
293
287
  } from "./chunk-5KP74NMF.js";
288
+ import {
289
+ AttractionEngine,
290
+ GhostInferenceEngine,
291
+ GhostLayoutResolver,
292
+ GhostTracePathBuilder,
293
+ calculateSocketCoordinates,
294
+ getBeamPoints,
295
+ useMagneticTraces
296
+ } from "./chunk-JXDJZSFW.js";
297
+ import {
298
+ ConnectionRuleStore,
299
+ HandleTypeRegistry,
300
+ WireTypeRegistry,
301
+ initializeDefaultGraphRules
302
+ } from "./chunk-TZOL3RN7.js";
294
303
  import {
295
304
  AutoSolidify,
296
305
  SpatialEngine,
@@ -304,15 +313,6 @@ import {
304
313
  import {
305
314
  CompatibilityMatrix
306
315
  } from "./chunk-ISFNY7EZ.js";
307
- import {
308
- LifecycleCycleError,
309
- LifecycleGraph,
310
- SKIPO_STATE,
311
- SkipoStateEngine,
312
- useLifecycleScope,
313
- useSkipoBind,
314
- useSkipoState
315
- } from "./chunk-EW4ACSZB.js";
316
316
  export {
317
317
  ALL_GRAPH_TYPES,
318
318
  ArrangementNodeModel,
@@ -252,7 +252,7 @@ import {
252
252
  validateProjectGraph,
253
253
  validateUniversalConnection,
254
254
  zoomAtPoint
255
- } from "./chunk-YUJC367F.js";
255
+ } from "./chunk-UKTICGGV.js";
256
256
  import {
257
257
  BaseHandle,
258
258
  DataHandle,
@@ -263,20 +263,14 @@ import {
263
263
  } from "./chunk-OXUDG6HE.js";
264
264
  import "./chunk-RHRXPY2U.js";
265
265
  import {
266
- AttractionEngine,
267
- GhostInferenceEngine,
268
- GhostLayoutResolver,
269
- GhostTracePathBuilder,
270
- calculateSocketCoordinates,
271
- getBeamPoints,
272
- useMagneticTraces
273
- } from "./chunk-JXDJZSFW.js";
274
- import {
275
- ConnectionRuleStore,
276
- HandleTypeRegistry,
277
- WireTypeRegistry,
278
- initializeDefaultGraphRules
279
- } from "./chunk-TZOL3RN7.js";
266
+ LifecycleCycleError,
267
+ LifecycleGraph,
268
+ SKIPO_STATE,
269
+ SkipoStateEngine,
270
+ useLifecycleScope,
271
+ useSkipoBind,
272
+ useSkipoState
273
+ } from "./chunk-EW4ACSZB.js";
280
274
  import {
281
275
  CommandApi,
282
276
  GhostStore,
@@ -291,6 +285,21 @@ import {
291
285
  CustomViewWindow,
292
286
  DEFAULT_GRAPH_SETTINGS
293
287
  } from "./chunk-5KP74NMF.js";
288
+ import {
289
+ AttractionEngine,
290
+ GhostInferenceEngine,
291
+ GhostLayoutResolver,
292
+ GhostTracePathBuilder,
293
+ calculateSocketCoordinates,
294
+ getBeamPoints,
295
+ useMagneticTraces
296
+ } from "./chunk-JXDJZSFW.js";
297
+ import {
298
+ ConnectionRuleStore,
299
+ HandleTypeRegistry,
300
+ WireTypeRegistry,
301
+ initializeDefaultGraphRules
302
+ } from "./chunk-TZOL3RN7.js";
294
303
  import {
295
304
  AutoSolidify,
296
305
  SpatialEngine,
@@ -304,15 +313,6 @@ import {
304
313
  import {
305
314
  CompatibilityMatrix
306
315
  } from "./chunk-ISFNY7EZ.js";
307
- import {
308
- LifecycleCycleError,
309
- LifecycleGraph,
310
- SKIPO_STATE,
311
- SkipoStateEngine,
312
- useLifecycleScope,
313
- useSkipoBind,
314
- useSkipoState
315
- } from "./chunk-EW4ACSZB.js";
316
316
 
317
317
  // src/index.ts
318
318
  import {
@@ -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
- };
@@ -1,369 +0,0 @@
1
- import {
2
- BaseStorageAdapter
3
- } from "./chunk-5F5V7NAG.js";
4
-
5
- // src/storage/googleDriveSdk.ts
6
- var googleSdkPromise;
7
- async function getGoogleSdk() {
8
- if (!googleSdkPromise) {
9
- googleSdkPromise = import("googleapis").then((storage) => storage.google).catch((error) => {
10
- googleSdkPromise = void 0;
11
- throw error;
12
- });
13
- }
14
- return googleSdkPromise;
15
- }
16
-
17
- // src/storage/GoogleDriveAdapter.ts
18
- import { Readable } from "stream";
19
- var FOLDER_MIME_TYPE = "application/vnd.google-apps.folder";
20
- function toTokenSet(credentials, fallback) {
21
- const accessToken = credentials.access_token || fallback?.accessToken;
22
- if (!accessToken) return void 0;
23
- return {
24
- accessToken,
25
- ...credentials.refresh_token || fallback?.refreshToken ? { refreshToken: credentials.refresh_token || fallback?.refreshToken } : {},
26
- ...credentials.expiry_date || fallback?.expiresAt ? { expiresAt: credentials.expiry_date || fallback?.expiresAt } : {},
27
- ...credentials.token_type || fallback?.tokenType ? { tokenType: credentials.token_type || fallback?.tokenType } : {}
28
- };
29
- }
30
- var GoogleDriveAdapter = class extends BaseStorageAdapter {
31
- client;
32
- auth;
33
- authPromise;
34
- pendingCredentialPersistence;
35
- credentialPersistenceError;
36
- runtimeAuth;
37
- constructor(config, runtimeAuth = {}) {
38
- super({ ...config, provider: "google_drive" });
39
- this.runtimeAuth = runtimeAuth;
40
- }
41
- async getAuth() {
42
- if (this.auth) return this.auth;
43
- if (this.authPromise) return this.authPromise;
44
- this.authPromise = (async () => {
45
- const google = await getGoogleSdk();
46
- const client = new google.auth.OAuth2(
47
- this.config.googleClientId,
48
- this.runtimeAuth.clientSecret,
49
- this.config.googleRedirectUri
50
- );
51
- const supplied = this.runtimeAuth.getCredentials ? await this.runtimeAuth.getCredentials() : void 0;
52
- const credentials = supplied ?? {
53
- accessToken: this.config.googleAccessToken,
54
- refreshToken: this.config.googleRefreshToken,
55
- expiresAt: this.config.googleAccessTokenExpiresAt
56
- };
57
- if (!credentials.accessToken && !credentials.refreshToken) {
58
- throw new Error("Google Drive OAuth credentials are incomplete. Reauthorize the Google account.");
59
- }
60
- client.setCredentials({
61
- ...credentials.accessToken ? { access_token: credentials.accessToken } : {},
62
- ...credentials.refreshToken ? { refresh_token: credentials.refreshToken } : {},
63
- ...credentials.expiresAt ? { expiry_date: credentials.expiresAt } : {},
64
- ...credentials.tokenType ? { token_type: credentials.tokenType } : {}
65
- });
66
- client.on("tokens", (tokens) => {
67
- const next = toTokenSet({ ...client.credentials, ...tokens }, credentials);
68
- if (!next) return;
69
- this.config.googleAccessToken = next.accessToken;
70
- if (next.refreshToken) this.config.googleRefreshToken = next.refreshToken;
71
- if (next.expiresAt) this.config.googleAccessTokenExpiresAt = next.expiresAt;
72
- if (!this.runtimeAuth.persistCredentials) return;
73
- this.pendingCredentialPersistence = Promise.resolve(this.runtimeAuth.persistCredentials(next)).then(
74
- () => void 0,
75
- () => {
76
- this.credentialPersistenceError = new Error("Google Drive credentials could not be persisted securely.");
77
- }
78
- );
79
- });
80
- this.auth = client;
81
- return client;
82
- })();
83
- try {
84
- return await this.authPromise;
85
- } catch (error) {
86
- this.authPromise = void 0;
87
- throw error;
88
- }
89
- }
90
- async getClient() {
91
- if (this.client) {
92
- if (this.pendingCredentialPersistence) await this.pendingCredentialPersistence;
93
- if (this.credentialPersistenceError) throw this.credentialPersistenceError;
94
- return this.client;
95
- }
96
- const google = await getGoogleSdk();
97
- const auth = await this.getAuth();
98
- const token = await auth.getAccessToken();
99
- if (this.pendingCredentialPersistence) await this.pendingCredentialPersistence;
100
- if (this.credentialPersistenceError) throw this.credentialPersistenceError;
101
- if (!token.token) {
102
- throw new Error("Google Drive authorization returned no access token. Reauthorize the Google account.");
103
- }
104
- this.config.googleAccessToken = token.token;
105
- if (auth.credentials.expiry_date) {
106
- this.config.googleAccessTokenExpiresAt = auth.credentials.expiry_date;
107
- }
108
- if (auth.credentials.refresh_token) {
109
- this.config.googleRefreshToken = auth.credentials.refresh_token;
110
- }
111
- this.client = google.drive({ version: "v3", auth });
112
- return this.client;
113
- }
114
- async findChild(parentId, name) {
115
- const drive = await this.getClient();
116
- const escapedName = name.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
117
- const response = await drive.files.list({
118
- q: `'${parentId}' in parents and name = '${escapedName}' and trashed = false`,
119
- fields: "files(id,name,size,modifiedTime,mimeType,parents)",
120
- pageSize: 10,
121
- supportsAllDrives: true,
122
- includeItemsFromAllDrives: true
123
- });
124
- return response.data.files?.[0] || null;
125
- }
126
- async resolveParent(relativeDir, create = false) {
127
- let parent = this.config.googleRootFolderId || "root";
128
- for (const part of this.normalizePath(relativeDir).split("/").filter(Boolean)) {
129
- let child = await this.findChild(parent, part);
130
- if (!child && create) {
131
- const drive = await this.getClient();
132
- const response = await drive.files.create({
133
- requestBody: {
134
- name: part,
135
- mimeType: FOLDER_MIME_TYPE,
136
- parents: [parent]
137
- },
138
- fields: "id,name,mimeType,parents,modifiedTime",
139
- supportsAllDrives: true
140
- });
141
- child = response.data;
142
- }
143
- if (!child?.id || child.mimeType !== FOLDER_MIME_TYPE) {
144
- throw new Error(`Google Drive directory not found: ${part}`);
145
- }
146
- parent = child.id;
147
- }
148
- return parent;
149
- }
150
- split(pathStr) {
151
- const key = this.normalizePath(pathStr);
152
- const i = key.lastIndexOf("/");
153
- return i < 0 ? { dir: "", name: key } : { dir: key.slice(0, i), name: key.slice(i + 1) };
154
- }
155
- /**
156
- * Return only non-secret connection metadata for persistence alongside the
157
- * authenticated application user's storage connection record.
158
- */
159
- getConnectionMetadata() {
160
- return {
161
- provider: "google_drive",
162
- ...this.config.googleClientId ? { googleClientId: this.config.googleClientId } : {},
163
- ...this.config.googleRedirectUri ? { googleRedirectUri: this.config.googleRedirectUri } : {},
164
- ...this.config.googleAccountId ? { googleAccountId: this.config.googleAccountId } : {},
165
- ...this.config.googleRootFolderId ? { googleRootFolderId: this.config.googleRootFolderId } : {}
166
- };
167
- }
168
- /** Browse only folders directly below the supplied parent (or selected storage root). */
169
- async listFolders(parentFolderId = this.config.googleRootFolderId || "root") {
170
- const drive = await this.getClient();
171
- const folders = [];
172
- let pageToken;
173
- do {
174
- const response = await drive.files.list({
175
- q: `'${parentFolderId}' in parents and mimeType = '${FOLDER_MIME_TYPE}' and trashed = false`,
176
- fields: "nextPageToken,files(id,name,mimeType,parents,modifiedTime)",
177
- pageSize: 1e3,
178
- supportsAllDrives: true,
179
- includeItemsFromAllDrives: true,
180
- ...pageToken ? { pageToken } : {}
181
- });
182
- for (const folder of response.data.files || []) {
183
- if (!folder.id || !folder.name) continue;
184
- folders.push({
185
- id: folder.id,
186
- name: folder.name,
187
- mimeType: FOLDER_MIME_TYPE,
188
- parentIds: folder.parents || [],
189
- modifiedAt: folder.modifiedTime ? Date.parse(folder.modifiedTime) : 0
190
- });
191
- }
192
- pageToken = response.data.nextPageToken || void 0;
193
- } while (pageToken);
194
- return folders;
195
- }
196
- /** Resolve and validate a provider-native folder ID before it is saved as a root. */
197
- async resolveFolder(folderId) {
198
- if (!folderId?.trim()) throw new Error("A Google Drive folder ID is required.");
199
- const drive = await this.getClient();
200
- const response = await drive.files.get({
201
- fileId: folderId,
202
- fields: "id,name,mimeType,parents,modifiedTime",
203
- supportsAllDrives: true
204
- });
205
- const folder = response.data;
206
- if (!folder.id || !folder.name || folder.mimeType !== FOLDER_MIME_TYPE) {
207
- throw new Error("The selected Google Drive item is not a folder.");
208
- }
209
- return {
210
- id: folder.id,
211
- name: folder.name,
212
- mimeType: FOLDER_MIME_TYPE,
213
- parentIds: folder.parents || [],
214
- modifiedAt: folder.modifiedTime ? Date.parse(folder.modifiedTime) : 0
215
- };
216
- }
217
- /** Select a validated folder as this connection's storage/workspace root. */
218
- async selectRootFolder(folderId) {
219
- const folder = await this.resolveFolder(folderId);
220
- this.config.googleRootFolderId = folder.id;
221
- return folder;
222
- }
223
- async read(pathStr) {
224
- const { dir, name } = this.split(pathStr);
225
- const parent = await this.resolveParent(dir);
226
- const file = await this.findChild(parent, name);
227
- if (!file?.id) throw new Error(`Google Drive file not found: ${pathStr}`);
228
- if (file.mimeType === FOLDER_MIME_TYPE) throw new Error(`Google Drive path is a folder, not a file: ${pathStr}`);
229
- const drive = await this.getClient();
230
- const response = await drive.files.get(
231
- { fileId: file.id, alt: "media", supportsAllDrives: true },
232
- { responseType: "arraybuffer" }
233
- );
234
- return new Uint8Array(response.data);
235
- }
236
- async write(pathStr, data, contentType = "application/octet-stream") {
237
- const { dir, name } = this.split(pathStr);
238
- if (!name) throw new Error("A Google Drive file name is required.");
239
- const parent = await this.resolveParent(dir, true);
240
- const existing = await this.findChild(parent, name);
241
- const bytes = typeof data === "string" ? new TextEncoder().encode(data) : data;
242
- const drive = await this.getClient();
243
- if (existing?.id) {
244
- if (existing.mimeType === FOLDER_MIME_TYPE) throw new Error(`Google Drive path is a folder: ${pathStr}`);
245
- await drive.files.update({
246
- fileId: existing.id,
247
- requestBody: { name, mimeType: contentType },
248
- media: { mimeType: contentType, body: Readable.from(bytes) },
249
- fields: "id",
250
- supportsAllDrives: true
251
- });
252
- return;
253
- }
254
- await drive.files.create({
255
- requestBody: { name, mimeType: contentType, parents: [parent] },
256
- media: { mimeType: contentType, body: Readable.from(bytes) },
257
- fields: "id",
258
- supportsAllDrives: true
259
- });
260
- }
261
- async delete(pathStr) {
262
- const { dir, name } = this.split(pathStr);
263
- const parent = await this.resolveParent(dir);
264
- const file = await this.findChild(parent, name);
265
- if (!file?.id) return;
266
- const drive = await this.getClient();
267
- try {
268
- await drive.files.delete({ fileId: file.id, supportsAllDrives: true });
269
- } catch (error) {
270
- if (error?.response?.status !== 404 && error?.code !== 404) throw error;
271
- }
272
- }
273
- async exists(pathStr) {
274
- try {
275
- await this.stat(pathStr);
276
- return true;
277
- } catch (error) {
278
- if (error?.response?.status === 404 || error?.code === 404) return false;
279
- throw error;
280
- }
281
- }
282
- async list(pathStr = "") {
283
- const parent = await this.resolveParent(pathStr);
284
- const drive = await this.getClient();
285
- const results = [];
286
- let pageToken;
287
- do {
288
- const response = await drive.files.list({
289
- q: `'${parent}' in parents and trashed = false`,
290
- fields: "nextPageToken,files(id,name,size,modifiedTime,mimeType)",
291
- pageSize: 1e3,
292
- supportsAllDrives: true,
293
- includeItemsFromAllDrives: true,
294
- ...pageToken ? { pageToken } : {}
295
- });
296
- for (const file of response.data.files || []) {
297
- if (!file.name) continue;
298
- results.push({
299
- path: this.normalizePath(pathStr ? `${pathStr}/${file.name}` : file.name),
300
- size: Number(file.size || 0),
301
- modifiedAt: file.modifiedTime ? Date.parse(file.modifiedTime) : 0,
302
- ...file.id ? { id: file.id } : {},
303
- ...file.mimeType ? { mimeType: file.mimeType } : {},
304
- isFolder: file.mimeType === FOLDER_MIME_TYPE
305
- });
306
- }
307
- pageToken = response.data.nextPageToken || void 0;
308
- } while (pageToken);
309
- return results;
310
- }
311
- async stat(pathStr) {
312
- const { dir, name } = this.split(pathStr);
313
- const parent = await this.resolveParent(dir);
314
- const file = await this.findChild(parent, name);
315
- if (!file?.id) throw new Error(`Google Drive file not found: ${pathStr}`);
316
- return {
317
- path: pathStr,
318
- size: Number(file.size || 0),
319
- modifiedAt: file.modifiedTime ? Date.parse(file.modifiedTime) : 0,
320
- id: file.id,
321
- ...file.mimeType ? { mimeType: file.mimeType } : {},
322
- isFolder: file.mimeType === FOLDER_MIME_TYPE
323
- };
324
- }
325
- async mkdir(pathStr) {
326
- await this.resolveParent(pathStr, true);
327
- }
328
- /** Resolve the stable Google account identity for association with the app user's server-side connection record. */
329
- async getAccountIdentity() {
330
- const drive = await this.getClient();
331
- const response = await drive.about.get({ fields: "user(permissionId,emailAddress)" });
332
- const accountId = response.data.user?.permissionId || response.data.user?.emailAddress;
333
- if (!accountId) throw new Error("Google Drive did not return an account identity.");
334
- if (this.config.googleAccountId && this.config.googleAccountId !== accountId) {
335
- throw new Error("Google Drive account identity does not match the saved storage connection.");
336
- }
337
- this.config.googleAccountId = accountId;
338
- return {
339
- accountId,
340
- ...response.data.user?.emailAddress ? { email: response.data.user.emailAddress } : {}
341
- };
342
- }
343
- async testConnection() {
344
- const start = performance.now();
345
- try {
346
- const identity = await this.getAccountIdentity();
347
- return {
348
- ok: true,
349
- latencyMs: Math.round(performance.now() - start),
350
- details: {
351
- accountId: identity.accountId,
352
- ...identity.email ? { email: identity.email } : {},
353
- rootFolderId: this.config.googleRootFolderId || "root"
354
- }
355
- };
356
- } catch (error) {
357
- return {
358
- ok: false,
359
- latencyMs: Math.round(performance.now() - start),
360
- error: error?.message || "Google Drive authorization failed."
361
- };
362
- }
363
- }
364
- };
365
-
366
- export {
367
- getGoogleSdk,
368
- GoogleDriveAdapter
369
- };
@@ -1,41 +0,0 @@
1
- import { BaseStorageAdapter } from './BaseStorageAdapter.js';
2
- import type { GoogleDriveFolder, FileInfo, StorageConfig, ConnectionTestResult } from './types.js';
3
- import type { GoogleDriveRuntimeAuthOptions } from './GoogleDriveOAuth.js';
4
- export declare class GoogleDriveAdapter extends BaseStorageAdapter {
5
- private client?;
6
- private auth?;
7
- private authPromise?;
8
- private pendingCredentialPersistence?;
9
- private credentialPersistenceError?;
10
- private readonly runtimeAuth;
11
- constructor(config: StorageConfig, runtimeAuth?: GoogleDriveRuntimeAuthOptions);
12
- private getAuth;
13
- private getClient;
14
- private findChild;
15
- private resolveParent;
16
- private split;
17
- /**
18
- * Return only non-secret connection metadata for persistence alongside the
19
- * authenticated application user's storage connection record.
20
- */
21
- getConnectionMetadata(): Pick<StorageConfig, 'provider' | 'googleClientId' | 'googleRedirectUri' | 'googleAccountId' | 'googleRootFolderId'>;
22
- /** Browse only folders directly below the supplied parent (or selected storage root). */
23
- listFolders(parentFolderId?: string): Promise<GoogleDriveFolder[]>;
24
- /** Resolve and validate a provider-native folder ID before it is saved as a root. */
25
- resolveFolder(folderId: string): Promise<GoogleDriveFolder>;
26
- /** Select a validated folder as this connection's storage/workspace root. */
27
- selectRootFolder(folderId: string): Promise<GoogleDriveFolder>;
28
- read(pathStr: string): Promise<Uint8Array>;
29
- write(pathStr: string, data: Uint8Array | string, contentType?: string): Promise<void>;
30
- delete(pathStr: string): Promise<void>;
31
- exists(pathStr: string): Promise<boolean>;
32
- list(pathStr?: string): Promise<FileInfo[]>;
33
- stat(pathStr: string): Promise<FileInfo>;
34
- mkdir(pathStr: string): Promise<void>;
35
- /** Resolve the stable Google account identity for association with the app user's server-side connection record. */
36
- getAccountIdentity(): Promise<{
37
- accountId: string;
38
- email?: string;
39
- }>;
40
- testConnection(): Promise<ConnectionTestResult>;
41
- }
@@ -1,34 +0,0 @@
1
- export interface GoogleDriveOAuthConfig {
2
- clientId: string;
3
- clientSecret?: string;
4
- redirectUri: string;
5
- scopes?: string[];
6
- }
7
- export interface GoogleDriveTokenSet {
8
- accessToken: string;
9
- refreshToken?: string;
10
- expiresAt?: number;
11
- tokenType?: string;
12
- }
13
- /**
14
- * Server-only runtime dependencies. Keep this object out of persisted
15
- * provider connection records and never pass it to browser code.
16
- */
17
- export interface GoogleDriveRuntimeAuthOptions {
18
- clientSecret?: string;
19
- getCredentials?: () => Promise<GoogleDriveTokenSet>;
20
- persistCredentials?: (tokens: GoogleDriveTokenSet) => Promise<void> | void;
21
- }
22
- /**
23
- * A storage root must be able to enumerate, read, create, update and delete
24
- * files below a user-selected existing folder. drive.file is deliberately
25
- * insufficient for this contract: it only covers files explicitly opened
26
- * or created by the application. The full Drive scope is therefore the
27
- * narrowest single scope that supports the complete storage abstraction.
28
- */
29
- export declare const GOOGLE_DRIVE_STORAGE_SCOPE = "https://www.googleapis.com/auth/drive";
30
- /** @deprecated Use GOOGLE_DRIVE_STORAGE_SCOPE for complete storage roots. */
31
- export declare const GOOGLE_DRIVE_FILE_SCOPE = "https://www.googleapis.com/auth/drive.file";
32
- export declare function createGoogleDriveAuthorizationUrl(config: GoogleDriveOAuthConfig, state: string, codeChallenge?: string): string;
33
- export declare function exchangeGoogleDriveCode(config: GoogleDriveOAuthConfig, code: string, codeVerifier?: string, existingRefreshToken?: string): Promise<GoogleDriveTokenSet>;
34
- export declare function refreshGoogleDriveAccessToken(clientId: string, refreshToken: string, clientSecret?: string, redirectUri?: string): Promise<GoogleDriveTokenSet>;
@@ -1 +0,0 @@
1
- export declare function getGoogleSdk(): Promise<any>;