@squadbase/vite-server 0.1.3-dev.0 → 0.1.3-dev.10

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 (70) hide show
  1. package/dist/cli/index.js +82859 -9645
  2. package/dist/connectors/airtable-oauth.js +77 -3
  3. package/dist/connectors/airtable.js +85 -2
  4. package/dist/connectors/amplitude.js +85 -2
  5. package/dist/connectors/anthropic.js +85 -2
  6. package/dist/connectors/{slack.d.ts → asana.d.ts} +1 -1
  7. package/dist/connectors/asana.js +744 -0
  8. package/dist/connectors/attio.js +85 -2
  9. package/dist/connectors/{microsoft-teams-oauth.d.ts → customerio.d.ts} +1 -1
  10. package/dist/connectors/customerio.js +716 -0
  11. package/dist/connectors/dbt.js +85 -2
  12. package/dist/connectors/gemini.js +86 -3
  13. package/dist/connectors/{microsoft-teams.d.ts → gmail-oauth.d.ts} +1 -1
  14. package/dist/connectors/gmail-oauth.js +713 -0
  15. package/dist/connectors/gmail.d.ts +5 -0
  16. package/dist/connectors/gmail.js +875 -0
  17. package/dist/connectors/google-ads-oauth.js +78 -4
  18. package/dist/connectors/google-ads.d.ts +5 -0
  19. package/dist/connectors/google-ads.js +867 -0
  20. package/dist/connectors/google-analytics-oauth.js +90 -8
  21. package/dist/connectors/google-analytics.js +85 -2
  22. package/dist/connectors/google-calendar-oauth.d.ts +5 -0
  23. package/dist/connectors/google-calendar-oauth.js +817 -0
  24. package/dist/connectors/google-calendar.d.ts +5 -0
  25. package/dist/connectors/google-calendar.js +991 -0
  26. package/dist/connectors/google-sheets-oauth.js +144 -33
  27. package/dist/connectors/google-sheets.d.ts +5 -0
  28. package/dist/connectors/google-sheets.js +707 -0
  29. package/dist/connectors/grafana.d.ts +5 -0
  30. package/dist/connectors/grafana.js +638 -0
  31. package/dist/connectors/hubspot-oauth.js +77 -3
  32. package/dist/connectors/hubspot.js +89 -6
  33. package/dist/connectors/intercom-oauth.d.ts +5 -0
  34. package/dist/connectors/intercom-oauth.js +584 -0
  35. package/dist/connectors/intercom.d.ts +5 -0
  36. package/dist/connectors/intercom.js +710 -0
  37. package/dist/connectors/jira-api-key.d.ts +5 -0
  38. package/dist/connectors/jira-api-key.js +598 -0
  39. package/dist/connectors/kintone-api-token.js +77 -3
  40. package/dist/connectors/kintone.js +86 -3
  41. package/dist/connectors/linkedin-ads-oauth.d.ts +5 -0
  42. package/dist/connectors/linkedin-ads-oauth.js +848 -0
  43. package/dist/connectors/linkedin-ads.d.ts +5 -0
  44. package/dist/connectors/linkedin-ads.js +865 -0
  45. package/dist/connectors/mailchimp-oauth.d.ts +5 -0
  46. package/dist/connectors/mailchimp-oauth.js +613 -0
  47. package/dist/connectors/mailchimp.d.ts +5 -0
  48. package/dist/connectors/mailchimp.js +729 -0
  49. package/dist/connectors/notion-oauth.d.ts +5 -0
  50. package/dist/connectors/notion-oauth.js +567 -0
  51. package/dist/connectors/notion.d.ts +5 -0
  52. package/dist/connectors/notion.js +663 -0
  53. package/dist/connectors/openai.js +85 -2
  54. package/dist/connectors/shopify-oauth.js +77 -3
  55. package/dist/connectors/shopify.js +85 -2
  56. package/dist/connectors/stripe-api-key.d.ts +5 -0
  57. package/dist/connectors/stripe-api-key.js +600 -0
  58. package/dist/connectors/stripe-oauth.js +77 -3
  59. package/dist/connectors/wix-store.js +85 -2
  60. package/dist/connectors/zendesk-oauth.d.ts +5 -0
  61. package/dist/connectors/zendesk-oauth.js +579 -0
  62. package/dist/connectors/zendesk.d.ts +5 -0
  63. package/dist/connectors/zendesk.js +714 -0
  64. package/dist/index.js +83024 -7099
  65. package/dist/main.js +82988 -7063
  66. package/dist/vite-plugin.js +82862 -6974
  67. package/package.json +86 -2
  68. package/dist/connectors/microsoft-teams-oauth.js +0 -479
  69. package/dist/connectors/microsoft-teams.js +0 -381
  70. package/dist/connectors/slack.js +0 -362
