@squadbase/vite-server 0.1.3-dev.11 → 0.1.3-dev.13

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.
@@ -0,0 +1,753 @@
1
+ // ../connectors/src/parameter-definition.ts
2
+ var ParameterDefinition = class {
3
+ slug;
4
+ name;
5
+ description;
6
+ envVarBaseKey;
7
+ type;
8
+ secret;
9
+ required;
10
+ constructor(config) {
11
+ this.slug = config.slug;
12
+ this.name = config.name;
13
+ this.description = config.description;
14
+ this.envVarBaseKey = config.envVarBaseKey;
15
+ this.type = config.type;
16
+ this.secret = config.secret;
17
+ this.required = config.required;
18
+ }
19
+ /**
20
+ * Get the parameter value from a ConnectorConnectionObject.
21
+ */
22
+ getValue(connection2) {
23
+ const param = connection2.parameters.find(
24
+ (p) => p.parameterSlug === this.slug
25
+ );
26
+ if (!param || param.value == null) {
27
+ throw new Error(
28
+ `Parameter "${this.slug}" not found or has no value in connection "${connection2.id}"`
29
+ );
30
+ }
31
+ return param.value;
32
+ }
33
+ /**
34
+ * Try to get the parameter value. Returns undefined if not found (for optional params).
35
+ */
36
+ tryGetValue(connection2) {
37
+ const param = connection2.parameters.find(
38
+ (p) => p.parameterSlug === this.slug
39
+ );
40
+ if (!param || param.value == null) return void 0;
41
+ return param.value;
42
+ }
43
+ };
44
+
45
+ // ../connectors/src/connectors/google-drive/sdk/index.ts
46
+ import * as crypto from "crypto";
47
+
48
+ // ../connectors/src/connectors/google-drive/parameters.ts
49
+ var parameters = {
50
+ serviceAccountKeyJsonBase64: new ParameterDefinition({
51
+ slug: "service-account-key-json-base64",
52
+ name: "Google Cloud Service Account JSON",
53
+ description: "The service account JSON key used to authenticate with Google Cloud Platform. Ensure that the service account has the necessary permissions to access Google Drive.",
54
+ envVarBaseKey: "GOOGLE_DRIVE_SERVICE_ACCOUNT_JSON_BASE64",
55
+ type: "base64EncodedJson",
56
+ secret: true,
57
+ required: true
58
+ }),
59
+ folderId: new ParameterDefinition({
60
+ slug: "folder-id",
61
+ name: "Google Drive Folder ID",
62
+ description: "The ID of a default Google Drive folder to scope operations to (e.g., from the folder URL: https://drive.google.com/drive/folders/{folderId}). Optional \u2014 if not set, operations target the root of My Drive.",
63
+ envVarBaseKey: "GOOGLE_DRIVE_FOLDER_ID",
64
+ type: "text",
65
+ secret: false,
66
+ required: false
67
+ })
68
+ };
69
+
70
+ // ../connectors/src/connectors/google-drive-oauth/utils.ts
71
+ var FOLDER_URL_PATTERN = /drive\.google\.com\/drive\/folders\/([a-zA-Z0-9_-]+)/;
72
+ function extractFolderId(urlOrId) {
73
+ const trimmed = urlOrId.trim();
74
+ const match = trimmed.match(FOLDER_URL_PATTERN);
75
+ if (match) {
76
+ return match[1];
77
+ }
78
+ return trimmed;
79
+ }
80
+
81
+ // ../connectors/src/connectors/google-drive/sdk/index.ts
82
+ var TOKEN_URL = "https://oauth2.googleapis.com/token";
83
+ var BASE_URL = "https://www.googleapis.com/drive/v3";
84
+ var SCOPE = "https://www.googleapis.com/auth/drive";
85
+ function base64url(input) {
86
+ const buf = typeof input === "string" ? Buffer.from(input) : input;
87
+ return buf.toString("base64url");
88
+ }
89
+ function buildJwt(clientEmail, privateKey, nowSec) {
90
+ const header = base64url(JSON.stringify({ alg: "RS256", typ: "JWT" }));
91
+ const payload = base64url(
92
+ JSON.stringify({
93
+ iss: clientEmail,
94
+ scope: SCOPE,
95
+ aud: TOKEN_URL,
96
+ iat: nowSec,
97
+ exp: nowSec + 3600
98
+ })
99
+ );
100
+ const signingInput = `${header}.${payload}`;
101
+ const sign = crypto.createSign("RSA-SHA256");
102
+ sign.update(signingInput);
103
+ sign.end();
104
+ const signature = base64url(sign.sign(privateKey));
105
+ return `${signingInput}.${signature}`;
106
+ }
107
+ var DEFAULT_FILE_FIELDS = "id,name,mimeType,parents,webViewLink,webContentLink,createdTime,modifiedTime,size,starred,trashed,shared,owners";
108
+ function createClient(params) {
109
+ const serviceAccountKeyJsonBase64 = params[parameters.serviceAccountKeyJsonBase64.slug];
110
+ const folderIdRaw = params[parameters.folderId.slug];
111
+ const defaultFolderId = folderIdRaw ? extractFolderId(folderIdRaw) : void 0;
112
+ if (!serviceAccountKeyJsonBase64) {
113
+ throw new Error(
114
+ `google-drive: missing required parameter: ${parameters.serviceAccountKeyJsonBase64.slug}`
115
+ );
116
+ }
117
+ let serviceAccountKey;
118
+ try {
119
+ const decoded = Buffer.from(
120
+ serviceAccountKeyJsonBase64,
121
+ "base64"
122
+ ).toString("utf-8");
123
+ serviceAccountKey = JSON.parse(decoded);
124
+ } catch {
125
+ throw new Error(
126
+ "google-drive: failed to decode service account key JSON from base64"
127
+ );
128
+ }
129
+ if (!serviceAccountKey.client_email || !serviceAccountKey.private_key) {
130
+ throw new Error(
131
+ "google-drive: service account key JSON must contain client_email and private_key"
132
+ );
133
+ }
134
+ let cachedToken = null;
135
+ let tokenExpiresAt = 0;
136
+ async function getAccessToken() {
137
+ const nowSec = Math.floor(Date.now() / 1e3);
138
+ if (cachedToken && nowSec < tokenExpiresAt - 60) {
139
+ return cachedToken;
140
+ }
141
+ const jwt = buildJwt(
142
+ serviceAccountKey.client_email,
143
+ serviceAccountKey.private_key,
144
+ nowSec
145
+ );
146
+ const response = await fetch(TOKEN_URL, {
147
+ method: "POST",
148
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
149
+ body: new URLSearchParams({
150
+ grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
151
+ assertion: jwt
152
+ })
153
+ });
154
+ if (!response.ok) {
155
+ const text = await response.text();
156
+ throw new Error(
157
+ `google-drive: token exchange failed (${response.status}): ${text}`
158
+ );
159
+ }
160
+ const data = await response.json();
161
+ cachedToken = data.access_token;
162
+ tokenExpiresAt = nowSec + data.expires_in;
163
+ return cachedToken;
164
+ }
165
+ async function authenticatedFetch(url, init) {
166
+ const accessToken = await getAccessToken();
167
+ const headers = new Headers(init?.headers);
168
+ headers.set("Authorization", `Bearer ${accessToken}`);
169
+ if (!headers.has("Content-Type")) {
170
+ headers.set("Content-Type", "application/json");
171
+ }
172
+ return fetch(url, { ...init, headers });
173
+ }
174
+ return {
175
+ async request(path2, init) {
176
+ const url = `${BASE_URL}${path2.startsWith("/") ? "" : "/"}${path2}`;
177
+ return authenticatedFetch(url, init);
178
+ },
179
+ async listFiles(options) {
180
+ const searchParams = new URLSearchParams();
181
+ let query = options?.query ?? "";
182
+ if (defaultFolderId && !query.includes("in parents")) {
183
+ const folderClause = `'${defaultFolderId}' in parents`;
184
+ query = query ? `${folderClause} and (${query})` : folderClause;
185
+ }
186
+ if (query) searchParams.set("q", query);
187
+ if (options?.pageSize) searchParams.set("pageSize", String(options.pageSize));
188
+ if (options?.pageToken) searchParams.set("pageToken", options.pageToken);
189
+ if (options?.orderBy) searchParams.set("orderBy", options.orderBy);
190
+ searchParams.set("fields", options?.fields ?? `nextPageToken,files(${DEFAULT_FILE_FIELDS})`);
191
+ const response = await authenticatedFetch(`${BASE_URL}/files?${searchParams.toString()}`);
192
+ if (!response.ok) {
193
+ const body = await response.text();
194
+ throw new Error(`google-drive: listFiles failed (${response.status}): ${body}`);
195
+ }
196
+ return await response.json();
197
+ },
198
+ async getFile(fileId, fields) {
199
+ const response = await authenticatedFetch(
200
+ `${BASE_URL}/files/${fileId}?fields=${fields ?? DEFAULT_FILE_FIELDS}`
201
+ );
202
+ if (!response.ok) {
203
+ const body = await response.text();
204
+ throw new Error(`google-drive: getFile failed (${response.status}): ${body}`);
205
+ }
206
+ return await response.json();
207
+ },
208
+ async createFile(options) {
209
+ const metadata = { name: options.name };
210
+ if (options.mimeType) metadata.mimeType = options.mimeType;
211
+ if (options.description) metadata.description = options.description;
212
+ if (options.parents) {
213
+ metadata.parents = options.parents;
214
+ } else if (defaultFolderId) {
215
+ metadata.parents = [defaultFolderId];
216
+ }
217
+ const response = await authenticatedFetch(`${BASE_URL}/files?fields=${DEFAULT_FILE_FIELDS}`, {
218
+ method: "POST",
219
+ body: JSON.stringify(metadata)
220
+ });
221
+ if (!response.ok) {
222
+ const body = await response.text();
223
+ throw new Error(`google-drive: createFile failed (${response.status}): ${body}`);
224
+ }
225
+ return await response.json();
226
+ },
227
+ async updateFile(fileId, metadata, addParents, removeParents) {
228
+ const sp = new URLSearchParams();
229
+ sp.set("fields", DEFAULT_FILE_FIELDS);
230
+ if (addParents) sp.set("addParents", addParents);
231
+ if (removeParents) sp.set("removeParents", removeParents);
232
+ const response = await authenticatedFetch(`${BASE_URL}/files/${fileId}?${sp.toString()}`, {
233
+ method: "PATCH",
234
+ body: JSON.stringify(metadata)
235
+ });
236
+ if (!response.ok) {
237
+ const body = await response.text();
238
+ throw new Error(`google-drive: updateFile failed (${response.status}): ${body}`);
239
+ }
240
+ return await response.json();
241
+ },
242
+ async copyFile(fileId, name, parents) {
243
+ const metadata = {};
244
+ if (name) metadata.name = name;
245
+ if (parents) metadata.parents = parents;
246
+ const response = await authenticatedFetch(`${BASE_URL}/files/${fileId}/copy?fields=${DEFAULT_FILE_FIELDS}`, {
247
+ method: "POST",
248
+ body: JSON.stringify(metadata)
249
+ });
250
+ if (!response.ok) {
251
+ const body = await response.text();
252
+ throw new Error(`google-drive: copyFile failed (${response.status}): ${body}`);
253
+ }
254
+ return await response.json();
255
+ },
256
+ async listPermissions(fileId) {
257
+ const response = await authenticatedFetch(
258
+ `${BASE_URL}/files/${fileId}/permissions?fields=permissions(id,type,role,emailAddress,displayName)`
259
+ );
260
+ if (!response.ok) {
261
+ const body = await response.text();
262
+ throw new Error(`google-drive: listPermissions failed (${response.status}): ${body}`);
263
+ }
264
+ return await response.json();
265
+ },
266
+ async shareFile(fileId, type, role, emailAddress) {
267
+ const permission = { type, role };
268
+ if (emailAddress) permission.emailAddress = emailAddress;
269
+ const response = await authenticatedFetch(`${BASE_URL}/files/${fileId}/permissions`, {
270
+ method: "POST",
271
+ body: JSON.stringify(permission)
272
+ });
273
+ if (!response.ok) {
274
+ const body = await response.text();
275
+ throw new Error(`google-drive: shareFile failed (${response.status}): ${body}`);
276
+ }
277
+ return await response.json();
278
+ },
279
+ downloadFile(fileId) {
280
+ return authenticatedFetch(`${BASE_URL}/files/${fileId}?alt=media`);
281
+ },
282
+ exportFile(fileId, mimeType) {
283
+ return authenticatedFetch(`${BASE_URL}/files/${fileId}/export?mimeType=${encodeURIComponent(mimeType)}`);
284
+ }
285
+ };
286
+ }
287
+
288
+ // ../connectors/src/connector-onboarding.ts
289
+ var ConnectorOnboarding = class {
290
+ /** Phase 1: Connection setup instructions (optional — some connectors don't need this) */
291
+ connectionSetupInstructions;
292
+ /** Phase 2: Data overview instructions */
293
+ dataOverviewInstructions;
294
+ constructor(config) {
295
+ this.connectionSetupInstructions = config.connectionSetupInstructions;
296
+ this.dataOverviewInstructions = config.dataOverviewInstructions;
297
+ }
298
+ getConnectionSetupPrompt(language) {
299
+ return this.connectionSetupInstructions?.[language] ?? null;
300
+ }
301
+ getDataOverviewInstructions(language) {
302
+ return this.dataOverviewInstructions[language];
303
+ }
304
+ };
305
+
306
+ // ../connectors/src/connector-tool.ts
307
+ var ConnectorTool = class {
308
+ name;
309
+ description;
310
+ inputSchema;
311
+ outputSchema;
312
+ _execute;
313
+ constructor(config) {
314
+ this.name = config.name;
315
+ this.description = config.description;
316
+ this.inputSchema = config.inputSchema;
317
+ this.outputSchema = config.outputSchema;
318
+ this._execute = config.execute;
319
+ }
320
+ createTool(connections, config) {
321
+ return {
322
+ description: this.description,
323
+ inputSchema: this.inputSchema,
324
+ outputSchema: this.outputSchema,
325
+ execute: (input) => this._execute(input, connections, config)
326
+ };
327
+ }
328
+ };
329
+
330
+ // ../connectors/src/connector-plugin.ts
331
+ var ConnectorPlugin = class _ConnectorPlugin {
332
+ slug;
333
+ authType;
334
+ name;
335
+ description;
336
+ iconUrl;
337
+ parameters;
338
+ releaseFlag;
339
+ proxyPolicy;
340
+ experimentalAttributes;
341
+ onboarding;
342
+ systemPrompt;
343
+ tools;
344
+ query;
345
+ checkConnection;
346
+ constructor(config) {
347
+ this.slug = config.slug;
348
+ this.authType = config.authType;
349
+ this.name = config.name;
350
+ this.description = config.description;
351
+ this.iconUrl = config.iconUrl;
352
+ this.parameters = config.parameters;
353
+ this.releaseFlag = config.releaseFlag;
354
+ this.proxyPolicy = config.proxyPolicy;
355
+ this.experimentalAttributes = config.experimentalAttributes;
356
+ this.onboarding = config.onboarding;
357
+ this.systemPrompt = config.systemPrompt;
358
+ this.tools = config.tools;
359
+ this.query = config.query;
360
+ this.checkConnection = config.checkConnection;
361
+ }
362
+ get connectorKey() {
363
+ return _ConnectorPlugin.deriveKey(this.slug, this.authType);
364
+ }
365
+ /**
366
+ * Create tools for connections that belong to this connector.
367
+ * Filters connections by connectorKey internally.
368
+ * Returns tools keyed as `${connectorKey}_${toolName}`.
369
+ */
370
+ createTools(connections, config) {
371
+ const myConnections = connections.filter(
372
+ (c) => _ConnectorPlugin.deriveKey(c.connector.slug, c.connector.authType) === this.connectorKey
373
+ );
374
+ const result = {};
375
+ for (const t of Object.values(this.tools)) {
376
+ result[`${this.connectorKey}_${t.name}`] = t.createTool(
377
+ myConnections,
378
+ config
379
+ );
380
+ }
381
+ return result;
382
+ }
383
+ static deriveKey(slug, authType) {
384
+ return authType ? `${slug}-${authType}` : slug;
385
+ }
386
+ };
387
+
388
+ // ../connectors/src/auth-types.ts
389
+ var AUTH_TYPES = {
390
+ OAUTH: "oauth",
391
+ API_KEY: "api-key",
392
+ JWT: "jwt",
393
+ SERVICE_ACCOUNT: "service-account",
394
+ PAT: "pat",
395
+ USER_PASSWORD: "user-password"
396
+ };
397
+
398
+ // ../connectors/src/connectors/google-drive/setup.ts
399
+ var googleDriveOnboarding = new ConnectorOnboarding({
400
+ dataOverviewInstructions: {
401
+ en: `1. Call google-drive_request with GET /files?pageSize=20&fields=files(id,name,mimeType,modifiedTime)&orderBy=modifiedTime desc to list recent files
402
+ 2. Call google-drive_request with GET /about?fields=user,storageQuota to get account info and storage usage`,
403
+ ja: `1. google-drive_request \u3067 GET /files?pageSize=20&fields=files(id,name,mimeType,modifiedTime)&orderBy=modifiedTime desc \u3092\u547C\u3073\u51FA\u3057\u3001\u6700\u8FD1\u306E\u30D5\u30A1\u30A4\u30EB\u3092\u4E00\u89A7\u8868\u793A
404
+ 2. google-drive_request \u3067 GET /about?fields=user,storageQuota \u3092\u547C\u3073\u51FA\u3057\u3001\u30A2\u30AB\u30A6\u30F3\u30C8\u60C5\u5831\u3068\u30B9\u30C8\u30EC\u30FC\u30B8\u4F7F\u7528\u91CF\u3092\u53D6\u5F97`
405
+ }
406
+ });
407
+
408
+ // ../connectors/src/connectors/google-drive/tools/request.ts
409
+ import { z } from "zod";
410
+ var BASE_URL2 = "https://www.googleapis.com/drive/v3";
411
+ var REQUEST_TIMEOUT_MS = 6e4;
412
+ var inputSchema = z.object({
413
+ toolUseIntent: z.string().optional().describe(
414
+ "Brief description of what you intend to accomplish with this tool call"
415
+ ),
416
+ connectionId: z.string().describe("ID of the Google Drive connection to use"),
417
+ method: z.enum(["GET", "POST", "PATCH"]).describe("HTTP method"),
418
+ path: z.string().describe(
419
+ "API path appended to https://www.googleapis.com/drive/v3 (e.g., '/files', '/files/{fileId}')."
420
+ ),
421
+ body: z.record(z.string(), z.unknown()).optional().describe("JSON request body for POST/PATCH requests"),
422
+ queryParams: z.record(z.string(), z.string()).optional().describe("Query parameters to append to the URL")
423
+ });
424
+ var outputSchema = z.discriminatedUnion("success", [
425
+ z.object({
426
+ success: z.literal(true),
427
+ status: z.number(),
428
+ data: z.unknown()
429
+ }),
430
+ z.object({
431
+ success: z.literal(false),
432
+ error: z.string()
433
+ })
434
+ ]);
435
+ var requestTool = new ConnectorTool({
436
+ name: "request",
437
+ description: `Send authenticated requests to the Google Drive API v3.
438
+ Supports GET (read/list/download), POST (create/copy), and PATCH (update) methods.
439
+ Authentication is handled automatically using a service account.`,
440
+ inputSchema,
441
+ outputSchema,
442
+ async execute({ connectionId, method, path: path2, body, queryParams }, connections) {
443
+ const connection2 = connections.find((c) => c.id === connectionId);
444
+ if (!connection2) {
445
+ return {
446
+ success: false,
447
+ error: `Connection ${connectionId} not found`
448
+ };
449
+ }
450
+ console.log(
451
+ `[connector-request] google-drive/${connection2.name}: ${method} ${path2}`
452
+ );
453
+ try {
454
+ const { GoogleAuth } = await import("google-auth-library");
455
+ const keyJsonBase64 = parameters.serviceAccountKeyJsonBase64.getValue(connection2);
456
+ const credentials = JSON.parse(
457
+ Buffer.from(keyJsonBase64, "base64").toString("utf-8")
458
+ );
459
+ const auth = new GoogleAuth({
460
+ credentials,
461
+ scopes: ["https://www.googleapis.com/auth/drive"]
462
+ });
463
+ const token = await auth.getAccessToken();
464
+ if (!token) {
465
+ return {
466
+ success: false,
467
+ error: "Failed to obtain access token"
468
+ };
469
+ }
470
+ let url = `${BASE_URL2}${path2.startsWith("/") ? "" : "/"}${path2}`;
471
+ if (queryParams) {
472
+ const searchParams = new URLSearchParams(queryParams);
473
+ url += `?${searchParams.toString()}`;
474
+ }
475
+ const controller = new AbortController();
476
+ const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
477
+ try {
478
+ const response = await fetch(url, {
479
+ method,
480
+ headers: {
481
+ Authorization: `Bearer ${token}`,
482
+ "Content-Type": "application/json"
483
+ },
484
+ ...body != null ? { body: JSON.stringify(body) } : {},
485
+ signal: controller.signal
486
+ });
487
+ const data = await response.json();
488
+ if (!response.ok) {
489
+ const errorObj = data;
490
+ return {
491
+ success: false,
492
+ error: errorObj?.error?.message ?? `HTTP ${response.status} ${response.statusText}`
493
+ };
494
+ }
495
+ return { success: true, status: response.status, data };
496
+ } finally {
497
+ clearTimeout(timeout);
498
+ }
499
+ } catch (err) {
500
+ const msg = err instanceof Error ? err.message : String(err);
501
+ return { success: false, error: msg };
502
+ }
503
+ }
504
+ });
505
+
506
+ // ../connectors/src/connectors/google-drive/index.ts
507
+ var tools = { request: requestTool };
508
+ var googleDriveConnector = new ConnectorPlugin({
509
+ slug: "google-drive",
510
+ authType: AUTH_TYPES.SERVICE_ACCOUNT,
511
+ name: "Google Drive",
512
+ description: "Connect to Google Drive for file management, sharing, and collaboration using a service account.",
513
+ iconUrl: "https://images.ctfassets.net/9ncizv60xc5y/4GJX5yQTogUgar1buWxXbv/4b43a65353319c508111489f834d22c4/google_drive.png",
514
+ parameters,
515
+ releaseFlag: { dev1: true, dev2: false, prod: false },
516
+ onboarding: googleDriveOnboarding,
517
+ systemPrompt: {
518
+ en: `### Tools
519
+
520
+ - \`google-drive_request\`: Send authenticated requests to the Google Drive API v3. Supports GET, POST, and PATCH methods. Authentication is configured automatically via service account.
521
+
522
+ ### Google Drive API Reference
523
+
524
+ #### Files
525
+ - GET \`/files\` \u2014 List files. Key query params: \`q\` (search query), \`pageSize\`, \`pageToken\`, \`orderBy\`, \`fields\`
526
+ - GET \`/files/{fileId}\` \u2014 Get file metadata
527
+ - GET \`/files/{fileId}?alt=media\` \u2014 Download file content (for non-Google-Workspace files)
528
+ - POST \`/files\` \u2014 Create a new file or folder (metadata only). Body: \`{ "name": "My File", "mimeType": "...", "parents": ["folderId"] }\`
529
+ - PATCH \`/files/{fileId}\` \u2014 Update file metadata (rename, move, star). Use \`addParents\`/\`removeParents\` query params to move
530
+ - POST \`/files/{fileId}/copy\` \u2014 Copy a file
531
+
532
+ #### Download & Export
533
+ - GET \`/files/{fileId}?alt=media\` \u2014 Download file content (PDFs, images, text files, etc.)
534
+ - GET \`/files/{fileId}/export?mimeType={mimeType}\` \u2014 Export Google Workspace files to another format
535
+
536
+ #### Permissions (Sharing)
537
+ - GET \`/files/{fileId}/permissions\` \u2014 List permissions
538
+ - POST \`/files/{fileId}/permissions\` \u2014 Share a file. Body: \`{ "type": "user", "role": "writer", "emailAddress": "user@example.com" }\`
539
+
540
+ ### Search Query Syntax (\`q\` parameter)
541
+ - \`name contains 'report'\` \u2014 Name contains text
542
+ - \`mimeType = 'application/vnd.google-apps.folder'\` \u2014 Folders only
543
+ - \`mimeType = 'application/vnd.google-apps.spreadsheet'\` \u2014 Google Sheets only
544
+ - \`'folderId' in parents\` \u2014 Files in a specific folder
545
+ - \`trashed = false\` \u2014 Exclude trashed files
546
+ - Combine with \`and\`/\`or\`: \`mimeType = 'application/vnd.google-apps.folder' and name contains 'project'\`
547
+
548
+ ### Business Logic
549
+
550
+ The business logic type for this connector is "typescript". Write handler code using the connector SDK shown below.
551
+
552
+ #### Example
553
+
554
+ \`\`\`ts
555
+ import { connection } from "@squadbase/vite-server/connectors/google-drive";
556
+
557
+ const drive = connection("<connectionId>");
558
+
559
+ const result = await drive.listFiles({ pageSize: 20, orderBy: "modifiedTime desc" });
560
+ result.files.forEach(f => console.log(f.name, f.mimeType));
561
+
562
+ const folder = await drive.createFile({ name: "Reports", mimeType: "application/vnd.google-apps.folder" });
563
+ const content = await drive.downloadFile("fileId123");
564
+ const pdf = await drive.exportFile("docFileId", "application/pdf");
565
+ \`\`\``,
566
+ ja: `### \u30C4\u30FC\u30EB
567
+
568
+ - \`google-drive_request\`: Google Drive API v3\u3078\u306E\u8A8D\u8A3C\u6E08\u307F\u30EA\u30AF\u30A8\u30B9\u30C8\u3092\u9001\u4FE1\u3057\u307E\u3059\u3002GET, POST, PATCH\u30E1\u30BD\u30C3\u30C9\u3092\u30B5\u30DD\u30FC\u30C8\u3057\u307E\u3059\u3002\u30B5\u30FC\u30D3\u30B9\u30A2\u30AB\u30A6\u30F3\u30C8\u7D4C\u7531\u3067\u8A8D\u8A3C\u306F\u81EA\u52D5\u8A2D\u5B9A\u3055\u308C\u307E\u3059\u3002
569
+
570
+ ### Google Drive API \u30EA\u30D5\u30A1\u30EC\u30F3\u30B9
571
+
572
+ #### \u30D5\u30A1\u30A4\u30EB
573
+ - GET \`/files\` \u2014 \u30D5\u30A1\u30A4\u30EB\u4E00\u89A7\u3002\u4E3B\u8981\u30AF\u30A8\u30EA\u30D1\u30E9\u30E1\u30FC\u30BF: \`q\`, \`pageSize\`, \`pageToken\`, \`orderBy\`, \`fields\`
574
+ - GET \`/files/{fileId}\` \u2014 \u30D5\u30A1\u30A4\u30EB\u30E1\u30BF\u30C7\u30FC\u30BF\u3092\u53D6\u5F97
575
+ - GET \`/files/{fileId}?alt=media\` \u2014 \u30D5\u30A1\u30A4\u30EB\u30B3\u30F3\u30C6\u30F3\u30C4\u3092\u30C0\u30A6\u30F3\u30ED\u30FC\u30C9\uFF08\u975EGoogle Workspace\u30D5\u30A1\u30A4\u30EB\uFF09
576
+ - POST \`/files\` \u2014 \u65B0\u3057\u3044\u30D5\u30A1\u30A4\u30EB\u307E\u305F\u306F\u30D5\u30A9\u30EB\u30C0\u3092\u4F5C\u6210\uFF08\u30E1\u30BF\u30C7\u30FC\u30BF\u306E\u307F\uFF09
577
+ - PATCH \`/files/{fileId}\` \u2014 \u30D5\u30A1\u30A4\u30EB\u30E1\u30BF\u30C7\u30FC\u30BF\u3092\u66F4\u65B0\uFF08\u540D\u524D\u5909\u66F4\u3001\u79FB\u52D5\u3001\u30B9\u30BF\u30FC\uFF09
578
+ - POST \`/files/{fileId}/copy\` \u2014 \u30D5\u30A1\u30A4\u30EB\u3092\u30B3\u30D4\u30FC
579
+
580
+ #### \u30C0\u30A6\u30F3\u30ED\u30FC\u30C9 & \u30A8\u30AF\u30B9\u30DD\u30FC\u30C8
581
+ - GET \`/files/{fileId}?alt=media\` \u2014 \u30D5\u30A1\u30A4\u30EB\u30B3\u30F3\u30C6\u30F3\u30C4\u3092\u30C0\u30A6\u30F3\u30ED\u30FC\u30C9
582
+ - GET \`/files/{fileId}/export?mimeType={mimeType}\` \u2014 Google Workspace\u30D5\u30A1\u30A4\u30EB\u3092\u5225\u5F62\u5F0F\u306B\u30A8\u30AF\u30B9\u30DD\u30FC\u30C8
583
+
584
+ #### \u30D1\u30FC\u30DF\u30C3\u30B7\u30E7\u30F3\uFF08\u5171\u6709\uFF09
585
+ - GET \`/files/{fileId}/permissions\` \u2014 \u30D1\u30FC\u30DF\u30C3\u30B7\u30E7\u30F3\u4E00\u89A7
586
+ - POST \`/files/{fileId}/permissions\` \u2014 \u30D5\u30A1\u30A4\u30EB\u3092\u5171\u6709
587
+
588
+ ### \u691C\u7D22\u30AF\u30A8\u30EA\u69CB\u6587\uFF08\`q\` \u30D1\u30E9\u30E1\u30FC\u30BF\uFF09
589
+ - \`name contains '\u30EC\u30DD\u30FC\u30C8'\` \u2014 \u540D\u524D\u306B\u30C6\u30AD\u30B9\u30C8\u3092\u542B\u3080
590
+ - \`mimeType = 'application/vnd.google-apps.folder'\` \u2014 \u30D5\u30A9\u30EB\u30C0\u306E\u307F
591
+ - \`'folderId' in parents\` \u2014 \u7279\u5B9A\u30D5\u30A9\u30EB\u30C0\u5185\u306E\u30D5\u30A1\u30A4\u30EB
592
+ - \`trashed = false\` \u2014 \u30B4\u30DF\u7BB1\u3092\u9664\u5916
593
+ - \`and\`/\`or\`\u3067\u7D44\u307F\u5408\u308F\u305B\u53EF\u80FD
594
+
595
+ ### Business Logic
596
+
597
+ \u3053\u306E\u30B3\u30CD\u30AF\u30BF\u306E\u30D3\u30B8\u30CD\u30B9\u30ED\u30B8\u30C3\u30AF\u30BF\u30A4\u30D7\u306F "typescript" \u3067\u3059\u3002\u4EE5\u4E0B\u306ESDK\u3092\u4F7F\u7528\u3057\u3066\u304F\u3060\u3055\u3044\u3002
598
+
599
+ #### Example
600
+
601
+ \`\`\`ts
602
+ import { connection } from "@squadbase/vite-server/connectors/google-drive";
603
+
604
+ const drive = connection("<connectionId>");
605
+
606
+ const result = await drive.listFiles({ pageSize: 20, orderBy: "modifiedTime desc" });
607
+ result.files.forEach(f => console.log(f.name, f.mimeType));
608
+
609
+ const folder = await drive.createFile({ name: "\u30EC\u30DD\u30FC\u30C8", mimeType: "application/vnd.google-apps.folder" });
610
+ const content = await drive.downloadFile("fileId123");
611
+ const pdf = await drive.exportFile("docFileId", "application/pdf");
612
+ \`\`\``
613
+ },
614
+ tools
615
+ });
616
+
617
+ // src/connectors/create-connector-sdk.ts
618
+ import { readFileSync } from "fs";
619
+ import path from "path";
620
+
621
+ // src/connector-client/env.ts
622
+ function resolveEnvVar(entry, key, connectionId) {
623
+ const envVarName = entry.envVars[key];
624
+ if (!envVarName) {
625
+ throw new Error(`Connection "${connectionId}" is missing envVars mapping for key "${key}"`);
626
+ }
627
+ const value = process.env[envVarName];
628
+ if (!value) {
629
+ throw new Error(`Environment variable "${envVarName}" (for connection "${connectionId}", key "${key}") is not set`);
630
+ }
631
+ return value;
632
+ }
633
+ function resolveEnvVarOptional(entry, key) {
634
+ const envVarName = entry.envVars[key];
635
+ if (!envVarName) return void 0;
636
+ return process.env[envVarName] || void 0;
637
+ }
638
+
639
+ // src/connector-client/proxy-fetch.ts
640
+ import { getContext } from "hono/context-storage";
641
+ import { getCookie } from "hono/cookie";
642
+ var APP_SESSION_COOKIE_NAME = "__Host-squadbase-session";
643
+ function createSandboxProxyFetch(connectionId) {
644
+ return async (input, init) => {
645
+ const token = process.env.INTERNAL_SQUADBASE_OAUTH_MACHINE_CREDENTIAL;
646
+ const sandboxId = process.env.INTERNAL_SQUADBASE_SANDBOX_ID;
647
+ if (!token || !sandboxId) {
648
+ throw new Error(
649
+ "Connection proxy is not configured. Please check your deployment settings."
650
+ );
651
+ }
652
+ const originalUrl = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
653
+ const originalMethod = init?.method ?? "GET";
654
+ const originalBody = init?.body ? JSON.parse(init.body) : void 0;
655
+ const baseDomain = process.env["SQUADBASE_PREVIEW_BASE_DOMAIN"] ?? "preview.app.squadbase.dev";
656
+ const proxyUrl = `https://${sandboxId}.${baseDomain}/_sqcore/connections/${connectionId}/request`;
657
+ return fetch(proxyUrl, {
658
+ method: "POST",
659
+ headers: {
660
+ "Content-Type": "application/json",
661
+ Authorization: `Bearer ${token}`
662
+ },
663
+ body: JSON.stringify({
664
+ url: originalUrl,
665
+ method: originalMethod,
666
+ body: originalBody
667
+ })
668
+ });
669
+ };
670
+ }
671
+ function createDeployedAppProxyFetch(connectionId) {
672
+ const projectId = process.env["SQUADBASE_PROJECT_ID"];
673
+ if (!projectId) {
674
+ throw new Error(
675
+ "Connection proxy is not configured. Please check your deployment settings."
676
+ );
677
+ }
678
+ const baseDomain = process.env["SQUADBASE_APP_BASE_DOMAIN"] ?? "squadbase.app";
679
+ const proxyUrl = `https://${projectId}.${baseDomain}/_sqcore/connections/${connectionId}/request`;
680
+ return async (input, init) => {
681
+ const originalUrl = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
682
+ const originalMethod = init?.method ?? "GET";
683
+ const originalBody = init?.body ? JSON.parse(init.body) : void 0;
684
+ const c = getContext();
685
+ const appSession = getCookie(c, APP_SESSION_COOKIE_NAME);
686
+ if (!appSession) {
687
+ throw new Error(
688
+ "No authentication method available for connection proxy."
689
+ );
690
+ }
691
+ return fetch(proxyUrl, {
692
+ method: "POST",
693
+ headers: {
694
+ "Content-Type": "application/json",
695
+ Authorization: `Bearer ${appSession}`
696
+ },
697
+ body: JSON.stringify({
698
+ url: originalUrl,
699
+ method: originalMethod,
700
+ body: originalBody
701
+ })
702
+ });
703
+ };
704
+ }
705
+ function createProxyFetch(connectionId) {
706
+ if (process.env.INTERNAL_SQUADBASE_SANDBOX_ID) {
707
+ return createSandboxProxyFetch(connectionId);
708
+ }
709
+ return createDeployedAppProxyFetch(connectionId);
710
+ }
711
+
712
+ // src/connectors/create-connector-sdk.ts
713
+ function loadConnectionsSync() {
714
+ const filePath = process.env.CONNECTIONS_PATH ?? path.join(process.cwd(), ".squadbase/connections.json");
715
+ try {
716
+ const raw = readFileSync(filePath, "utf-8");
717
+ return JSON.parse(raw);
718
+ } catch {
719
+ return {};
720
+ }
721
+ }
722
+ function createConnectorSdk(plugin, createClient2) {
723
+ return (connectionId) => {
724
+ const connections = loadConnectionsSync();
725
+ const entry = connections[connectionId];
726
+ if (!entry) {
727
+ throw new Error(
728
+ `Connection "${connectionId}" not found in .squadbase/connections.json`
729
+ );
730
+ }
731
+ if (entry.connector.slug !== plugin.slug) {
732
+ throw new Error(
733
+ `Connection "${connectionId}" is not a ${plugin.slug} connection (got "${entry.connector.slug}")`
734
+ );
735
+ }
736
+ const params = {};
737
+ for (const param of Object.values(plugin.parameters)) {
738
+ if (param.required) {
739
+ params[param.slug] = resolveEnvVar(entry, param.slug, connectionId);
740
+ } else {
741
+ const val = resolveEnvVarOptional(entry, param.slug);
742
+ if (val !== void 0) params[param.slug] = val;
743
+ }
744
+ }
745
+ return createClient2(params, createProxyFetch(connectionId));
746
+ };
747
+ }
748
+
749
+ // src/connectors/entries/google-drive.ts
750
+ var connection = createConnectorSdk(googleDriveConnector, createClient);
751
+ export {
752
+ connection
753
+ };