@langchain/google 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/LICENSE +21 -0
  3. package/README.md +97 -0
  4. package/dist/_virtual/rolldown_runtime.cjs +25 -0
  5. package/dist/chat_models/api-types.d.cts +1506 -0
  6. package/dist/chat_models/api-types.d.ts +1506 -0
  7. package/dist/chat_models/base.cjs +445 -0
  8. package/dist/chat_models/base.cjs.map +1 -0
  9. package/dist/chat_models/base.d.cts +319 -0
  10. package/dist/chat_models/base.d.ts +319 -0
  11. package/dist/chat_models/base.js +442 -0
  12. package/dist/chat_models/base.js.map +1 -0
  13. package/dist/chat_models/index.cjs +23 -0
  14. package/dist/chat_models/index.cjs.map +1 -0
  15. package/dist/chat_models/index.d.cts +39 -0
  16. package/dist/chat_models/index.d.ts +39 -0
  17. package/dist/chat_models/index.js +22 -0
  18. package/dist/chat_models/index.js.map +1 -0
  19. package/dist/chat_models/node.cjs +35 -0
  20. package/dist/chat_models/node.cjs.map +1 -0
  21. package/dist/chat_models/node.d.cts +13 -0
  22. package/dist/chat_models/node.d.ts +13 -0
  23. package/dist/chat_models/node.js +34 -0
  24. package/dist/chat_models/node.js.map +1 -0
  25. package/dist/chat_models/profiles.cjs +373 -0
  26. package/dist/chat_models/profiles.cjs.map +1 -0
  27. package/dist/chat_models/profiles.js +372 -0
  28. package/dist/chat_models/profiles.js.map +1 -0
  29. package/dist/chat_models/types.d.cts +250 -0
  30. package/dist/chat_models/types.d.ts +250 -0
  31. package/dist/clients/index.cjs +219 -0
  32. package/dist/clients/index.cjs.map +1 -0
  33. package/dist/clients/index.d.cts +49 -0
  34. package/dist/clients/index.d.ts +49 -0
  35. package/dist/clients/index.js +217 -0
  36. package/dist/clients/index.js.map +1 -0
  37. package/dist/clients/node.cjs +327 -0
  38. package/dist/clients/node.cjs.map +1 -0
  39. package/dist/clients/node.d.cts +59 -0
  40. package/dist/clients/node.d.ts +59 -0
  41. package/dist/clients/node.js +325 -0
  42. package/dist/clients/node.js.map +1 -0
  43. package/dist/const.cjs +13 -0
  44. package/dist/const.cjs.map +1 -0
  45. package/dist/const.js +9 -0
  46. package/dist/const.js.map +1 -0
  47. package/dist/converters/messages.cjs +697 -0
  48. package/dist/converters/messages.cjs.map +1 -0
  49. package/dist/converters/messages.js +691 -0
  50. package/dist/converters/messages.js.map +1 -0
  51. package/dist/converters/params.cjs +205 -0
  52. package/dist/converters/params.cjs.map +1 -0
  53. package/dist/converters/params.js +202 -0
  54. package/dist/converters/params.js.map +1 -0
  55. package/dist/converters/tools.cjs +356 -0
  56. package/dist/converters/tools.cjs.map +1 -0
  57. package/dist/converters/tools.js +353 -0
  58. package/dist/converters/tools.js.map +1 -0
  59. package/dist/index.cjs +7 -0
  60. package/dist/index.d.cts +3 -0
  61. package/dist/index.d.ts +3 -0
  62. package/dist/index.js +4 -0
  63. package/dist/node.cjs +7 -0
  64. package/dist/node.d.cts +3 -0
  65. package/dist/node.d.ts +3 -0
  66. package/dist/node.js +4 -0
  67. package/dist/utils/errors.cjs +543 -0
  68. package/dist/utils/errors.cjs.map +1 -0
  69. package/dist/utils/errors.js +535 -0
  70. package/dist/utils/errors.js.map +1 -0
  71. package/dist/utils/gcp-auth.cjs +188 -0
  72. package/dist/utils/gcp-auth.cjs.map +1 -0
  73. package/dist/utils/gcp-auth.d.cts +43 -0
  74. package/dist/utils/gcp-auth.d.ts +43 -0
  75. package/dist/utils/gcp-auth.js +186 -0
  76. package/dist/utils/gcp-auth.js.map +1 -0
  77. package/dist/utils/handler.cjs +67 -0
  78. package/dist/utils/handler.cjs.map +1 -0
  79. package/dist/utils/handler.d.cts +34 -0
  80. package/dist/utils/handler.d.ts +34 -0
  81. package/dist/utils/handler.js +64 -0
  82. package/dist/utils/handler.js.map +1 -0
  83. package/dist/utils/misc.cjs +10 -0
  84. package/dist/utils/misc.cjs.map +1 -0
  85. package/dist/utils/misc.d.cts +14 -0
  86. package/dist/utils/misc.d.ts +14 -0
  87. package/dist/utils/misc.js +9 -0
  88. package/dist/utils/misc.js.map +1 -0
  89. package/dist/utils/stream.cjs +26 -0
  90. package/dist/utils/stream.cjs.map +1 -0
  91. package/dist/utils/stream.js +25 -0
  92. package/dist/utils/stream.js.map +1 -0
  93. package/package.json +96 -0