@@ -0,0 +1,867 @@
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-ads/sdk/index.ts
46
+ import * as crypto from "crypto";
47
+
48
+ // ../connectors/src/connectors/google-ads/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 Ads.",
54
+ envVarBaseKey: "GOOGLE_ADS_SERVICE_ACCOUNT_JSON_BASE64",
55
+ type: "base64EncodedJson",
56
+ secret: true,
57
+ required: true
58
+ }),
59
+ developerToken: new ParameterDefinition({
60
+ slug: "developer-token",
61
+ name: "Google Ads Developer Token",
62
+ description: "The developer token for accessing the Google Ads API. Required for all API requests.",
63
+ envVarBaseKey: "GOOGLE_ADS_DEVELOPER_TOKEN",
64
+ type: "text",
65
+ secret: true,
66
+ required: true
67
+ }),
68
+ customerId: new ParameterDefinition({
69
+ slug: "customer-id",
70
+ name: "Google Ads Customer ID",
71
+ description: "The Google Ads customer ID (e.g., 123-456-7890 or 1234567890). Can be found in the top-right corner of your Google Ads account.",
72
+ envVarBaseKey: "GOOGLE_ADS_CUSTOMER_ID",
73
+ type: "text",
74
+ secret: false,
75
+ required: false
76
+ }),
77
+ loginCustomerId: new ParameterDefinition({
78
+ slug: "login-customer-id",
79
+ name: "Login Customer ID (MCC)",
80
+ description: "The manager account (MCC) customer ID used for login. Required when accessing client accounts through a manager account. If not set, the customer ID is used.",
81
+ envVarBaseKey: "GOOGLE_ADS_LOGIN_CUSTOMER_ID",
82
+ type: "text",
83
+ secret: false,
84
+ required: false
85
+ })
86
+ };
87
+
88
+ // ../connectors/src/connectors/google-ads/sdk/index.ts
89
+ var TOKEN_URL = "https://oauth2.googleapis.com/token";
90
+ var BASE_URL = "https://googleads.googleapis.com/v18/";
91
+ var SCOPE = "https://www.googleapis.com/auth/adwords";
92
+ function base64url(input) {
93
+ const buf = typeof input === "string" ? Buffer.from(input) : input;
94
+ return buf.toString("base64url");
95
+ }
96
+ function buildJwt(clientEmail, privateKey, nowSec) {
97
+ const header = base64url(JSON.stringify({ alg: "RS256", typ: "JWT" }));
98
+ const payload = base64url(
99
+ JSON.stringify({
100
+ iss: clientEmail,
101
+ scope: SCOPE,
102
+ aud: TOKEN_URL,
103
+ iat: nowSec,
104
+ exp: nowSec + 3600
105
+ })
106
+ );
107
+ const signingInput = `${header}.${payload}`;
108
+ const sign = crypto.createSign("RSA-SHA256");
109
+ sign.update(signingInput);
110
+ sign.end();
111
+ const signature = base64url(sign.sign(privateKey));
112
+ return `${signingInput}.${signature}`;
113
+ }
114
+ function createClient(params) {
115
+ const serviceAccountKeyJsonBase64 = params[parameters.serviceAccountKeyJsonBase64.slug];
116
+ const developerToken = params[parameters.developerToken.slug];
117
+ const rawCustomerId = params[parameters.customerId.slug];
118
+ const defaultCustomerId = rawCustomerId?.replace(/-/g, "") ?? "";
119
+ const rawLoginCustomerId = params[parameters.loginCustomerId.slug];
120
+ const loginCustomerId = rawLoginCustomerId?.replace(/-/g, "") ?? "";
121
+ if (!serviceAccountKeyJsonBase64 || !developerToken) {
122
+ const required = [
123
+ parameters.serviceAccountKeyJsonBase64.slug,
124
+ parameters.developerToken.slug
125
+ ];
126
+ const missing = required.filter((s) => !params[s]);
127
+ throw new Error(
128
+ `google-ads: missing required parameters: ${missing.join(", ")}`
129
+ );
130
+ }
131
+ let serviceAccountKey;
132
+ try {
133
+ const decoded = Buffer.from(
134
+ serviceAccountKeyJsonBase64,
135
+ "base64"
136
+ ).toString("utf-8");
137
+ serviceAccountKey = JSON.parse(decoded);
138
+ } catch {
139
+ throw new Error(
140
+ "google-ads: failed to decode service account key JSON from base64"
141
+ );
142
+ }
143
+ if (!serviceAccountKey.client_email || !serviceAccountKey.private_key) {
144
+ throw new Error(
145
+ "google-ads: service account key JSON must contain client_email and private_key"
146
+ );
147
+ }
148
+ let cachedToken = null;
149
+ let tokenExpiresAt = 0;
150
+ async function getAccessToken() {
151
+ const nowSec = Math.floor(Date.now() / 1e3);
152
+ if (cachedToken && nowSec < tokenExpiresAt - 60) {
153
+ return cachedToken;
154
+ }
155
+ const jwt = buildJwt(
156
+ serviceAccountKey.client_email,
157
+ serviceAccountKey.private_key,
158
+ nowSec
159
+ );
160
+ const response = await fetch(TOKEN_URL, {
161
+ method: "POST",
162
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
163
+ body: new URLSearchParams({
164
+ grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
165
+ assertion: jwt
166
+ })
167
+ });
168
+ if (!response.ok) {
169
+ const text = await response.text();
170
+ throw new Error(
171
+ `google-ads: token exchange failed (${response.status}): ${text}`
172
+ );
173
+ }
174
+ const data = await response.json();
175
+ cachedToken = data.access_token;
176
+ tokenExpiresAt = nowSec + data.expires_in;
177
+ return cachedToken;
178
+ }
179
+ function resolveCustomerId(override) {
180
+ const id = override?.replace(/-/g, "") ?? defaultCustomerId;
181
+ if (!id) {
182
+ throw new Error(
183
+ "google-ads: customerId is required. Either configure a default or pass it explicitly."
184
+ );
185
+ }
186
+ return id;
187
+ }
188
+ function getLoginCustomerId() {
189
+ return loginCustomerId || defaultCustomerId;
190
+ }
191
+ return {
192
+ async request(path2, init) {
193
+ const accessToken = await getAccessToken();
194
+ const resolvedPath = defaultCustomerId ? path2.replace(/\{customerId\}/g, defaultCustomerId) : path2;
195
+ const url = `${BASE_URL}${resolvedPath}`;
196
+ const headers = new Headers(init?.headers);
197
+ headers.set("Authorization", `Bearer ${accessToken}`);
198
+ headers.set("developer-token", developerToken);
199
+ const lid = getLoginCustomerId();
200
+ if (lid) {
201
+ headers.set("login-customer-id", lid);
202
+ }
203
+ return fetch(url, { ...init, headers });
204
+ },
205
+ async search(query, customerId) {
206
+ const cid = resolveCustomerId(customerId);
207
+ const accessToken = await getAccessToken();
208
+ const url = `${BASE_URL}customers/${cid}/googleAds:searchStream`;
209
+ const headers = new Headers();
210
+ headers.set("Content-Type", "application/json");
211
+ headers.set("Authorization", `Bearer ${accessToken}`);
212
+ headers.set("developer-token", developerToken);
213
+ const lid = loginCustomerId || cid;
214
+ headers.set("login-customer-id", lid);
215
+ const response = await fetch(url, {
216
+ method: "POST",
217
+ headers,
218
+ body: JSON.stringify({ query })
219
+ });
220
+ if (!response.ok) {
221
+ const body = await response.text();
222
+ throw new Error(
223
+ `google-ads: search failed (${response.status}): ${body}`
224
+ );
225
+ }
226
+ const data = await response.json();
227
+ return data.flatMap((chunk) => chunk.results ?? []);
228
+ },
229
+ async listAccessibleCustomers() {
230
+ const accessToken = await getAccessToken();
231
+ const url = `${BASE_URL}customers:listAccessibleCustomers`;
232
+ const headers = new Headers();
233
+ headers.set("Authorization", `Bearer ${accessToken}`);
234
+ headers.set("developer-token", developerToken);
235
+ const response = await fetch(url, { method: "GET", headers });
236
+ if (!response.ok) {
237
+ const body = await response.text();
238
+ throw new Error(
239
+ `google-ads: listAccessibleCustomers failed (${response.status}): ${body}`
240
+ );
241
+ }
242
+ const data = await response.json();
243
+ return (data.resourceNames ?? []).map(
244
+ (rn) => rn.replace(/^customers\//, "")
245
+ );
246
+ }
247
+ };
248
+ }
249
+
250
+ // ../connectors/src/connector-onboarding.ts
251
+ var ConnectorOnboarding = class {
252
+ /** Phase 1: Connection setup instructions (optional — some connectors don't need this) */
253
+ connectionSetupInstructions;
254
+ /** Phase 2: Data overview instructions */
255
+ dataOverviewInstructions;
256
+ constructor(config) {
257
+ this.connectionSetupInstructions = config.connectionSetupInstructions;
258
+ this.dataOverviewInstructions = config.dataOverviewInstructions;
259
+ }
260
+ getConnectionSetupPrompt(language) {
261
+ return this.connectionSetupInstructions?.[language] ?? null;
262
+ }
263
+ getDataOverviewInstructions(language) {
264
+ return this.dataOverviewInstructions[language];
265
+ }
266
+ };
267
+
268
+ // ../connectors/src/connector-tool.ts
269
+ var ConnectorTool = class {
270
+ name;
271
+ description;
272
+ inputSchema;
273
+ outputSchema;
274
+ _execute;
275
+ constructor(config) {
276
+ this.name = config.name;
277
+ this.description = config.description;
278
+ this.inputSchema = config.inputSchema;
279
+ this.outputSchema = config.outputSchema;
280
+ this._execute = config.execute;
281
+ }
282
+ createTool(connections, config) {
283
+ return {
284
+ description: this.description,
285
+ inputSchema: this.inputSchema,
286
+ outputSchema: this.outputSchema,
287
+ execute: (input) => this._execute(input, connections, config)
288
+ };
289
+ }
290
+ };
291
+
292
+ // ../connectors/src/connector-plugin.ts
293
+ var ConnectorPlugin = class _ConnectorPlugin {
294
+ slug;
295
+ authType;
296
+ name;
297
+ description;
298
+ iconUrl;
299
+ parameters;
300
+ releaseFlag;
301
+ proxyPolicy;
302
+ experimentalAttributes;
303
+ onboarding;
304
+ systemPrompt;
305
+ tools;
306
+ query;
307
+ checkConnection;
308
+ constructor(config) {
309
+ this.slug = config.slug;
310
+ this.authType = config.authType;
311
+ this.name = config.name;
312
+ this.description = config.description;
313
+ this.iconUrl = config.iconUrl;
314
+ this.parameters = config.parameters;
315
+ this.releaseFlag = config.releaseFlag;
316
+ this.proxyPolicy = config.proxyPolicy;
317
+ this.experimentalAttributes = config.experimentalAttributes;
318
+ this.onboarding = config.onboarding;
319
+ this.systemPrompt = config.systemPrompt;
320
+ this.tools = config.tools;
321
+ this.query = config.query;
322
+ this.checkConnection = config.checkConnection;
323
+ }
324
+ get connectorKey() {
325
+ return _ConnectorPlugin.deriveKey(this.slug, this.authType);
326
+ }
327
+ /**
328
+ * Create tools for connections that belong to this connector.
329
+ * Filters connections by connectorKey internally.
330
+ * Returns tools keyed as `${connectorKey}_${toolName}`.
331
+ */
332
+ createTools(connections, config) {
333
+ const myConnections = connections.filter(
334
+ (c) => _ConnectorPlugin.deriveKey(c.connector.slug, c.connector.authType) === this.connectorKey
335
+ );
336
+ const result = {};
337
+ for (const t of Object.values(this.tools)) {
338
+ result[`${this.connectorKey}_${t.name}`] = t.createTool(
339
+ myConnections,
340
+ config
341
+ );
342
+ }
343
+ return result;
344
+ }
345
+ static deriveKey(slug, authType) {
346
+ return authType ? `${slug}-${authType}` : slug;
347
+ }
348
+ };
349
+
350
+ // ../connectors/src/auth-types.ts
351
+ var AUTH_TYPES = {
352
+ OAUTH: "oauth",
353
+ API_KEY: "api-key",
354
+ JWT: "jwt",
355
+ SERVICE_ACCOUNT: "service-account",
356
+ PAT: "pat",
357
+ USER_PASSWORD: "user-password"
358
+ };
359
+
360
+ // ../connectors/src/connectors/google-ads/setup.ts
361
+ var googleAdsOnboarding = new ConnectorOnboarding({
362
+ dataOverviewInstructions: {
363
+ en: `1. Call google-ads_request with POST customers/{customerId}/googleAds:searchStream to explore available campaign data using GAQL: SELECT campaign.id, campaign.name, campaign.status FROM campaign LIMIT 10
364
+ 2. Explore ad group and keyword data as needed to understand the data structure`,
365
+ ja: `1. google-ads_request \u3067 POST customers/{customerId}/googleAds:searchStream \u3092\u547C\u3073\u51FA\u3057\u3001GAQL\u3067\u30AD\u30E3\u30F3\u30DA\u30FC\u30F3\u30C7\u30FC\u30BF\u3092\u63A2\u7D22: SELECT campaign.id, campaign.name, campaign.status FROM campaign LIMIT 10
366
+ 2. \u5FC5\u8981\u306B\u5FDC\u3058\u3066\u5E83\u544A\u30B0\u30EB\u30FC\u30D7\u3084\u30AD\u30FC\u30EF\u30FC\u30C9\u30C7\u30FC\u30BF\u3092\u63A2\u7D22\u3057\u3001\u30C7\u30FC\u30BF\u69CB\u9020\u3092\u628A\u63E1`
367
+ }
368
+ });
369
+
370
+ // ../connectors/src/connectors/google-ads/tools/request.ts
371
+ import { z } from "zod";
372
+ var BASE_URL2 = "https://googleads.googleapis.com/v18/";
373
+ var REQUEST_TIMEOUT_MS = 6e4;
374
+ var inputSchema = z.object({
375
+ toolUseIntent: z.string().optional().describe(
376
+ "Brief description of what you intend to accomplish with this tool call"
377
+ ),
378
+ connectionId: z.string().describe("ID of the Google Ads connection to use"),
379
+ method: z.enum(["GET", "POST"]).describe("HTTP method"),
380
+ path: z.string().describe(
381
+ "API path appended to https://googleads.googleapis.com/v18/ (e.g., 'customers/{customerId}/googleAds:searchStream'). {customerId} is automatically replaced."
382
+ ),
383
+ body: z.record(z.string(), z.unknown()).optional().describe("POST request body (JSON)")
384
+ });
385
+ var outputSchema = z.discriminatedUnion("success", [
386
+ z.object({
387
+ success: z.literal(true),
388
+ status: z.number(),
389
+ data: z.unknown()
390
+ }),
391
+ z.object({
392
+ success: z.literal(false),
393
+ error: z.string()
394
+ })
395
+ ]);
396
+ var requestTool = new ConnectorTool({
397
+ name: "request",
398
+ description: `Send authenticated requests to the Google Ads API v18.
399
+ Authentication is handled automatically using a service account.
400
+ {customerId} in the path is automatically replaced with the connection's customer ID (hyphens removed).`,
401
+ inputSchema,
402
+ outputSchema,
403
+ async execute({ connectionId, method, path: path2, body }, connections) {
404
+ const connection2 = connections.find((c) => c.id === connectionId);
405
+ if (!connection2) {
406
+ return {
407
+ success: false,
408
+ error: `Connection ${connectionId} not found`
409
+ };
410
+ }
411
+ console.log(
412
+ `[connector-request] google-ads/${connection2.name}: ${method} ${path2}`
413
+ );
414
+ try {
415
+ const { GoogleAuth } = await import("google-auth-library");
416
+ const keyJsonBase64 = parameters.serviceAccountKeyJsonBase64.getValue(connection2);
417
+ const developerToken = parameters.developerToken.getValue(connection2);
418
+ const rawCustomerId = parameters.customerId.tryGetValue(connection2);
419
+ const customerId = rawCustomerId?.replace(/-/g, "") ?? "";
420
+ const rawLoginCustomerId = parameters.loginCustomerId.tryGetValue(connection2);
421
+ const loginCustomerId = rawLoginCustomerId?.replace(/-/g, "") ?? "";
422
+ const credentials = JSON.parse(
423
+ Buffer.from(keyJsonBase64, "base64").toString("utf-8")
424
+ );
425
+ const auth = new GoogleAuth({
426
+ credentials,
427
+ scopes: ["https://www.googleapis.com/auth/adwords"]
428
+ });
429
+ const token = await auth.getAccessToken();
430
+ if (!token) {
431
+ return {
432
+ success: false,
433
+ error: "Failed to obtain access token"
434
+ };
435
+ }
436
+ const resolvedPath = customerId ? path2.replace(/\{customerId\}/g, customerId) : path2;
437
+ const url = `${BASE_URL2}${resolvedPath}`;
438
+ const controller = new AbortController();
439
+ const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
440
+ try {
441
+ const lid = loginCustomerId || customerId;
442
+ const response = await fetch(url, {
443
+ method,
444
+ headers: {
445
+ Authorization: `Bearer ${token}`,
446
+ "Content-Type": "application/json",
447
+ "developer-token": developerToken,
448
+ ...lid ? { "login-customer-id": lid } : {}
449
+ },
450
+ body: method === "POST" && body ? JSON.stringify(body) : void 0,
451
+ signal: controller.signal
452
+ });
453
+ const data = await response.json();
454
+ if (!response.ok) {
455
+ const dataObj = data;
456
+ const errorObj = dataObj?.error;
457
+ return {
458
+ success: false,
459
+ error: errorObj?.message ?? `HTTP ${response.status} ${response.statusText}`
460
+ };
461
+ }
462
+ return { success: true, status: response.status, data };
463
+ } finally {
464
+ clearTimeout(timeout);
465
+ }
466
+ } catch (err) {
467
+ const msg = err instanceof Error ? err.message : String(err);
468
+ return { success: false, error: msg };
469
+ }
470
+ }
471
+ });
472
+
473
+ // ../connectors/src/connectors/google-ads/tools/list-customers.ts
474
+ import { z as z2 } from "zod";
475
+ var BASE_URL3 = "https://googleads.googleapis.com/v18/";
476
+ var REQUEST_TIMEOUT_MS2 = 6e4;
477
+ var inputSchema2 = z2.object({
478
+ toolUseIntent: z2.string().optional().describe(
479
+ "Brief description of what you intend to accomplish with this tool call"
480
+ ),
481
+ connectionId: z2.string().describe("ID of the Google Ads connection to use")
482
+ });
483
+ var outputSchema2 = z2.discriminatedUnion("success", [
484
+ z2.object({
485
+ success: z2.literal(true),
486
+ customers: z2.array(
487
+ z2.object({
488
+ customerId: z2.string(),
489
+ descriptiveName: z2.string()
490
+ })
491
+ )
492
+ }),
493
+ z2.object({
494
+ success: z2.literal(false),
495
+ error: z2.string()
496
+ })
497
+ ]);
498
+ var listCustomersTool = new ConnectorTool({
499
+ name: "listCustomers",
500
+ description: "List Google Ads customer accounts accessible with the service account credentials.",
501
+ inputSchema: inputSchema2,
502
+ outputSchema: outputSchema2,
503
+ async execute({ connectionId }, connections) {
504
+ const connection2 = connections.find((c) => c.id === connectionId);
505
+ if (!connection2) {
506
+ return {
507
+ success: false,
508
+ error: `Connection ${connectionId} not found`
509
+ };
510
+ }
511
+ console.log(
512
+ `[connector-request] google-ads/${connection2.name}: listCustomers`
513
+ );
514
+ try {
515
+ const { GoogleAuth } = await import("google-auth-library");
516
+ const keyJsonBase64 = parameters.serviceAccountKeyJsonBase64.getValue(connection2);
517
+ const developerToken = parameters.developerToken.getValue(connection2);
518
+ const credentials = JSON.parse(
519
+ Buffer.from(keyJsonBase64, "base64").toString("utf-8")
520
+ );
521
+ const auth = new GoogleAuth({
522
+ credentials,
523
+ scopes: ["https://www.googleapis.com/auth/adwords"]
524
+ });
525
+ const token = await auth.getAccessToken();
526
+ if (!token) {
527
+ return {
528
+ success: false,
529
+ error: "Failed to obtain access token"
530
+ };
531
+ }
532
+ const controller = new AbortController();
533
+ const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS2);
534
+ try {
535
+ const listResponse = await fetch(
536
+ `${BASE_URL3}customers:listAccessibleCustomers`,
537
+ {
538
+ method: "GET",
539
+ headers: {
540
+ Authorization: `Bearer ${token}`,
541
+ "developer-token": developerToken
542
+ },
543
+ signal: controller.signal
544
+ }
545
+ );
546
+ const listData = await listResponse.json();
547
+ if (!listResponse.ok) {
548
+ return {
549
+ success: false,
550
+ error: listData.error?.message ?? `HTTP ${listResponse.status} ${listResponse.statusText}`
551
+ };
552
+ }
553
+ const customerIds = (listData.resourceNames ?? []).map(
554
+ (rn) => rn.replace(/^customers\//, "")
555
+ );
556
+ const customers = [];
557
+ for (const cid of customerIds) {
558
+ try {
559
+ const detailResponse = await fetch(
560
+ `${BASE_URL3}customers/${cid}/googleAds:searchStream`,
561
+ {
562
+ method: "POST",
563
+ headers: {
564
+ Authorization: `Bearer ${token}`,
565
+ "Content-Type": "application/json",
566
+ "developer-token": developerToken,
567
+ "login-customer-id": cid
568
+ },
569
+ body: JSON.stringify({
570
+ query: "SELECT customer.id, customer.descriptive_name FROM customer LIMIT 1"
571
+ }),
572
+ signal: controller.signal
573
+ }
574
+ );
575
+ if (detailResponse.ok) {
576
+ const detailData = await detailResponse.json();
577
+ const customer = detailData?.[0]?.results?.[0]?.customer;
578
+ customers.push({
579
+ customerId: cid,
580
+ descriptiveName: customer?.descriptiveName ?? cid
581
+ });
582
+ } else {
583
+ customers.push({
584
+ customerId: cid,
585
+ descriptiveName: cid
586
+ });
587
+ }
588
+ } catch {
589
+ customers.push({
590
+ customerId: cid,
591
+ descriptiveName: cid
592
+ });
593
+ }
594
+ }
595
+ return { success: true, customers };
596
+ } finally {
597
+ clearTimeout(timeout);
598
+ }
599
+ } catch (err) {
600
+ const msg = err instanceof Error ? err.message : String(err);
601
+ return { success: false, error: msg };
602
+ }
603
+ }
604
+ });
605
+
606
+ // ../connectors/src/connectors/google-ads/index.ts
607
+ var tools = {
608
+ request: requestTool,
609
+ listCustomers: listCustomersTool
610
+ };
611
+ var googleAdsConnector = new ConnectorPlugin({
612
+ slug: "google-ads",
613
+ authType: AUTH_TYPES.SERVICE_ACCOUNT,
614
+ name: "Google Ads",
615
+ description: "Connect to Google Ads for advertising campaign data and reporting using a service account.",
616
+ iconUrl: "https://images.ctfassets.net/9ncizv60xc5y/1NGvmgvCxX7Tn11EST2N3N/a745fe7c63d360ed40a27ddaad3af168/google-ads.svg",
617
+ parameters,
618
+ releaseFlag: { dev1: true, dev2: false, prod: false },
619
+ onboarding: googleAdsOnboarding,
620
+ systemPrompt: {
621
+ en: `### Tools
622
+
623
+ - \`google-ads_request\`: Send authenticated requests to the Google Ads API. Use it for GAQL queries via searchStream. The {customerId} placeholder in paths is automatically replaced (hyphens removed). Authentication via service account and developer token are configured automatically.
624
+ - \`google-ads_listCustomers\`: List accessible Google Ads customer accounts. Use this during setup to discover available accounts.
625
+
626
+ ### Google Ads API Reference
627
+
628
+ #### Query Data (searchStream)
629
+ - POST customers/{customerId}/googleAds:searchStream
630
+ - Body: { "query": "SELECT campaign.id, campaign.name, metrics.impressions FROM campaign WHERE segments.date DURING LAST_30_DAYS" }
631
+
632
+ ### Common GAQL Resources
633
+ - \`campaign\`: Campaign data (campaign.id, campaign.name, campaign.status)
634
+ - \`ad_group\`: Ad group data (ad_group.id, ad_group.name, ad_group.status)
635
+ - \`ad_group_ad\`: Ad data (ad_group_ad.ad.id, ad_group_ad.status)
636
+ - \`keyword_view\`: Keyword performance data
637
+
638
+ ### Common Metrics
639
+ metrics.impressions, metrics.clicks, metrics.cost_micros, metrics.conversions,
640
+ metrics.ctr, metrics.average_cpc, metrics.conversions_value
641
+
642
+ ### Common Segments
643
+ segments.date, segments.device, segments.ad_network_type
644
+
645
+ ### Date Filters
646
+ - \`DURING LAST_7_DAYS\`, \`DURING LAST_30_DAYS\`, \`DURING THIS_MONTH\`
647
+ - \`WHERE segments.date BETWEEN '2024-01-01' AND '2024-01-31'\`
648
+
649
+ ### Tips
650
+ - cost_micros is in micros (divide by 1,000,000 for actual currency)
651
+ - Use LIMIT to restrict result count
652
+ - Always include relevant WHERE clauses to filter data
653
+
654
+ ### Business Logic
655
+
656
+ The business logic type for this connector is "typescript". Write handler code using the connector SDK shown below. Do NOT access credentials directly from environment variables.
657
+
658
+ #### Example
659
+
660
+ \`\`\`ts
661
+ import { connection } from "@squadbase/vite-server/connectors/google-ads";
662
+
663
+ const ads = connection("<connectionId>");
664
+
665
+ // Execute a GAQL query
666
+ const rows = await ads.search(
667
+ "SELECT campaign.name, metrics.impressions, metrics.clicks FROM campaign WHERE segments.date DURING LAST_7_DAYS"
668
+ );
669
+ rows.forEach(row => console.log(row));
670
+
671
+ // List accessible customer accounts
672
+ const customerIds = await ads.listAccessibleCustomers();
673
+ \`\`\``,
674
+ ja: `### \u30C4\u30FC\u30EB
675
+
676
+ - \`google-ads_request\`: Google Ads API\u3078\u8A8D\u8A3C\u6E08\u307F\u30EA\u30AF\u30A8\u30B9\u30C8\u3092\u9001\u4FE1\u3057\u307E\u3059\u3002searchStream\u3092\u4F7F\u3063\u305FGAQL\u30AF\u30A8\u30EA\u306B\u4F7F\u7528\u3057\u307E\u3059\u3002\u30D1\u30B9\u5185\u306E{customerId}\u30D7\u30EC\u30FC\u30B9\u30DB\u30EB\u30C0\u30FC\u306F\u81EA\u52D5\u7684\u306B\u7F6E\u63DB\u3055\u308C\u307E\u3059\uFF08\u30CF\u30A4\u30D5\u30F3\u306F\u9664\u53BB\uFF09\u3002\u30B5\u30FC\u30D3\u30B9\u30A2\u30AB\u30A6\u30F3\u30C8\u306B\u3088\u308B\u8A8D\u8A3C\u3068\u30C7\u30D9\u30ED\u30C3\u30D1\u30FC\u30C8\u30FC\u30AF\u30F3\u306F\u81EA\u52D5\u8A2D\u5B9A\u3055\u308C\u307E\u3059\u3002
677
+ - \`google-ads_listCustomers\`: \u30A2\u30AF\u30BB\u30B9\u53EF\u80FD\u306AGoogle Ads\u9867\u5BA2\u30A2\u30AB\u30A6\u30F3\u30C8\u306E\u4E00\u89A7\u3092\u53D6\u5F97\u3057\u307E\u3059\u3002\u30BB\u30C3\u30C8\u30A2\u30C3\u30D7\u6642\u306B\u5229\u7528\u53EF\u80FD\u306A\u30A2\u30AB\u30A6\u30F3\u30C8\u3092\u78BA\u8A8D\u3059\u308B\u305F\u3081\u306B\u4F7F\u7528\u3057\u307E\u3059\u3002
678
+
679
+ ### Google Ads API \u30EA\u30D5\u30A1\u30EC\u30F3\u30B9
680
+
681
+ #### \u30C7\u30FC\u30BF\u306E\u30AF\u30A8\u30EA (searchStream)
682
+ - POST customers/{customerId}/googleAds:searchStream
683
+ - Body: { "query": "SELECT campaign.id, campaign.name, metrics.impressions FROM campaign WHERE segments.date DURING LAST_30_DAYS" }
684
+
685
+ ### \u4E3B\u8981\u306AGAQL\u30EA\u30BD\u30FC\u30B9
686
+ - \`campaign\`: \u30AD\u30E3\u30F3\u30DA\u30FC\u30F3\u30C7\u30FC\u30BF (campaign.id, campaign.name, campaign.status)
687
+ - \`ad_group\`: \u5E83\u544A\u30B0\u30EB\u30FC\u30D7\u30C7\u30FC\u30BF (ad_group.id, ad_group.name, ad_group.status)
688
+ - \`ad_group_ad\`: \u5E83\u544A\u30C7\u30FC\u30BF (ad_group_ad.ad.id, ad_group_ad.status)
689
+ - \`keyword_view\`: \u30AD\u30FC\u30EF\u30FC\u30C9\u30D1\u30D5\u30A9\u30FC\u30DE\u30F3\u30B9\u30C7\u30FC\u30BF
690
+
691
+ ### \u4E3B\u8981\u306A\u30E1\u30C8\u30EA\u30AF\u30B9
692
+ metrics.impressions, metrics.clicks, metrics.cost_micros, metrics.conversions,
693
+ metrics.ctr, metrics.average_cpc, metrics.conversions_value
694
+
695
+ ### \u4E3B\u8981\u306A\u30BB\u30B0\u30E1\u30F3\u30C8
696
+ segments.date, segments.device, segments.ad_network_type
697
+
698
+ ### \u65E5\u4ED8\u30D5\u30A3\u30EB\u30BF
699
+ - \`DURING LAST_7_DAYS\`, \`DURING LAST_30_DAYS\`, \`DURING THIS_MONTH\`
700
+ - \`WHERE segments.date BETWEEN '2024-01-01' AND '2024-01-31'\`
701
+
702
+ ### \u30D2\u30F3\u30C8
703
+ - cost_micros \u306F\u30DE\u30A4\u30AF\u30ED\u5358\u4F4D\u3067\u3059\uFF08\u5B9F\u969B\u306E\u901A\u8CA8\u984D\u306B\u3059\u308B\u306B\u306F1,000,000\u3067\u5272\u308A\u307E\u3059\uFF09
704
+ - LIMIT \u3092\u4F7F\u7528\u3057\u3066\u7D50\u679C\u6570\u3092\u5236\u9650\u3057\u307E\u3059
705
+ - \u30C7\u30FC\u30BF\u3092\u30D5\u30A3\u30EB\u30BF\u3059\u308B\u305F\u3081\u306B\u5E38\u306B\u9069\u5207\u306AWHERE\u53E5\u3092\u542B\u3081\u3066\u304F\u3060\u3055\u3044
706
+
707
+ ### Business Logic
708
+
709
+ \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\u306B\u793A\u3059\u30B3\u30CD\u30AF\u30BFSDK\u3092\u4F7F\u7528\u3057\u3066\u30CF\u30F3\u30C9\u30E9\u30B3\u30FC\u30C9\u3092\u8A18\u8FF0\u3057\u3066\u304F\u3060\u3055\u3044\u3002\u74B0\u5883\u5909\u6570\u304B\u3089\u76F4\u63A5\u8A8D\u8A3C\u60C5\u5831\u306B\u30A2\u30AF\u30BB\u30B9\u3057\u306A\u3044\u3067\u304F\u3060\u3055\u3044\u3002
710
+
711
+ #### Example
712
+
713
+ \`\`\`ts
714
+ import { connection } from "@squadbase/vite-server/connectors/google-ads";
715
+
716
+ const ads = connection("<connectionId>");
717
+
718
+ // Execute a GAQL query
719
+ const rows = await ads.search(
720
+ "SELECT campaign.name, metrics.impressions, metrics.clicks FROM campaign WHERE segments.date DURING LAST_7_DAYS"
721
+ );
722
+ rows.forEach(row => console.log(row));
723
+
724
+ // List accessible customer accounts
725
+ const customerIds = await ads.listAccessibleCustomers();
726
+ \`\`\``
727
+ },
728
+ tools
729
+ });
730
+
731
+ // src/connectors/create-connector-sdk.ts
732
+ import { readFileSync } from "fs";
733
+ import path from "path";
734
+
735
+ // src/connector-client/env.ts
736
+ function resolveEnvVar(entry, key, connectionId) {
737
+ const envVarName = entry.envVars[key];
738
+ if (!envVarName) {
739
+ throw new Error(`Connection "${connectionId}" is missing envVars mapping for key "${key}"`);
740
+ }
741
+ const value = process.env[envVarName];
742
+ if (!value) {
743
+ throw new Error(`Environment variable "${envVarName}" (for connection "${connectionId}", key "${key}") is not set`);
744
+ }
745
+ return value;
746
+ }
747
+ function resolveEnvVarOptional(entry, key) {
748
+ const envVarName = entry.envVars[key];
749
+ if (!envVarName) return void 0;
750
+ return process.env[envVarName] || void 0;
751
+ }
752
+
753
+ // src/connector-client/proxy-fetch.ts
754
+ import { getContext } from "hono/context-storage";
755
+ import { getCookie } from "hono/cookie";
756
+ var APP_SESSION_COOKIE_NAME = "__Host-squadbase-session";
757
+ function createSandboxProxyFetch(connectionId) {
758
+ return async (input, init) => {
759
+ const token = process.env.INTERNAL_SQUADBASE_OAUTH_MACHINE_CREDENTIAL;
760
+ const sandboxId = process.env.INTERNAL_SQUADBASE_SANDBOX_ID;
761
+ if (!token || !sandboxId) {
762
+ throw new Error(
763
+ "Connection proxy is not configured. Please check your deployment settings."
764
+ );
765
+ }
766
+ const originalUrl = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
767
+ const originalMethod = init?.method ?? "GET";
768
+ const originalBody = init?.body ? JSON.parse(init.body) : void 0;
769
+ const baseDomain = process.env["SQUADBASE_PREVIEW_BASE_DOMAIN"] ?? "preview.app.squadbase.dev";
770
+ const proxyUrl = `https://${sandboxId}.${baseDomain}/_sqcore/connections/${connectionId}/request`;
771
+ return fetch(proxyUrl, {
772
+ method: "POST",
773
+ headers: {
774
+ "Content-Type": "application/json",
775
+ Authorization: `Bearer ${token}`
776
+ },
777
+ body: JSON.stringify({
778
+ url: originalUrl,
779
+ method: originalMethod,
780
+ body: originalBody
781
+ })
782
+ });
783
+ };
784
+ }
785
+ function createDeployedAppProxyFetch(connectionId) {
786
+ const projectId = process.env["SQUADBASE_PROJECT_ID"];
787
+ if (!projectId) {
788
+ throw new Error(
789
+ "Connection proxy is not configured. Please check your deployment settings."
790
+ );
791
+ }
792
+ const baseDomain = process.env["SQUADBASE_APP_BASE_DOMAIN"] ?? "squadbase.app";
793
+ const proxyUrl = `https://${projectId}.${baseDomain}/_sqcore/connections/${connectionId}/request`;
794
+ return async (input, init) => {
795
+ const originalUrl = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
796
+ const originalMethod = init?.method ?? "GET";
797
+ const originalBody = init?.body ? JSON.parse(init.body) : void 0;
798
+ const c = getContext();
799
+ const appSession = getCookie(c, APP_SESSION_COOKIE_NAME);
800
+ if (!appSession) {
801
+ throw new Error(
802
+ "No authentication method available for connection proxy."
803
+ );
804
+ }
805
+ return fetch(proxyUrl, {
806
+ method: "POST",
807
+ headers: {
808
+ "Content-Type": "application/json",
809
+ Authorization: `Bearer ${appSession}`
810
+ },
811
+ body: JSON.stringify({
812
+ url: originalUrl,
813
+ method: originalMethod,
814
+ body: originalBody
815
+ })
816
+ });
817
+ };
818
+ }
819
+ function createProxyFetch(connectionId) {
820
+ if (process.env.INTERNAL_SQUADBASE_SANDBOX_ID) {
821
+ return createSandboxProxyFetch(connectionId);
822
+ }
823
+ return createDeployedAppProxyFetch(connectionId);
824
+ }
825
+
826
+ // src/connectors/create-connector-sdk.ts
827
+ function loadConnectionsSync() {
828
+ const filePath = process.env.CONNECTIONS_PATH ?? path.join(process.cwd(), ".squadbase/connections.json");
829
+ try {
830
+ const raw = readFileSync(filePath, "utf-8");
831
+ return JSON.parse(raw);
832
+ } catch {
833
+ return {};
834
+ }
835
+ }
836
+ function createConnectorSdk(plugin, createClient2) {
837
+ return (connectionId) => {
838
+ const connections = loadConnectionsSync();
839
+ const entry = connections[connectionId];
840
+ if (!entry) {
841
+ throw new Error(
842
+ `Connection "${connectionId}" not found in .squadbase/connections.json`
843
+ );
844
+ }
845
+ if (entry.connector.slug !== plugin.slug) {
846
+ throw new Error(
847
+ `Connection "${connectionId}" is not a ${plugin.slug} connection (got "${entry.connector.slug}")`
848
+ );
849
+ }
850
+ const params = {};
851
+ for (const param of Object.values(plugin.parameters)) {
852
+ if (param.required) {
853
+ params[param.slug] = resolveEnvVar(entry, param.slug, connectionId);
854
+ } else {
855
+ const val = resolveEnvVarOptional(entry, param.slug);
856
+ if (val !== void 0) params[param.slug] = val;
857
+ }
858
+ }
859
+ return createClient2(params, createProxyFetch(connectionId));
860
+ };
861
+ }
862
+
863
+ // src/connectors/entries/google-ads.ts
864
+ var connection = createConnectorSdk(googleAdsConnector, createClient);
865
+ export {
866
+ connection
867
+ };