@@ -0,0 +1,59 @@
1
+ import { GCPCredentials } from "../utils/gcp-auth.js";
2
+ import { GoogleAuth, GoogleAuthOptions } from "google-auth-library";
3
+
4
+ //#region src/clients/node.d.ts
5
+
6
+ /**
7
+ * Configuration parameters for the NodeApiClient.
8
+ *
9
+ * This interface defines the authentication options available for Node.js-based
10
+ * API clients. Authentication can be provided via an API key, GCP service
11
+ * account credentials, or advanced Google Auth options. The client will
12
+ * automatically check environment variables if explicit values are not provided.
13
+ *
14
+ * @interface
15
+ */
16
+ interface NodeApiClientParams {
17
+ /**
18
+ * Google API key for authentication.
19
+ *
20
+ * If not provided, the client will attempt to read from the
21
+ * `GOOGLE_API_KEY` environment variable.
22
+ *
23
+ * @see https://cloud.google.com/docs/authentication/api-keys
24
+ */
25
+ apiKey?: string;
26
+ /**
27
+ * GCP service account credentials for authentication.
28
+ *
29
+ * Can be provided as either:
30
+ * - A JSON string containing the service account key
31
+ * - A GCPCredentials object
32
+ *
33
+ * If not provided, the client will attempt to read from the
34
+ * `GOOGLE_CLOUD_CREDENTIALS` environment variable.
35
+ *
36
+ * @see https://cloud.google.com/iam/docs/creating-managing-service-account-keys
37
+ */
38
+ credentials?: string | GCPCredentials;
39
+ /**
40
+ * Google Auth options configuration.
41
+ *
42
+ * Provides fine-grained control over authentication behavior using the
43
+ * google-auth-library. This option enables:
44
+ * - Custom OAuth2 scopes
45
+ * - Application Default Credentials (ADC)
46
+ * - Impersonation and delegation
47
+ * - Custom credential sources
48
+ *
49
+ * When provided, this takes precedence over simple credential-based auth
50
+ * but is lower priority than API key authentication.
51
+ *
52
+ * @see https://github.com/googleapis/google-auth-library-nodejs
53
+ * @see https://cloud.google.com/docs/authentication/application-default-credentials
54
+ */
55
+ googleAuthOptions?: GoogleAuthOptions;
56
+ }
57
+ //#endregion
58
+ export { NodeApiClientParams };
59
+ //# sourceMappingURL=node.d.ts.map
@@ -0,0 +1,325 @@
1
+ import { GCP_API_KEY_HEADER, GOOGLE_API_KEY_HEADER } from "../const.js";
2
+ import { iife } from "../utils/misc.js";
3
+ import { ConfigurationError } from "../utils/errors.js";
4
+ import { getGCPCredentialsAccessToken, normalizeGCPCredentials } from "../utils/gcp-auth.js";
5
+ import { ApiClient } from "./index.js";
6
+ import { getEnvironmentVariable } from "@langchain/core/utils/env";
7
+ import { GoogleAuth } from "google-auth-library";
8
+
9
+ //#region src/clients/node.ts
10
+ /**
11
+ * Node.js-specific API client for Google services.
12
+ *
13
+ * This client provides comprehensive authentication for Google API requests in
14
+ * Node.js environments, leveraging the full capabilities of the google-auth-library.
15
+ * It supports three authentication methods with the following priority:
16
+ *
17
+ * 1. **API Key Authentication**: Simple key-based authentication suitable for
18
+ * public APIs and development environments.
19
+ *
20
+ * 2. **Service Account Credentials**: OAuth2-based authentication using GCP
21
+ * service account keys. The client automatically handles token generation
22
+ * and caching using a web-compatible implementation.
23
+ *
24
+ * 3. **Google Auth Library**: Advanced authentication using google-auth-library,
25
+ * supporting Application Default Credentials (ADC), custom scopes, and
26
+ * various credential sources.
27
+ *
28
+ * The client follows this authentication priority:
29
+ * 1. Explicit `apiKey` parameter
30
+ * 2. `GOOGLE_API_KEY` environment variable
31
+ * 3. Explicit `credentials` parameter
32
+ * 4. `GOOGLE_CLOUD_CREDENTIALS` environment variable
33
+ * 5. `googleAuthOptions` parameter
34
+ * 6. Application Default Credentials (if googleAuthOptions is provided without explicit credentials)
35
+ *
36
+ * @extends ApiClient
37
+ *
38
+ * @example
39
+ * ```typescript
40
+ * // Using API key
41
+ * const client = new NodeApiClient({
42
+ * apiKey: 'your-api-key'
43
+ * });
44
+ *
45
+ * // Using service account credentials
46
+ * const client = new NodeApiClient({
47
+ * credentials: {
48
+ * type: "service_account",
49
+ * project_id: "my-project",
50
+ * private_key_id: "key-id",
51
+ * private_key: "-----BEGIN PRIVATE KEY-----\n...",
52
+ * client_email: "service-account@project.iam.gserviceaccount.com",
53
+ * // ... other required fields
54
+ * }
55
+ * });
56
+ *
57
+ * // Using Google Auth with custom scopes
58
+ * const client = new NodeApiClient({
59
+ * googleAuthOptions: {
60
+ * scopes: ['https://www.googleapis.com/auth/cloud-platform'],
61
+ * keyFilename: '/path/to/service-account-key.json'
62
+ * }
63
+ * });
64
+ *
65
+ * // Using Application Default Credentials
66
+ * const client = new NodeApiClient({
67
+ * googleAuthOptions: {}
68
+ * });
69
+ *
70
+ * // Using environment variables
71
+ * // Set GOOGLE_API_KEY or GOOGLE_CLOUD_CREDENTIALS
72
+ * const client = new NodeApiClient();
73
+ *
74
+ * // Make authenticated requests
75
+ * const request = new Request('https://api.google.com/...');
76
+ * const response = await client.fetch(request);
77
+ * ```
78
+ *
79
+ * @remarks
80
+ * - API keys are added via the `X-Goog-Api-Key` header
81
+ * - Service account tokens are added via the `Authorization` header with Bearer scheme
82
+ * - Google Auth headers are automatically generated and added by google-auth-library
83
+ * - Tokens are automatically cached and refreshed as needed
84
+ * - For web/edge environments without google-auth-library, use WebApiClient instead
85
+ *
86
+ * @see {@link WebApiClient} for web-compatible authentication without google-auth-library
87
+ * @see {@link GCPCredentials} for service account credential structure
88
+ * @see {@link GoogleAuthOptions} for advanced authentication configuration
89
+ */
90
+ var NodeApiClient = class extends ApiClient {
91
+ hasApiKey() {
92
+ return typeof this.apiKey === "string" && this.apiKey !== "";
93
+ }
94
+ async getProjectId() {
95
+ if (typeof this.credentials !== "undefined") return this.credentials.project_id;
96
+ else if (typeof this.googleAuth !== "undefined") return this.googleAuth.getProjectId();
97
+ else return super.getProjectId();
98
+ }
99
+ /**
100
+ * The Google API key used for authentication, if provided.
101
+ *
102
+ * This value is resolved from either the constructor parameter or the
103
+ * `GOOGLE_API_KEY` environment variable.
104
+ *
105
+ * @protected
106
+ */
107
+ apiKey;
108
+ /**
109
+ * The normalized GCP service account credentials, if provided.
110
+ *
111
+ * This value is resolved from either the constructor parameter or the
112
+ * `GOOGLE_CLOUD_CREDENTIALS` environment variable, and is normalized
113
+ * to ensure immutability.
114
+ *
115
+ * @protected
116
+ */
117
+ credentials;
118
+ /**
119
+ * The Google Auth instance for advanced authentication, if configured.
120
+ *
121
+ * This instance is created when `googleAuthOptions` is provided and
122
+ * handles Application Default Credentials, custom scopes, and other
123
+ * advanced authentication scenarios.
124
+ *
125
+ * @protected
126
+ */
127
+ googleAuth;
128
+ /**
129
+ * Creates a new NodeApiClient instance.
130
+ *
131
+ * The constructor initializes authentication credentials by checking:
132
+ * 1. Explicit parameters passed to the constructor
133
+ * 2. Environment variables (`GOOGLE_API_KEY`, `GOOGLE_CLOUD_CREDENTIALS`)
134
+ * 3. Application Default Credentials (if googleAuthOptions is provided)
135
+ *
136
+ * Credentials are normalized and frozen to prevent accidental modification.
137
+ * The GoogleAuth instance is lazily initialized only when googleAuthOptions
138
+ * is provided.
139
+ *
140
+ * @param params - Configuration parameters for the client. Defaults to an empty object.
141
+ *
142
+ * @example
143
+ * ```typescript
144
+ * // Minimal configuration (uses environment variables or ADC)
145
+ * const client = new NodeApiClient();
146
+ *
147
+ * // With explicit API key
148
+ * const client = new WebApiClient({
149
+ * apiKey: 'your-api-key'
150
+ * });
151
+ *
152
+ * // With service account credentials as JSON string
153
+ * const client = new WebApiClient({
154
+ * credentials: '{"type":"service_account",...}'
155
+ * });
156
+ *
157
+ * // With service account credentials as object
158
+ * const client = new NodeApiClient({
159
+ * credentials: {
160
+ * type: "service_account",
161
+ * // ... other fields
162
+ * }
163
+ * });
164
+ *
165
+ * // With Google Auth options
166
+ * const client = new NodeApiClient({
167
+ * googleAuthOptions: {
168
+ * scopes: ['https://www.googleapis.com/auth/cloud-platform'],
169
+ * projectId: 'my-project'
170
+ * }
171
+ * });
172
+ * ```
173
+ */
174
+ constructor(params = {}) {
175
+ super();
176
+ this.params = params;
177
+ this.apiKey = params.apiKey ?? getEnvironmentVariable("GOOGLE_API_KEY");
178
+ this.credentials = iife(() => {
179
+ if (params.credentials) return normalizeGCPCredentials(params.credentials);
180
+ const credentialsVar = getEnvironmentVariable("GOOGLE_CLOUD_CREDENTIALS");
181
+ if (credentialsVar) return normalizeGCPCredentials(credentialsVar);
182
+ return void 0;
183
+ });
184
+ this.googleAuth = iife(() => {
185
+ if (params.googleAuthOptions) return new GoogleAuth(params.googleAuthOptions);
186
+ if (!this.apiKey && !this.credentials) return new GoogleAuth();
187
+ return void 0;
188
+ });
189
+ }
190
+ /**
191
+ * Executes an HTTP request with appropriate Google API authentication.
192
+ *
193
+ * This method adds authentication headers to the request based on the
194
+ * configured authentication method, following this priority:
195
+ *
196
+ * 1. If an API key is configured, adds the `X-Goog-Api-Key` header
197
+ * 2. If service account credentials are configured, generates an access token
198
+ * and adds it via the `Authorization` header with Bearer scheme
199
+ * 3. If Google Auth is configured, uses google-auth-library to generate
200
+ * appropriate authentication headers (may include Authorization, x-goog-user-project, etc.)
201
+ *
202
+ * The authentication priority ensures that explicit API keys take precedence,
203
+ * followed by service account credentials, and finally Google Auth options.
204
+ *
205
+ * @param request - The HTTP request to execute. Headers will be modified
206
+ * in-place to include authentication information.
207
+ * @returns A Promise that resolves to the HTTP response
208
+ *
209
+ * @throws {AuthError} If service account authentication fails (e.g., invalid
210
+ * credentials, network error, or token generation failure)
211
+ * @throws {Error} If Google Auth authentication fails (e.g., missing credentials,
212
+ * invalid configuration, or ADC not available)
213
+ *
214
+ * @example
215
+ * ```typescript
216
+ * const client = new NodeApiClient({ apiKey: 'your-key' });
217
+ * const request = new Request('https://generativelanguage.googleapis.com/v1/models');
218
+ * const response = await client.fetch(request);
219
+ * const data = await response.json();
220
+ * ```
221
+ *
222
+ * @remarks
223
+ * - The request object is modified in-place by adding headers
224
+ * - Service account tokens are automatically cached and refreshed
225
+ * - Google Auth tokens are managed by google-auth-library with automatic refresh
226
+ * - Only one authentication method is used per request (based on priority)
227
+ * - Google Auth may add multiple headers depending on the authentication type
228
+ */
229
+ async fetch(request) {
230
+ if (this.apiKey) request.headers.set(GOOGLE_API_KEY_HEADER, this.apiKey);
231
+ else if (this.credentials) request.headers.set(GCP_API_KEY_HEADER, `Bearer ${getGCPCredentialsAccessToken(this.credentials)}`);
232
+ else if (this.googleAuth) {
233
+ const authHeaders = await this.googleAuth.getRequestHeaders(request.url);
234
+ authHeaders.forEach((value, key) => {
235
+ if (value !== null) request.headers.set(key, value);
236
+ });
237
+ }
238
+ return fetch(request);
239
+ }
240
+ };
241
+ /**
242
+ * Ensures that Google Auth options include required OAuth2 scopes.
243
+ *
244
+ * This utility function validates and augments GoogleAuthOptions to ensure
245
+ * that all required OAuth2 scopes are present. It handles three scenarios:
246
+ *
247
+ * 1. **No auth options provided**: Creates new options with required scopes
248
+ * 2. **Auth options without scopes**: Adds required scopes to existing options
249
+ * 3. **Auth options with scopes**: Validates that all required scopes are present
250
+ *
251
+ * This is particularly useful when working with Google APIs that require specific
252
+ * scopes for access, ensuring that authentication is properly configured before
253
+ * making API requests.
254
+ *
255
+ * @param authOptions - The existing Google Auth options to validate/augment.
256
+ * Can be undefined or an empty object.
257
+ * @param requiredScopes - Array of OAuth2 scope URLs that must be present.
258
+ * These are typically Google API scope URLs like
259
+ * 'https://www.googleapis.com/auth/cloud-platform'
260
+ * @returns The validated/augmented GoogleAuthOptions with all required scopes
261
+ *
262
+ * @throws {Error} If authOptions already has scopes but is missing any of the
263
+ * required scopes. This prevents accidental scope reduction that
264
+ * could break API access.
265
+ *
266
+ * @example
267
+ * ```typescript
268
+ * // Create new options with required scopes
269
+ * const options = ensureAuthScopes(undefined, [
270
+ * 'https://www.googleapis.com/auth/cloud-platform'
271
+ * ]);
272
+ * // Result: { scopes: ['https://www.googleapis.com/auth/cloud-platform'] }
273
+ *
274
+ * // Add scopes to existing options
275
+ * const options = ensureAuthScopes(
276
+ * { projectId: 'my-project' },
277
+ * ['https://www.googleapis.com/auth/cloud-platform']
278
+ * );
279
+ * // Result: { projectId: 'my-project', scopes: [...] }
280
+ *
281
+ * // Validate existing scopes
282
+ * const options = ensureAuthScopes(
283
+ * { scopes: ['https://www.googleapis.com/auth/cloud-platform'] },
284
+ * ['https://www.googleapis.com/auth/cloud-platform']
285
+ * );
286
+ * // Result: Original options (validation passed)
287
+ *
288
+ * // Error case - missing required scope
289
+ * try {
290
+ * ensureAuthScopes(
291
+ * { scopes: ['https://www.googleapis.com/auth/userinfo.email'] },
292
+ * ['https://www.googleapis.com/auth/cloud-platform']
293
+ * );
294
+ * } catch (error) {
295
+ * // Error: Invalid auth scopes. Scopes must include ...
296
+ * }
297
+ * ```
298
+ *
299
+ * @remarks
300
+ * - Scopes can be provided as a string or array of strings in GoogleAuthOptions
301
+ * - The function normalizes single-string scopes to arrays for validation
302
+ * - Required scopes are not automatically added if existing scopes are present;
303
+ * instead, an error is thrown to prevent unintended scope changes
304
+ * - This function does not modify the original authOptions object
305
+ *
306
+ * @see https://developers.google.com/identity/protocols/oauth2/scopes
307
+ * @see {@link GoogleAuthOptions} for the full authentication configuration interface
308
+ */
309
+ function ensureAuthScopes(authOptions, requiredScopes) {
310
+ if (!authOptions) return { scopes: requiredScopes };
311
+ else if (!authOptions.scopes) return {
312
+ ...authOptions,
313
+ scopes: requiredScopes
314
+ };
315
+ else {
316
+ const existingScopes = Array.isArray(authOptions.scopes) ? authOptions.scopes : [authOptions.scopes];
317
+ const missingScopes = requiredScopes.filter((scope) => !existingScopes.includes(scope));
318
+ if (missingScopes.length > 0) throw new ConfigurationError(`Invalid auth scopes. Scopes must include ${requiredScopes.join(", ")}`);
319
+ }
320
+ return authOptions;
321
+ }
322
+
323
+ //#endregion
324
+ export { NodeApiClient, ensureAuthScopes };
325
+ //# sourceMappingURL=node.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node.js","names":["params: NodeApiClientParams","request: Request","authOptions: GoogleAuthOptions","requiredScopes: string[]"],"sources":["../../src/clients/node.ts"],"sourcesContent":["import { GoogleAuth, type GoogleAuthOptions } from \"google-auth-library\";\nimport { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { GCP_API_KEY_HEADER, GOOGLE_API_KEY_HEADER } from \"../const.js\";\nimport { ApiClient } from \"./index.js\";\nimport {\n GCPCredentials,\n getGCPCredentialsAccessToken,\n normalizeGCPCredentials,\n} from \"../utils/gcp-auth.js\";\nimport { ConfigurationError } from \"../utils/errors.js\";\nimport { iife } from \"../utils/misc.js\";\n\n/**\n * Configuration parameters for the NodeApiClient.\n *\n * This interface defines the authentication options available for Node.js-based\n * API clients. Authentication can be provided via an API key, GCP service\n * account credentials, or advanced Google Auth options. The client will\n * automatically check environment variables if explicit values are not provided.\n *\n * @interface\n */\nexport interface NodeApiClientParams {\n /**\n * Google API key for authentication.\n *\n * If not provided, the client will attempt to read from the\n * `GOOGLE_API_KEY` environment variable.\n *\n * @see https://cloud.google.com/docs/authentication/api-keys\n */\n apiKey?: string;\n\n /**\n * GCP service account credentials for authentication.\n *\n * Can be provided as either:\n * - A JSON string containing the service account key\n * - A GCPCredentials object\n *\n * If not provided, the client will attempt to read from the\n * `GOOGLE_CLOUD_CREDENTIALS` environment variable.\n *\n * @see https://cloud.google.com/iam/docs/creating-managing-service-account-keys\n */\n credentials?: string | GCPCredentials;\n\n /**\n * Google Auth options configuration.\n *\n * Provides fine-grained control over authentication behavior using the\n * google-auth-library. This option enables:\n * - Custom OAuth2 scopes\n * - Application Default Credentials (ADC)\n * - Impersonation and delegation\n * - Custom credential sources\n *\n * When provided, this takes precedence over simple credential-based auth\n * but is lower priority than API key authentication.\n *\n * @see https://github.com/googleapis/google-auth-library-nodejs\n * @see https://cloud.google.com/docs/authentication/application-default-credentials\n */\n googleAuthOptions?: GoogleAuthOptions;\n}\n\n/**\n * Node.js-specific API client for Google services.\n *\n * This client provides comprehensive authentication for Google API requests in\n * Node.js environments, leveraging the full capabilities of the google-auth-library.\n * It supports three authentication methods with the following priority:\n *\n * 1. **API Key Authentication**: Simple key-based authentication suitable for\n * public APIs and development environments.\n *\n * 2. **Service Account Credentials**: OAuth2-based authentication using GCP\n * service account keys. The client automatically handles token generation\n * and caching using a web-compatible implementation.\n *\n * 3. **Google Auth Library**: Advanced authentication using google-auth-library,\n * supporting Application Default Credentials (ADC), custom scopes, and\n * various credential sources.\n *\n * The client follows this authentication priority:\n * 1. Explicit `apiKey` parameter\n * 2. `GOOGLE_API_KEY` environment variable\n * 3. Explicit `credentials` parameter\n * 4. `GOOGLE_CLOUD_CREDENTIALS` environment variable\n * 5. `googleAuthOptions` parameter\n * 6. Application Default Credentials (if googleAuthOptions is provided without explicit credentials)\n *\n * @extends ApiClient\n *\n * @example\n * ```typescript\n * // Using API key\n * const client = new NodeApiClient({\n * apiKey: 'your-api-key'\n * });\n *\n * // Using service account credentials\n * const client = new NodeApiClient({\n * credentials: {\n * type: \"service_account\",\n * project_id: \"my-project\",\n * private_key_id: \"key-id\",\n * private_key: \"-----BEGIN PRIVATE KEY-----\\n...\",\n * client_email: \"service-account@project.iam.gserviceaccount.com\",\n * // ... other required fields\n * }\n * });\n *\n * // Using Google Auth with custom scopes\n * const client = new NodeApiClient({\n * googleAuthOptions: {\n * scopes: ['https://www.googleapis.com/auth/cloud-platform'],\n * keyFilename: '/path/to/service-account-key.json'\n * }\n * });\n *\n * // Using Application Default Credentials\n * const client = new NodeApiClient({\n * googleAuthOptions: {}\n * });\n *\n * // Using environment variables\n * // Set GOOGLE_API_KEY or GOOGLE_CLOUD_CREDENTIALS\n * const client = new NodeApiClient();\n *\n * // Make authenticated requests\n * const request = new Request('https://api.google.com/...');\n * const response = await client.fetch(request);\n * ```\n *\n * @remarks\n * - API keys are added via the `X-Goog-Api-Key` header\n * - Service account tokens are added via the `Authorization` header with Bearer scheme\n * - Google Auth headers are automatically generated and added by google-auth-library\n * - Tokens are automatically cached and refreshed as needed\n * - For web/edge environments without google-auth-library, use WebApiClient instead\n *\n * @see {@link WebApiClient} for web-compatible authentication without google-auth-library\n * @see {@link GCPCredentials} for service account credential structure\n * @see {@link GoogleAuthOptions} for advanced authentication configuration\n */\nexport class NodeApiClient extends ApiClient {\n hasApiKey(): boolean {\n return typeof this.apiKey === \"string\" && this.apiKey !== \"\";\n }\n\n async getProjectId(): Promise<string> {\n if (typeof this.credentials !== \"undefined\") {\n return this.credentials.project_id;\n } else if (typeof this.googleAuth !== \"undefined\") {\n return this.googleAuth.getProjectId();\n } else {\n return super.getProjectId();\n }\n }\n\n /**\n * The Google API key used for authentication, if provided.\n *\n * This value is resolved from either the constructor parameter or the\n * `GOOGLE_API_KEY` environment variable.\n *\n * @protected\n */\n protected apiKey?: string;\n\n /**\n * The normalized GCP service account credentials, if provided.\n *\n * This value is resolved from either the constructor parameter or the\n * `GOOGLE_CLOUD_CREDENTIALS` environment variable, and is normalized\n * to ensure immutability.\n *\n * @protected\n */\n protected credentials?: GCPCredentials;\n\n /**\n * The Google Auth instance for advanced authentication, if configured.\n *\n * This instance is created when `googleAuthOptions` is provided and\n * handles Application Default Credentials, custom scopes, and other\n * advanced authentication scenarios.\n *\n * @protected\n */\n protected googleAuth?: GoogleAuth;\n\n /**\n * Creates a new NodeApiClient instance.\n *\n * The constructor initializes authentication credentials by checking:\n * 1. Explicit parameters passed to the constructor\n * 2. Environment variables (`GOOGLE_API_KEY`, `GOOGLE_CLOUD_CREDENTIALS`)\n * 3. Application Default Credentials (if googleAuthOptions is provided)\n *\n * Credentials are normalized and frozen to prevent accidental modification.\n * The GoogleAuth instance is lazily initialized only when googleAuthOptions\n * is provided.\n *\n * @param params - Configuration parameters for the client. Defaults to an empty object.\n *\n * @example\n * ```typescript\n * // Minimal configuration (uses environment variables or ADC)\n * const client = new NodeApiClient();\n *\n * // With explicit API key\n * const client = new WebApiClient({\n * apiKey: 'your-api-key'\n * });\n *\n * // With service account credentials as JSON string\n * const client = new WebApiClient({\n * credentials: '{\"type\":\"service_account\",...}'\n * });\n *\n * // With service account credentials as object\n * const client = new NodeApiClient({\n * credentials: {\n * type: \"service_account\",\n * // ... other fields\n * }\n * });\n *\n * // With Google Auth options\n * const client = new NodeApiClient({\n * googleAuthOptions: {\n * scopes: ['https://www.googleapis.com/auth/cloud-platform'],\n * projectId: 'my-project'\n * }\n * });\n * ```\n */\n constructor(protected params: NodeApiClientParams = {}) {\n super();\n\n this.apiKey = params.apiKey ?? getEnvironmentVariable(\"GOOGLE_API_KEY\");\n this.credentials = iife(() => {\n if (params.credentials) {\n return normalizeGCPCredentials(params.credentials);\n }\n const credentialsVar = getEnvironmentVariable(\"GOOGLE_CLOUD_CREDENTIALS\");\n if (credentialsVar) {\n return normalizeGCPCredentials(credentialsVar);\n }\n return undefined;\n });\n this.googleAuth = iife(() => {\n if (params.googleAuthOptions) {\n return new GoogleAuth(params.googleAuthOptions);\n }\n if (!this.apiKey && !this.credentials) {\n return new GoogleAuth();\n }\n return undefined;\n });\n }\n\n /**\n * Executes an HTTP request with appropriate Google API authentication.\n *\n * This method adds authentication headers to the request based on the\n * configured authentication method, following this priority:\n *\n * 1. If an API key is configured, adds the `X-Goog-Api-Key` header\n * 2. If service account credentials are configured, generates an access token\n * and adds it via the `Authorization` header with Bearer scheme\n * 3. If Google Auth is configured, uses google-auth-library to generate\n * appropriate authentication headers (may include Authorization, x-goog-user-project, etc.)\n *\n * The authentication priority ensures that explicit API keys take precedence,\n * followed by service account credentials, and finally Google Auth options.\n *\n * @param request - The HTTP request to execute. Headers will be modified\n * in-place to include authentication information.\n * @returns A Promise that resolves to the HTTP response\n *\n * @throws {AuthError} If service account authentication fails (e.g., invalid\n * credentials, network error, or token generation failure)\n * @throws {Error} If Google Auth authentication fails (e.g., missing credentials,\n * invalid configuration, or ADC not available)\n *\n * @example\n * ```typescript\n * const client = new NodeApiClient({ apiKey: 'your-key' });\n * const request = new Request('https://generativelanguage.googleapis.com/v1/models');\n * const response = await client.fetch(request);\n * const data = await response.json();\n * ```\n *\n * @remarks\n * - The request object is modified in-place by adding headers\n * - Service account tokens are automatically cached and refreshed\n * - Google Auth tokens are managed by google-auth-library with automatic refresh\n * - Only one authentication method is used per request (based on priority)\n * - Google Auth may add multiple headers depending on the authentication type\n */\n async fetch(request: Request): Promise<Response> {\n if (this.apiKey) {\n request.headers.set(GOOGLE_API_KEY_HEADER, this.apiKey);\n } else if (this.credentials) {\n request.headers.set(\n GCP_API_KEY_HEADER,\n `Bearer ${getGCPCredentialsAccessToken(this.credentials)}`\n );\n } else if (this.googleAuth) {\n const authHeaders = await this.googleAuth.getRequestHeaders(request.url);\n authHeaders.forEach((value, key) => {\n if (value !== null) {\n request.headers.set(key, value);\n }\n });\n }\n return fetch(request);\n }\n}\n\n/**\n * Ensures that Google Auth options include required OAuth2 scopes.\n *\n * This utility function validates and augments GoogleAuthOptions to ensure\n * that all required OAuth2 scopes are present. It handles three scenarios:\n *\n * 1. **No auth options provided**: Creates new options with required scopes\n * 2. **Auth options without scopes**: Adds required scopes to existing options\n * 3. **Auth options with scopes**: Validates that all required scopes are present\n *\n * This is particularly useful when working with Google APIs that require specific\n * scopes for access, ensuring that authentication is properly configured before\n * making API requests.\n *\n * @param authOptions - The existing Google Auth options to validate/augment.\n * Can be undefined or an empty object.\n * @param requiredScopes - Array of OAuth2 scope URLs that must be present.\n * These are typically Google API scope URLs like\n * 'https://www.googleapis.com/auth/cloud-platform'\n * @returns The validated/augmented GoogleAuthOptions with all required scopes\n *\n * @throws {Error} If authOptions already has scopes but is missing any of the\n * required scopes. This prevents accidental scope reduction that\n * could break API access.\n *\n * @example\n * ```typescript\n * // Create new options with required scopes\n * const options = ensureAuthScopes(undefined, [\n * 'https://www.googleapis.com/auth/cloud-platform'\n * ]);\n * // Result: { scopes: ['https://www.googleapis.com/auth/cloud-platform'] }\n *\n * // Add scopes to existing options\n * const options = ensureAuthScopes(\n * { projectId: 'my-project' },\n * ['https://www.googleapis.com/auth/cloud-platform']\n * );\n * // Result: { projectId: 'my-project', scopes: [...] }\n *\n * // Validate existing scopes\n * const options = ensureAuthScopes(\n * { scopes: ['https://www.googleapis.com/auth/cloud-platform'] },\n * ['https://www.googleapis.com/auth/cloud-platform']\n * );\n * // Result: Original options (validation passed)\n *\n * // Error case - missing required scope\n * try {\n * ensureAuthScopes(\n * { scopes: ['https://www.googleapis.com/auth/userinfo.email'] },\n * ['https://www.googleapis.com/auth/cloud-platform']\n * );\n * } catch (error) {\n * // Error: Invalid auth scopes. Scopes must include ...\n * }\n * ```\n *\n * @remarks\n * - Scopes can be provided as a string or array of strings in GoogleAuthOptions\n * - The function normalizes single-string scopes to arrays for validation\n * - Required scopes are not automatically added if existing scopes are present;\n * instead, an error is thrown to prevent unintended scope changes\n * - This function does not modify the original authOptions object\n *\n * @see https://developers.google.com/identity/protocols/oauth2/scopes\n * @see {@link GoogleAuthOptions} for the full authentication configuration interface\n */\nexport function ensureAuthScopes(\n authOptions: GoogleAuthOptions,\n requiredScopes: string[]\n): GoogleAuthOptions {\n if (!authOptions) {\n return { scopes: requiredScopes };\n } else if (!authOptions.scopes) {\n return { ...authOptions, scopes: requiredScopes };\n } else {\n const existingScopes = Array.isArray(authOptions.scopes)\n ? authOptions.scopes\n : [authOptions.scopes];\n const missingScopes = requiredScopes.filter(\n (scope) => !existingScopes.includes(scope)\n );\n if (missingScopes.length > 0) {\n throw new ConfigurationError(\n `Invalid auth scopes. Scopes must include ${requiredScopes.join(\", \")}`\n );\n }\n }\n return authOptions;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkJA,IAAa,gBAAb,cAAmC,UAAU;CAC3C,YAAqB;AACnB,SAAO,OAAO,KAAK,WAAW,YAAY,KAAK,WAAW;CAC3D;CAED,MAAM,eAAgC;AACpC,MAAI,OAAO,KAAK,gBAAgB,YAC9B,QAAO,KAAK,YAAY;WACf,OAAO,KAAK,eAAe,YACpC,QAAO,KAAK,WAAW,cAAc;MAErC,QAAO,MAAM,cAAc;CAE9B;;;;;;;;;CAUD,AAAU;;;;;;;;;;CAWV,AAAU;;;;;;;;;;CAWV,AAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgDV,YAAsBA,SAA8B,CAAE,GAAE;EACtD,OAAO;EADa;EAGpB,KAAK,SAAS,OAAO,UAAU,uBAAuB,iBAAiB;EACvE,KAAK,cAAc,KAAK,MAAM;AAC5B,OAAI,OAAO,YACT,QAAO,wBAAwB,OAAO,YAAY;GAEpD,MAAM,iBAAiB,uBAAuB,2BAA2B;AACzE,OAAI,eACF,QAAO,wBAAwB,eAAe;AAEhD,UAAO;EACR,EAAC;EACF,KAAK,aAAa,KAAK,MAAM;AAC3B,OAAI,OAAO,kBACT,QAAO,IAAI,WAAW,OAAO;AAE/B,OAAI,CAAC,KAAK,UAAU,CAAC,KAAK,YACxB,QAAO,IAAI;AAEb,UAAO;EACR,EAAC;CACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAyCD,MAAM,MAAMC,SAAqC;AAC/C,MAAI,KAAK,QACP,QAAQ,QAAQ,IAAI,uBAAuB,KAAK,OAAO;WAC9C,KAAK,aACd,QAAQ,QAAQ,IACd,oBACA,CAAC,OAAO,EAAE,6BAA6B,KAAK,YAAY,EAAE,CAC3D;WACQ,KAAK,YAAY;GAC1B,MAAM,cAAc,MAAM,KAAK,WAAW,kBAAkB,QAAQ,IAAI;GACxE,YAAY,QAAQ,CAAC,OAAO,QAAQ;AAClC,QAAI,UAAU,MACZ,QAAQ,QAAQ,IAAI,KAAK,MAAM;GAElC,EAAC;EACH;AACD,SAAO,MAAM,QAAQ;CACtB;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsED,SAAgB,iBACdC,aACAC,gBACmB;AACnB,KAAI,CAAC,YACH,QAAO,EAAE,QAAQ,eAAgB;UACxB,CAAC,YAAY,OACtB,QAAO;EAAE,GAAG;EAAa,QAAQ;CAAgB;MAC5C;EACL,MAAM,iBAAiB,MAAM,QAAQ,YAAY,OAAO,GACpD,YAAY,SACZ,CAAC,YAAY,MAAO;EACxB,MAAM,gBAAgB,eAAe,OACnC,CAAC,UAAU,CAAC,eAAe,SAAS,MAAM,CAC3C;AACD,MAAI,cAAc,SAAS,EACzB,OAAM,IAAI,mBACR,CAAC,yCAAyC,EAAE,eAAe,KAAK,KAAK,EAAE;CAG5E;AACD,QAAO;AACR"}
package/dist/const.cjs ADDED
@@ -0,0 +1,13 @@
1
+
2
+ //#region src/const.ts
3
+ const GOOGLE_API_KEY_HEADER = "x-goog-api-key";
4
+ const GCP_API_KEY_HEADER = "Authorization";
5
+ const GENERATIVE_AI_AUTH_SCOPES = ["https://www.googleapis.com/auth/generative-language"];
6
+ const VERTEX_AI_AUTH_SCOPES = ["https://www.googleapis.com/auth/cloud-platform"];
7
+
8
+ //#endregion
9
+ exports.GCP_API_KEY_HEADER = GCP_API_KEY_HEADER;
10
+ exports.GENERATIVE_AI_AUTH_SCOPES = GENERATIVE_AI_AUTH_SCOPES;
11
+ exports.GOOGLE_API_KEY_HEADER = GOOGLE_API_KEY_HEADER;
12
+ exports.VERTEX_AI_AUTH_SCOPES = VERTEX_AI_AUTH_SCOPES;
13
+ //# sourceMappingURL=const.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"const.cjs","names":[],"sources":["../src/const.ts"],"sourcesContent":["export const GOOGLE_API_KEY_HEADER = \"x-goog-api-key\";\n\nexport const GCP_API_KEY_HEADER = \"Authorization\";\n\nexport const GENERATIVE_AI_AUTH_SCOPES = [\n \"https://www.googleapis.com/auth/generative-language\",\n];\n\nexport const VERTEX_AI_AUTH_SCOPES = [\n \"https://www.googleapis.com/auth/cloud-platform\",\n];\n"],"mappings":";;AAAA,MAAa,wBAAwB;AAErC,MAAa,qBAAqB;AAElC,MAAa,4BAA4B,CACvC,qDACD;AAED,MAAa,wBAAwB,CACnC,gDACD"}
package/dist/const.js ADDED
@@ -0,0 +1,9 @@
1
+ //#region src/const.ts
2
+ const GOOGLE_API_KEY_HEADER = "x-goog-api-key";
3
+ const GCP_API_KEY_HEADER = "Authorization";
4
+ const GENERATIVE_AI_AUTH_SCOPES = ["https://www.googleapis.com/auth/generative-language"];
5
+ const VERTEX_AI_AUTH_SCOPES = ["https://www.googleapis.com/auth/cloud-platform"];
6
+
7
+ //#endregion
8
+ export { GCP_API_KEY_HEADER, GENERATIVE_AI_AUTH_SCOPES, GOOGLE_API_KEY_HEADER, VERTEX_AI_AUTH_SCOPES };
9
+ //# sourceMappingURL=const.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"const.js","names":[],"sources":["../src/const.ts"],"sourcesContent":["export const GOOGLE_API_KEY_HEADER = \"x-goog-api-key\";\n\nexport const GCP_API_KEY_HEADER = \"Authorization\";\n\nexport const GENERATIVE_AI_AUTH_SCOPES = [\n \"https://www.googleapis.com/auth/generative-language\",\n];\n\nexport const VERTEX_AI_AUTH_SCOPES = [\n \"https://www.googleapis.com/auth/cloud-platform\",\n];\n"],"mappings":";AAAA,MAAa,wBAAwB;AAErC,MAAa,qBAAqB;AAElC,MAAa,4BAA4B,CACvC,qDACD;AAED,MAAa,wBAAwB,CACnC,gDACD"}