@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,188 @@
1
+ const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
2
+ const require_misc = require('./misc.cjs');
3
+ const require_errors = require('./errors.cjs');
4
+ const jose = require_rolldown_runtime.__toESM(require("jose"));
5
+
6
+ //#region src/utils/gcp-auth.ts
7
+ const cache = /* @__PURE__ */ new Map();
8
+ const CACHE_MAX_AGE = 3600;
9
+ /**
10
+ * Normalizes GCP credentials to a frozen GCPCredentials object.
11
+ *
12
+ * This function accepts credentials in either string (JSON) or object format
13
+ * and ensures the returned value is a frozen (immutable) GCPCredentials object.
14
+ * Freezing the credentials prevents accidental modification and ensures
15
+ * consistency throughout the application lifecycle.
16
+ *
17
+ * @param credentials - The GCP service account credentials, either as a JSON string
18
+ * or as a GCPCredentials object
19
+ * @returns A frozen GCPCredentials object that cannot be modified
20
+ *
21
+ * @example
22
+ * ```typescript
23
+ * // From JSON string
24
+ * const creds = normalizeGCPCredentials('{"type":"service_account",...}');
25
+ *
26
+ * // From object
27
+ * const creds = normalizeGCPCredentials({
28
+ * type: "service_account",
29
+ * project_id: "my-project",
30
+ * // ... other fields
31
+ * });
32
+ * ```
33
+ */
34
+ function normalizeGCPCredentials(credentials) {
35
+ return typeof credentials === "string" ? Object.freeze(JSON.parse(credentials)) : Object.isFrozen(credentials) ? credentials : Object.freeze(credentials);
36
+ }
37
+ /**
38
+ * Imports and returns the private key from GCP credentials for JWT signing.
39
+ *
40
+ * This function extracts the RSA private key from the service account credentials
41
+ * and imports it using the PKCS#8 format with the RS256 algorithm. The returned
42
+ * key can be used to sign JWTs for authentication with Google Cloud services.
43
+ *
44
+ * @param credentials - The GCP service account credentials containing the private key
45
+ * @returns A Promise that resolves to the imported private key suitable for JWT signing
46
+ *
47
+ * @throws {Error} If the private key format is invalid or cannot be imported
48
+ *
49
+ * @example
50
+ * ```typescript
51
+ * const credentials = normalizeGCPCredentials(credentialsJson);
52
+ * const privateKey = await getGCPPrivateKey(credentials);
53
+ * // Use privateKey for signing operations
54
+ * ```
55
+ */
56
+ function getGCPPrivateKey(credentials) {
57
+ return (0, jose.importPKCS8)(credentials.private_key, "RS256");
58
+ }
59
+ /**
60
+ * Generates a custom JWT token for authenticating with Google Cloud services.
61
+ *
62
+ * This function creates a signed JWT (JSON Web Token) using the service account's
63
+ * private key. The token includes standard claims such as issuer, audience, subject,
64
+ * issued-at time, and expiration time. This custom token can be exchanged for an
65
+ * access token or ID token through Google's OAuth2 token endpoint.
66
+ *
67
+ * The generated JWT is valid for 1 hour and follows the OAuth 2.0 JWT Bearer
68
+ * Token flow as specified by RFC 7523.
69
+ *
70
+ * @param credentials - The GCP service account credentials used to sign the JWT
71
+ * @returns A Promise that resolves to the signed JWT string
72
+ *
73
+ * @throws {Error} If the private key cannot be imported or the JWT cannot be signed
74
+ *
75
+ * @see https://datatracker.ietf.org/doc/html/rfc7523
76
+ * @see https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials
77
+ *
78
+ * @example
79
+ * ```typescript
80
+ * const credentials = normalizeGCPCredentials(credentialsJson);
81
+ * const customToken = await getGCPCustomToken(credentials);
82
+ * // Use customToken to request an access token
83
+ * ```
84
+ */
85
+ async function getGCPCustomToken(credentials) {
86
+ const privateKey = await getGCPPrivateKey(credentials);
87
+ const customToken = await new jose.SignJWT().setIssuer(credentials.client_email).setAudience(credentials.token_uri).setSubject(credentials.client_email).setProtectedHeader({ alg: "RS256" }).setIssuedAt().setExpirationTime("1h").sign(privateKey);
88
+ return customToken;
89
+ }
90
+ /**
91
+ * Retrieves an access token for authenticating with Google Cloud APIs.
92
+ *
93
+ * - Tokens are cached based on the token URI and private key ID
94
+ * - Cache entries are valid for up to 1 hour
95
+ * - Expired tokens trigger automatic refresh
96
+ * - Multiple concurrent requests for the same token are deduplicated
97
+ *
98
+ * The function handles both access tokens and ID tokens, automatically detecting
99
+ * which type is returned by the token endpoint and extracting the appropriate
100
+ * expiration time.
101
+ *
102
+ * @param credentials - The GCP service account credentials used to request the token
103
+ * @returns A Promise that resolves to the access token string
104
+ *
105
+ * @throws {AuthError} If the token request fails (e.g., invalid credentials,
106
+ * network error, or API error)
107
+ *
108
+ * @see https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials
109
+ * @see https://datatracker.ietf.org/doc/html/rfc7523
110
+ *
111
+ * @example
112
+ * ```typescript
113
+ * const credentials = normalizeGCPCredentials(credentialsJson);
114
+ * const accessToken = await getGCPCredentialsAccessToken(credentials);
115
+ *
116
+ * // Use the access token in API requests
117
+ * const response = await fetch('https://api.google.com/...', {
118
+ * headers: {
119
+ * 'Authorization': `Bearer ${accessToken}`
120
+ * }
121
+ * });
122
+ * ```
123
+ *
124
+ * @remarks
125
+ * The caching mechanism uses a two-level validation:
126
+ * 1. Cache entry age (must be less than CACHE_MAX_AGE)
127
+ * 2. Token expiration time (must not be expired)
128
+ *
129
+ * This ensures that even if a cache entry is fresh, an expired token
130
+ * will trigger a refresh request.
131
+ */
132
+ async function getGCPCredentialsAccessToken(credentials) {
133
+ const tokenUrl = credentials.token_uri;
134
+ const cacheKeyUrl = new URL(tokenUrl);
135
+ cacheKeyUrl.searchParams.set("key", credentials.private_key_id);
136
+ const cacheKey = cacheKeyUrl.toString();
137
+ const cacheValue = cache.get(cacheKey);
138
+ let now = Math.floor(Date.now() / 1e3);
139
+ if (cacheValue) if (cacheValue.created > now - CACHE_MAX_AGE) {
140
+ let token = await cacheValue.promise;
141
+ if (token.expires > now) return token.token;
142
+ else {
143
+ const nextValue = cache.get(cacheKey);
144
+ if (nextValue && nextValue !== cacheValue) {
145
+ token = await nextValue.promise;
146
+ if (token.expires > now) return token.token;
147
+ else cache.delete(cacheKey);
148
+ }
149
+ }
150
+ } else cache.delete(cacheKey);
151
+ const promise = require_misc.iife(async () => {
152
+ now = Math.floor(Date.now() / 1e3);
153
+ const jwt = await getGCPCustomToken(credentials);
154
+ const body = new URLSearchParams();
155
+ body.append("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer");
156
+ body.append("assertion", jwt);
157
+ const res = await fetch(tokenUrl, {
158
+ method: "POST",
159
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
160
+ body
161
+ });
162
+ if (!res.ok) throw await require_errors.AuthError.fromResponse(res);
163
+ const data = await res.json();
164
+ if ("id_token" in data) {
165
+ const claims = (0, jose.decodeJwt)(data.id_token);
166
+ return {
167
+ token: data.id_token,
168
+ expires: claims.exp
169
+ };
170
+ }
171
+ const lastModified = res.headers.get("last-modified");
172
+ const expires = lastModified ? Math.floor(new Date(lastModified).valueOf() / 1e3) + data.expires_in : now + data.expires_in;
173
+ return {
174
+ expires,
175
+ token: data.access_token
176
+ };
177
+ });
178
+ cache.set(cacheKey, {
179
+ created: now,
180
+ promise
181
+ });
182
+ return await promise.then((data) => data.token);
183
+ }
184
+
185
+ //#endregion
186
+ exports.getGCPCredentialsAccessToken = getGCPCredentialsAccessToken;
187
+ exports.normalizeGCPCredentials = normalizeGCPCredentials;
188
+ //# sourceMappingURL=gcp-auth.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gcp-auth.cjs","names":["credentials: string | GCPCredentials","credentials: GCPCredentials","SignJWT","iife","AuthError"],"sources":["../../src/utils/gcp-auth.ts"],"sourcesContent":["/**\n * GCP authentication utilities.\n *\n * Adapted from: https://github.com/kriasoft/web-auth-library\n * Original source: web-auth-library by Kriasoft\n * License: MIT (https://github.com/kriasoft/web-auth-library/blob/main/LICENSE)\n */\n\nimport { decodeJwt, importPKCS8, SignJWT } from \"jose\";\nimport { AuthError } from \"../utils/errors.js\";\nimport { iife } from \"../utils/misc.js\";\n\n/**\n * Google Cloud Platform service account credentials interface.\n *\n * This interface represents the structure of a GCP service account key file,\n * which is used for authenticating with Google Cloud APIs. Service account\n * keys can be downloaded from the Google Cloud Console and contain all the\n * information needed to authenticate as a service account.\n *\n * @see https://cloud.google.com/iam/docs/creating-managing-service-account-keys\n */\nexport interface GCPCredentials {\n /** The type of credential, typically \"service_account\" */\n type: string;\n /** The GCP project ID associated with this service account */\n project_id: string;\n /** The unique identifier for the private key */\n private_key_id: string;\n /** The RSA private key in PEM format used for signing JWTs */\n private_key: string;\n /** The unique client ID for this service account */\n client_id: string;\n /** The email address of the service account */\n client_email: string;\n /** The OAuth2 authorization endpoint URI */\n auth_uri: string;\n /** The OAuth2 token endpoint URI where access tokens are requested */\n token_uri: string;\n /** The URL for the OAuth2 provider's x509 certificate */\n auth_provider_x509_cert_url: string;\n /** The URL for this service account's x509 certificate */\n client_x509_cert_url: string;\n}\n\ninterface CacheValue {\n /** Unix timestamp (in seconds) when this cache entry was created */\n created: number;\n /** Promise that resolves to the token and its expiration time */\n promise: Promise<{ token: string; expires: number }>;\n}\n\nconst cache = new Map<string, CacheValue>();\nconst CACHE_MAX_AGE = 60 * 60; // 1 hour\n\n/**\n * Normalizes GCP credentials to a frozen GCPCredentials object.\n *\n * This function accepts credentials in either string (JSON) or object format\n * and ensures the returned value is a frozen (immutable) GCPCredentials object.\n * Freezing the credentials prevents accidental modification and ensures\n * consistency throughout the application lifecycle.\n *\n * @param credentials - The GCP service account credentials, either as a JSON string\n * or as a GCPCredentials object\n * @returns A frozen GCPCredentials object that cannot be modified\n *\n * @example\n * ```typescript\n * // From JSON string\n * const creds = normalizeGCPCredentials('{\"type\":\"service_account\",...}');\n *\n * // From object\n * const creds = normalizeGCPCredentials({\n * type: \"service_account\",\n * project_id: \"my-project\",\n * // ... other fields\n * });\n * ```\n */\nexport function normalizeGCPCredentials(\n credentials: string | GCPCredentials\n): GCPCredentials {\n return typeof credentials === \"string\"\n ? Object.freeze(JSON.parse(credentials))\n : Object.isFrozen(credentials)\n ? credentials\n : Object.freeze(credentials);\n}\n\n/**\n * Imports and returns the private key from GCP credentials for JWT signing.\n *\n * This function extracts the RSA private key from the service account credentials\n * and imports it using the PKCS#8 format with the RS256 algorithm. The returned\n * key can be used to sign JWTs for authentication with Google Cloud services.\n *\n * @param credentials - The GCP service account credentials containing the private key\n * @returns A Promise that resolves to the imported private key suitable for JWT signing\n *\n * @throws {Error} If the private key format is invalid or cannot be imported\n *\n * @example\n * ```typescript\n * const credentials = normalizeGCPCredentials(credentialsJson);\n * const privateKey = await getGCPPrivateKey(credentials);\n * // Use privateKey for signing operations\n * ```\n */\nexport function getGCPPrivateKey(credentials: GCPCredentials) {\n return importPKCS8(credentials.private_key, \"RS256\");\n}\n\n/**\n * Generates a custom JWT token for authenticating with Google Cloud services.\n *\n * This function creates a signed JWT (JSON Web Token) using the service account's\n * private key. The token includes standard claims such as issuer, audience, subject,\n * issued-at time, and expiration time. This custom token can be exchanged for an\n * access token or ID token through Google's OAuth2 token endpoint.\n *\n * The generated JWT is valid for 1 hour and follows the OAuth 2.0 JWT Bearer\n * Token flow as specified by RFC 7523.\n *\n * @param credentials - The GCP service account credentials used to sign the JWT\n * @returns A Promise that resolves to the signed JWT string\n *\n * @throws {Error} If the private key cannot be imported or the JWT cannot be signed\n *\n * @see https://datatracker.ietf.org/doc/html/rfc7523\n * @see https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials\n *\n * @example\n * ```typescript\n * const credentials = normalizeGCPCredentials(credentialsJson);\n * const customToken = await getGCPCustomToken(credentials);\n * // Use customToken to request an access token\n * ```\n */\nexport async function getGCPCustomToken(credentials: GCPCredentials) {\n const privateKey = await getGCPPrivateKey(credentials);\n const customToken = await new SignJWT()\n .setIssuer(credentials.client_email)\n .setAudience(credentials.token_uri)\n .setSubject(credentials.client_email)\n .setProtectedHeader({ alg: \"RS256\" })\n .setIssuedAt()\n .setExpirationTime(\"1h\")\n .sign(privateKey);\n return customToken;\n}\n\n/**\n * Retrieves an access token for authenticating with Google Cloud APIs.\n *\n * - Tokens are cached based on the token URI and private key ID\n * - Cache entries are valid for up to 1 hour\n * - Expired tokens trigger automatic refresh\n * - Multiple concurrent requests for the same token are deduplicated\n *\n * The function handles both access tokens and ID tokens, automatically detecting\n * which type is returned by the token endpoint and extracting the appropriate\n * expiration time.\n *\n * @param credentials - The GCP service account credentials used to request the token\n * @returns A Promise that resolves to the access token string\n *\n * @throws {AuthError} If the token request fails (e.g., invalid credentials,\n * network error, or API error)\n *\n * @see https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials\n * @see https://datatracker.ietf.org/doc/html/rfc7523\n *\n * @example\n * ```typescript\n * const credentials = normalizeGCPCredentials(credentialsJson);\n * const accessToken = await getGCPCredentialsAccessToken(credentials);\n *\n * // Use the access token in API requests\n * const response = await fetch('https://api.google.com/...', {\n * headers: {\n * 'Authorization': `Bearer ${accessToken}`\n * }\n * });\n * ```\n *\n * @remarks\n * The caching mechanism uses a two-level validation:\n * 1. Cache entry age (must be less than CACHE_MAX_AGE)\n * 2. Token expiration time (must not be expired)\n *\n * This ensures that even if a cache entry is fresh, an expired token\n * will trigger a refresh request.\n */\nexport async function getGCPCredentialsAccessToken(\n credentials: GCPCredentials\n): Promise<string> {\n const tokenUrl = credentials.token_uri;\n\n const cacheKeyUrl = new URL(tokenUrl);\n cacheKeyUrl.searchParams.set(\"key\", credentials.private_key_id);\n const cacheKey = cacheKeyUrl.toString();\n\n // Attempt to retrieve the token from the cache\n const cacheValue = cache.get(cacheKey);\n let now = Math.floor(Date.now() / 1000);\n\n if (cacheValue) {\n if (cacheValue.created > now - CACHE_MAX_AGE) {\n let token = await cacheValue.promise;\n\n if (token.expires > now) {\n return token.token;\n } else {\n const nextValue = cache.get(cacheKey);\n\n if (nextValue && nextValue !== cacheValue) {\n token = await nextValue.promise;\n if (token.expires > now) {\n return token.token;\n } else {\n cache.delete(cacheKey);\n }\n }\n }\n } else {\n cache.delete(cacheKey);\n }\n }\n\n const promise = iife(async () => {\n now = Math.floor(Date.now() / 1000);\n\n // Request a new token from the Google Cloud API\n const jwt = await getGCPCustomToken(credentials);\n const body = new URLSearchParams();\n body.append(\"grant_type\", \"urn:ietf:params:oauth:grant-type:jwt-bearer\");\n body.append(\"assertion\", jwt);\n const res = await fetch(tokenUrl, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body,\n });\n\n if (!res.ok) {\n throw await AuthError.fromResponse(res);\n }\n\n const data = await res.json();\n\n if (\"id_token\" in data) {\n const claims = decodeJwt(data.id_token);\n return { token: data.id_token, expires: claims.exp as number };\n }\n\n const lastModified = res.headers.get(\"last-modified\");\n const expires = lastModified\n ? Math.floor(new Date(lastModified).valueOf() / 1000) + data.expires_in\n : now + data.expires_in;\n\n return { expires, token: data.access_token };\n });\n\n cache.set(cacheKey, { created: now, promise });\n return await promise.then((data) => data.token);\n}\n"],"mappings":";;;;;;AAoDA,MAAM,wBAAQ,IAAI;AAClB,MAAM,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BtB,SAAgB,wBACdA,aACgB;AAChB,QAAO,OAAO,gBAAgB,WAC1B,OAAO,OAAO,KAAK,MAAM,YAAY,CAAC,GACtC,OAAO,SAAS,YAAY,GAC5B,cACA,OAAO,OAAO,YAAY;AAC/B;;;;;;;;;;;;;;;;;;;;AAqBD,SAAgB,iBAAiBC,aAA6B;AAC5D,8BAAmB,YAAY,aAAa,QAAQ;AACrD;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BD,eAAsB,kBAAkBA,aAA6B;CACnE,MAAM,aAAa,MAAM,iBAAiB,YAAY;CACtD,MAAM,cAAc,MAAM,IAAIC,eAC3B,UAAU,YAAY,aAAa,CACnC,YAAY,YAAY,UAAU,CAClC,WAAW,YAAY,aAAa,CACpC,mBAAmB,EAAE,KAAK,QAAS,EAAC,CACpC,aAAa,CACb,kBAAkB,KAAK,CACvB,KAAK,WAAW;AACnB,QAAO;AACR;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CD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,MAAM,KAAK;AAEf,SAAO;GAAE;GAAS,OAAO,KAAK;EAAc;CAC7C,EAAC;CAEF,MAAM,IAAI,UAAU;EAAE,SAAS;EAAK;CAAS,EAAC;AAC9C,QAAO,MAAM,QAAQ,KAAK,CAAC,SAAS,KAAK,MAAM;AAChD"}
@@ -0,0 +1,43 @@
1
+ //#region src/utils/gcp-auth.d.ts
2
+ /**
3
+ * GCP authentication utilities.
4
+ *
5
+ * Adapted from: https://github.com/kriasoft/web-auth-library
6
+ * Original source: web-auth-library by Kriasoft
7
+ * License: MIT (https://github.com/kriasoft/web-auth-library/blob/main/LICENSE)
8
+ */
9
+ /**
10
+ * Google Cloud Platform service account credentials interface.
11
+ *
12
+ * This interface represents the structure of a GCP service account key file,
13
+ * which is used for authenticating with Google Cloud APIs. Service account
14
+ * keys can be downloaded from the Google Cloud Console and contain all the
15
+ * information needed to authenticate as a service account.
16
+ *
17
+ * @see https://cloud.google.com/iam/docs/creating-managing-service-account-keys
18
+ */
19
+ interface GCPCredentials {
20
+ /** The type of credential, typically "service_account" */
21
+ type: string;
22
+ /** The GCP project ID associated with this service account */
23
+ project_id: string;
24
+ /** The unique identifier for the private key */
25
+ private_key_id: string;
26
+ /** The RSA private key in PEM format used for signing JWTs */
27
+ private_key: string;
28
+ /** The unique client ID for this service account */
29
+ client_id: string;
30
+ /** The email address of the service account */
31
+ client_email: string;
32
+ /** The OAuth2 authorization endpoint URI */
33
+ auth_uri: string;
34
+ /** The OAuth2 token endpoint URI where access tokens are requested */
35
+ token_uri: string;
36
+ /** The URL for the OAuth2 provider's x509 certificate */
37
+ auth_provider_x509_cert_url: string;
38
+ /** The URL for this service account's x509 certificate */
39
+ client_x509_cert_url: string;
40
+ }
41
+ //#endregion
42
+ export { GCPCredentials };
43
+ //# sourceMappingURL=gcp-auth.d.cts.map
@@ -0,0 +1,43 @@
1
+ //#region src/utils/gcp-auth.d.ts
2
+ /**
3
+ * GCP authentication utilities.
4
+ *
5
+ * Adapted from: https://github.com/kriasoft/web-auth-library
6
+ * Original source: web-auth-library by Kriasoft
7
+ * License: MIT (https://github.com/kriasoft/web-auth-library/blob/main/LICENSE)
8
+ */
9
+ /**
10
+ * Google Cloud Platform service account credentials interface.
11
+ *
12
+ * This interface represents the structure of a GCP service account key file,
13
+ * which is used for authenticating with Google Cloud APIs. Service account
14
+ * keys can be downloaded from the Google Cloud Console and contain all the
15
+ * information needed to authenticate as a service account.
16
+ *
17
+ * @see https://cloud.google.com/iam/docs/creating-managing-service-account-keys
18
+ */
19
+ interface GCPCredentials {
20
+ /** The type of credential, typically "service_account" */
21
+ type: string;
22
+ /** The GCP project ID associated with this service account */
23
+ project_id: string;
24
+ /** The unique identifier for the private key */
25
+ private_key_id: string;
26
+ /** The RSA private key in PEM format used for signing JWTs */
27
+ private_key: string;
28
+ /** The unique client ID for this service account */
29
+ client_id: string;
30
+ /** The email address of the service account */
31
+ client_email: string;
32
+ /** The OAuth2 authorization endpoint URI */
33
+ auth_uri: string;
34
+ /** The OAuth2 token endpoint URI where access tokens are requested */
35
+ token_uri: string;
36
+ /** The URL for the OAuth2 provider's x509 certificate */
37
+ auth_provider_x509_cert_url: string;
38
+ /** The URL for this service account's x509 certificate */
39
+ client_x509_cert_url: string;
40
+ }
41
+ //#endregion
42
+ export { GCPCredentials };
43
+ //# sourceMappingURL=gcp-auth.d.ts.map
@@ -0,0 +1,186 @@
1
+ import { iife } from "./misc.js";
2
+ import { AuthError } from "./errors.js";
3
+ import { SignJWT, decodeJwt, importPKCS8 } from "jose";
4
+
5
+ //#region src/utils/gcp-auth.ts
6
+ const cache = /* @__PURE__ */ new Map();
7
+ const CACHE_MAX_AGE = 3600;
8
+ /**
9
+ * Normalizes GCP credentials to a frozen GCPCredentials object.
10
+ *
11
+ * This function accepts credentials in either string (JSON) or object format
12
+ * and ensures the returned value is a frozen (immutable) GCPCredentials object.
13
+ * Freezing the credentials prevents accidental modification and ensures
14
+ * consistency throughout the application lifecycle.
15
+ *
16
+ * @param credentials - The GCP service account credentials, either as a JSON string
17
+ * or as a GCPCredentials object
18
+ * @returns A frozen GCPCredentials object that cannot be modified
19
+ *
20
+ * @example
21
+ * ```typescript
22
+ * // From JSON string
23
+ * const creds = normalizeGCPCredentials('{"type":"service_account",...}');
24
+ *
25
+ * // From object
26
+ * const creds = normalizeGCPCredentials({
27
+ * type: "service_account",
28
+ * project_id: "my-project",
29
+ * // ... other fields
30
+ * });
31
+ * ```
32
+ */
33
+ function normalizeGCPCredentials(credentials) {
34
+ return typeof credentials === "string" ? Object.freeze(JSON.parse(credentials)) : Object.isFrozen(credentials) ? credentials : Object.freeze(credentials);
35
+ }
36
+ /**
37
+ * Imports and returns the private key from GCP credentials for JWT signing.
38
+ *
39
+ * This function extracts the RSA private key from the service account credentials
40
+ * and imports it using the PKCS#8 format with the RS256 algorithm. The returned
41
+ * key can be used to sign JWTs for authentication with Google Cloud services.
42
+ *
43
+ * @param credentials - The GCP service account credentials containing the private key
44
+ * @returns A Promise that resolves to the imported private key suitable for JWT signing
45
+ *
46
+ * @throws {Error} If the private key format is invalid or cannot be imported
47
+ *
48
+ * @example
49
+ * ```typescript
50
+ * const credentials = normalizeGCPCredentials(credentialsJson);
51
+ * const privateKey = await getGCPPrivateKey(credentials);
52
+ * // Use privateKey for signing operations
53
+ * ```
54
+ */
55
+ function getGCPPrivateKey(credentials) {
56
+ return importPKCS8(credentials.private_key, "RS256");
57
+ }
58
+ /**
59
+ * Generates a custom JWT token for authenticating with Google Cloud services.
60
+ *
61
+ * This function creates a signed JWT (JSON Web Token) using the service account's
62
+ * private key. The token includes standard claims such as issuer, audience, subject,
63
+ * issued-at time, and expiration time. This custom token can be exchanged for an
64
+ * access token or ID token through Google's OAuth2 token endpoint.
65
+ *
66
+ * The generated JWT is valid for 1 hour and follows the OAuth 2.0 JWT Bearer
67
+ * Token flow as specified by RFC 7523.
68
+ *
69
+ * @param credentials - The GCP service account credentials used to sign the JWT
70
+ * @returns A Promise that resolves to the signed JWT string
71
+ *
72
+ * @throws {Error} If the private key cannot be imported or the JWT cannot be signed
73
+ *
74
+ * @see https://datatracker.ietf.org/doc/html/rfc7523
75
+ * @see https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials
76
+ *
77
+ * @example
78
+ * ```typescript
79
+ * const credentials = normalizeGCPCredentials(credentialsJson);
80
+ * const customToken = await getGCPCustomToken(credentials);
81
+ * // Use customToken to request an access token
82
+ * ```
83
+ */
84
+ async function getGCPCustomToken(credentials) {
85
+ const privateKey = await getGCPPrivateKey(credentials);
86
+ const customToken = await new SignJWT().setIssuer(credentials.client_email).setAudience(credentials.token_uri).setSubject(credentials.client_email).setProtectedHeader({ alg: "RS256" }).setIssuedAt().setExpirationTime("1h").sign(privateKey);
87
+ return customToken;
88
+ }
89
+ /**
90
+ * Retrieves an access token for authenticating with Google Cloud APIs.
91
+ *
92
+ * - Tokens are cached based on the token URI and private key ID
93
+ * - Cache entries are valid for up to 1 hour
94
+ * - Expired tokens trigger automatic refresh
95
+ * - Multiple concurrent requests for the same token are deduplicated
96
+ *
97
+ * The function handles both access tokens and ID tokens, automatically detecting
98
+ * which type is returned by the token endpoint and extracting the appropriate
99
+ * expiration time.
100
+ *
101
+ * @param credentials - The GCP service account credentials used to request the token
102
+ * @returns A Promise that resolves to the access token string
103
+ *
104
+ * @throws {AuthError} If the token request fails (e.g., invalid credentials,
105
+ * network error, or API error)
106
+ *
107
+ * @see https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials
108
+ * @see https://datatracker.ietf.org/doc/html/rfc7523
109
+ *
110
+ * @example
111
+ * ```typescript
112
+ * const credentials = normalizeGCPCredentials(credentialsJson);
113
+ * const accessToken = await getGCPCredentialsAccessToken(credentials);
114
+ *
115
+ * // Use the access token in API requests
116
+ * const response = await fetch('https://api.google.com/...', {
117
+ * headers: {
118
+ * 'Authorization': `Bearer ${accessToken}`
119
+ * }
120
+ * });
121
+ * ```
122
+ *
123
+ * @remarks
124
+ * The caching mechanism uses a two-level validation:
125
+ * 1. Cache entry age (must be less than CACHE_MAX_AGE)
126
+ * 2. Token expiration time (must not be expired)
127
+ *
128
+ * This ensures that even if a cache entry is fresh, an expired token
129
+ * will trigger a refresh request.
130
+ */
131
+ async function getGCPCredentialsAccessToken(credentials) {
132
+ const tokenUrl = credentials.token_uri;
133
+ const cacheKeyUrl = new URL(tokenUrl);
134
+ cacheKeyUrl.searchParams.set("key", credentials.private_key_id);
135
+ const cacheKey = cacheKeyUrl.toString();
136
+ const cacheValue = cache.get(cacheKey);
137
+ let now = Math.floor(Date.now() / 1e3);
138
+ if (cacheValue) if (cacheValue.created > now - CACHE_MAX_AGE) {
139
+ let token = await cacheValue.promise;
140
+ if (token.expires > now) return token.token;
141
+ else {
142
+ const nextValue = cache.get(cacheKey);
143
+ if (nextValue && nextValue !== cacheValue) {
144
+ token = await nextValue.promise;
145
+ if (token.expires > now) return token.token;
146
+ else cache.delete(cacheKey);
147
+ }
148
+ }
149
+ } else cache.delete(cacheKey);
150
+ const promise = iife(async () => {
151
+ now = Math.floor(Date.now() / 1e3);
152
+ const jwt = await getGCPCustomToken(credentials);
153
+ const body = new URLSearchParams();
154
+ body.append("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer");
155
+ body.append("assertion", jwt);
156
+ const res = await fetch(tokenUrl, {
157
+ method: "POST",
158
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
159
+ body
160
+ });
161
+ if (!res.ok) throw await AuthError.fromResponse(res);
162
+ const data = await res.json();
163
+ if ("id_token" in data) {
164
+ const claims = decodeJwt(data.id_token);
165
+ return {
166
+ token: data.id_token,
167
+ expires: claims.exp
168
+ };
169
+ }
170
+ const lastModified = res.headers.get("last-modified");
171
+ const expires = lastModified ? Math.floor(new Date(lastModified).valueOf() / 1e3) + data.expires_in : now + data.expires_in;
172
+ return {
173
+ expires,
174
+ token: data.access_token
175
+ };
176
+ });
177
+ cache.set(cacheKey, {
178
+ created: now,
179
+ promise
180
+ });
181
+ return await promise.then((data) => data.token);
182
+ }
183
+
184
+ //#endregion
185
+ export { getGCPCredentialsAccessToken, normalizeGCPCredentials };
186
+ //# sourceMappingURL=gcp-auth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gcp-auth.js","names":["credentials: string | GCPCredentials","credentials: GCPCredentials"],"sources":["../../src/utils/gcp-auth.ts"],"sourcesContent":["/**\n * GCP authentication utilities.\n *\n * Adapted from: https://github.com/kriasoft/web-auth-library\n * Original source: web-auth-library by Kriasoft\n * License: MIT (https://github.com/kriasoft/web-auth-library/blob/main/LICENSE)\n */\n\nimport { decodeJwt, importPKCS8, SignJWT } from \"jose\";\nimport { AuthError } from \"../utils/errors.js\";\nimport { iife } from \"../utils/misc.js\";\n\n/**\n * Google Cloud Platform service account credentials interface.\n *\n * This interface represents the structure of a GCP service account key file,\n * which is used for authenticating with Google Cloud APIs. Service account\n * keys can be downloaded from the Google Cloud Console and contain all the\n * information needed to authenticate as a service account.\n *\n * @see https://cloud.google.com/iam/docs/creating-managing-service-account-keys\n */\nexport interface GCPCredentials {\n /** The type of credential, typically \"service_account\" */\n type: string;\n /** The GCP project ID associated with this service account */\n project_id: string;\n /** The unique identifier for the private key */\n private_key_id: string;\n /** The RSA private key in PEM format used for signing JWTs */\n private_key: string;\n /** The unique client ID for this service account */\n client_id: string;\n /** The email address of the service account */\n client_email: string;\n /** The OAuth2 authorization endpoint URI */\n auth_uri: string;\n /** The OAuth2 token endpoint URI where access tokens are requested */\n token_uri: string;\n /** The URL for the OAuth2 provider's x509 certificate */\n auth_provider_x509_cert_url: string;\n /** The URL for this service account's x509 certificate */\n client_x509_cert_url: string;\n}\n\ninterface CacheValue {\n /** Unix timestamp (in seconds) when this cache entry was created */\n created: number;\n /** Promise that resolves to the token and its expiration time */\n promise: Promise<{ token: string; expires: number }>;\n}\n\nconst cache = new Map<string, CacheValue>();\nconst CACHE_MAX_AGE = 60 * 60; // 1 hour\n\n/**\n * Normalizes GCP credentials to a frozen GCPCredentials object.\n *\n * This function accepts credentials in either string (JSON) or object format\n * and ensures the returned value is a frozen (immutable) GCPCredentials object.\n * Freezing the credentials prevents accidental modification and ensures\n * consistency throughout the application lifecycle.\n *\n * @param credentials - The GCP service account credentials, either as a JSON string\n * or as a GCPCredentials object\n * @returns A frozen GCPCredentials object that cannot be modified\n *\n * @example\n * ```typescript\n * // From JSON string\n * const creds = normalizeGCPCredentials('{\"type\":\"service_account\",...}');\n *\n * // From object\n * const creds = normalizeGCPCredentials({\n * type: \"service_account\",\n * project_id: \"my-project\",\n * // ... other fields\n * });\n * ```\n */\nexport function normalizeGCPCredentials(\n credentials: string | GCPCredentials\n): GCPCredentials {\n return typeof credentials === \"string\"\n ? Object.freeze(JSON.parse(credentials))\n : Object.isFrozen(credentials)\n ? credentials\n : Object.freeze(credentials);\n}\n\n/**\n * Imports and returns the private key from GCP credentials for JWT signing.\n *\n * This function extracts the RSA private key from the service account credentials\n * and imports it using the PKCS#8 format with the RS256 algorithm. The returned\n * key can be used to sign JWTs for authentication with Google Cloud services.\n *\n * @param credentials - The GCP service account credentials containing the private key\n * @returns A Promise that resolves to the imported private key suitable for JWT signing\n *\n * @throws {Error} If the private key format is invalid or cannot be imported\n *\n * @example\n * ```typescript\n * const credentials = normalizeGCPCredentials(credentialsJson);\n * const privateKey = await getGCPPrivateKey(credentials);\n * // Use privateKey for signing operations\n * ```\n */\nexport function getGCPPrivateKey(credentials: GCPCredentials) {\n return importPKCS8(credentials.private_key, \"RS256\");\n}\n\n/**\n * Generates a custom JWT token for authenticating with Google Cloud services.\n *\n * This function creates a signed JWT (JSON Web Token) using the service account's\n * private key. The token includes standard claims such as issuer, audience, subject,\n * issued-at time, and expiration time. This custom token can be exchanged for an\n * access token or ID token through Google's OAuth2 token endpoint.\n *\n * The generated JWT is valid for 1 hour and follows the OAuth 2.0 JWT Bearer\n * Token flow as specified by RFC 7523.\n *\n * @param credentials - The GCP service account credentials used to sign the JWT\n * @returns A Promise that resolves to the signed JWT string\n *\n * @throws {Error} If the private key cannot be imported or the JWT cannot be signed\n *\n * @see https://datatracker.ietf.org/doc/html/rfc7523\n * @see https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials\n *\n * @example\n * ```typescript\n * const credentials = normalizeGCPCredentials(credentialsJson);\n * const customToken = await getGCPCustomToken(credentials);\n * // Use customToken to request an access token\n * ```\n */\nexport async function getGCPCustomToken(credentials: GCPCredentials) {\n const privateKey = await getGCPPrivateKey(credentials);\n const customToken = await new SignJWT()\n .setIssuer(credentials.client_email)\n .setAudience(credentials.token_uri)\n .setSubject(credentials.client_email)\n .setProtectedHeader({ alg: \"RS256\" })\n .setIssuedAt()\n .setExpirationTime(\"1h\")\n .sign(privateKey);\n return customToken;\n}\n\n/**\n * Retrieves an access token for authenticating with Google Cloud APIs.\n *\n * - Tokens are cached based on the token URI and private key ID\n * - Cache entries are valid for up to 1 hour\n * - Expired tokens trigger automatic refresh\n * - Multiple concurrent requests for the same token are deduplicated\n *\n * The function handles both access tokens and ID tokens, automatically detecting\n * which type is returned by the token endpoint and extracting the appropriate\n * expiration time.\n *\n * @param credentials - The GCP service account credentials used to request the token\n * @returns A Promise that resolves to the access token string\n *\n * @throws {AuthError} If the token request fails (e.g., invalid credentials,\n * network error, or API error)\n *\n * @see https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials\n * @see https://datatracker.ietf.org/doc/html/rfc7523\n *\n * @example\n * ```typescript\n * const credentials = normalizeGCPCredentials(credentialsJson);\n * const accessToken = await getGCPCredentialsAccessToken(credentials);\n *\n * // Use the access token in API requests\n * const response = await fetch('https://api.google.com/...', {\n * headers: {\n * 'Authorization': `Bearer ${accessToken}`\n * }\n * });\n * ```\n *\n * @remarks\n * The caching mechanism uses a two-level validation:\n * 1. Cache entry age (must be less than CACHE_MAX_AGE)\n * 2. Token expiration time (must not be expired)\n *\n * This ensures that even if a cache entry is fresh, an expired token\n * will trigger a refresh request.\n */\nexport async function getGCPCredentialsAccessToken(\n credentials: GCPCredentials\n): Promise<string> {\n const tokenUrl = credentials.token_uri;\n\n const cacheKeyUrl = new URL(tokenUrl);\n cacheKeyUrl.searchParams.set(\"key\", credentials.private_key_id);\n const cacheKey = cacheKeyUrl.toString();\n\n // Attempt to retrieve the token from the cache\n const cacheValue = cache.get(cacheKey);\n let now = Math.floor(Date.now() / 1000);\n\n if (cacheValue) {\n if (cacheValue.created > now - CACHE_MAX_AGE) {\n let token = await cacheValue.promise;\n\n if (token.expires > now) {\n return token.token;\n } else {\n const nextValue = cache.get(cacheKey);\n\n if (nextValue && nextValue !== cacheValue) {\n token = await nextValue.promise;\n if (token.expires > now) {\n return token.token;\n } else {\n cache.delete(cacheKey);\n }\n }\n }\n } else {\n cache.delete(cacheKey);\n }\n }\n\n const promise = iife(async () => {\n now = Math.floor(Date.now() / 1000);\n\n // Request a new token from the Google Cloud API\n const jwt = await getGCPCustomToken(credentials);\n const body = new URLSearchParams();\n body.append(\"grant_type\", \"urn:ietf:params:oauth:grant-type:jwt-bearer\");\n body.append(\"assertion\", jwt);\n const res = await fetch(tokenUrl, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body,\n });\n\n if (!res.ok) {\n throw await AuthError.fromResponse(res);\n }\n\n const data = await res.json();\n\n if (\"id_token\" in data) {\n const claims = decodeJwt(data.id_token);\n return { token: data.id_token, expires: claims.exp as number };\n }\n\n const lastModified = res.headers.get(\"last-modified\");\n const expires = lastModified\n ? Math.floor(new Date(lastModified).valueOf() / 1000) + data.expires_in\n : now + data.expires_in;\n\n return { expires, token: data.access_token };\n });\n\n cache.set(cacheKey, { created: now, promise });\n return await promise.then((data) => data.token);\n}\n"],"mappings":";;;;;AAoDA,MAAM,wBAAQ,IAAI;AAClB,MAAM,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BtB,SAAgB,wBACdA,aACgB;AAChB,QAAO,OAAO,gBAAgB,WAC1B,OAAO,OAAO,KAAK,MAAM,YAAY,CAAC,GACtC,OAAO,SAAS,YAAY,GAC5B,cACA,OAAO,OAAO,YAAY;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AO,aAAa,IAAI;EAC7B,MAAM,MAAM,MAAM,MAAM,UAAU;GAChC,QAAQ;GACR,SAAS,EAAE,gBAAgB,oCAAqC;GAChE;EACD,EAAC;AAEF,MAAI,CAAC,IAAI,GACP,OAAM,MAAM,UAAU,aAAa,IAAI;EAGzC,MAAM,OAAO,MAAM,IAAI,MAAM;AAE7B,MAAI,cAAc,MAAM;GACtB,MAAM,SAAS,UAAU,KAAK,SAAS;AACvC,UAAO;IAAE,OAAO,KAAK;IAAU,SAAS,OAAO;GAAe;EAC/D;EAED,MAAM,eAAe,IAAI,QAAQ,IAAI,gBAAgB;EACrD,MAAM,UAAU,eACZ,KAAK,MAAM,IAAI,KAAK,cAAc,SAAS,GAAG,IAAK,GAAG,KAAK,aAC3D,MAAM,KAAK;AAEf,SAAO;GAAE;GAAS,OAAO,KAAK;EAAc;CAC7C,EAAC;CAEF,MAAM,IAAI,UAAU;EAAE,SAAS;EAAK;CAAS,EAAC;AAC9C,QAAO,MAAM,QAAQ,KAAK,CAAC,SAAS,KAAK,MAAM;AAChD"}
@@ -0,0 +1,67 @@
1
+ const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
2
+ const __langchain_core_callbacks_base = require_rolldown_runtime.__toESM(require("@langchain/core/callbacks/base"));
3
+
4
+ //#region src/utils/handler.ts
5
+ var GoogleRequestCallbackHandler = class extends __langchain_core_callbacks_base.BaseCallbackHandler {
6
+ customEventInfo(eventName) {
7
+ const names = eventName.split("-");
8
+ return {
9
+ subEvent: names[1],
10
+ module: names[2]
11
+ };
12
+ }
13
+ handleCustomEvent(eventName, data, runId, tags, metadata) {
14
+ if (!eventName) return void 0;
15
+ const eventInfo = this.customEventInfo(eventName);
16
+ switch (eventInfo.subEvent) {
17
+ case "request": return this.handleCustomRequestEvent(eventName, eventInfo, data, runId, tags, metadata);
18
+ case "response": return this.handleCustomResponseEvent(eventName, eventInfo, data, runId, tags, metadata);
19
+ case "chunk": return this.handleCustomChunkEvent(eventName, eventInfo, data, runId, tags, metadata);
20
+ default: console.error(`Unexpected eventInfo for ${eventName} ${JSON.stringify(eventInfo, null, 1)}`);
21
+ }
22
+ }
23
+ };
24
+ var GoogleRequestLogger = class extends GoogleRequestCallbackHandler {
25
+ name = "GoogleRequestLogger";
26
+ shortenStringLength = 40;
27
+ log(eventName, data, tags) {
28
+ const splitLen = this.shortenStringLength;
29
+ const half = splitLen / 2;
30
+ const replacer = (_key, value) => {
31
+ if (typeof value === "string" && splitLen > 0 && value.length > splitLen) return `${value.substring(0, half)}...${value.substring(value.length - half)}`;
32
+ return value;
33
+ };
34
+ const tagStr = tags ? `[${tags}]` : "[]";
35
+ console.log(`${eventName} ${tagStr} ${JSON.stringify(data, replacer, 1)}`);
36
+ }
37
+ handleCustomRequestEvent(eventName, _eventInfo, data, _runId, tags, _metadata) {
38
+ this.log(eventName, data, tags);
39
+ }
40
+ handleCustomResponseEvent(eventName, _eventInfo, data, _runId, tags, _metadata) {
41
+ this.log(eventName, data, tags);
42
+ }
43
+ handleCustomChunkEvent(eventName, _eventInfo, data, _runId, tags, _metadata) {
44
+ this.log(eventName, data, tags);
45
+ }
46
+ };
47
+ var GoogleRequestRecorder = class extends GoogleRequestCallbackHandler {
48
+ name = "GoogleRequestRecorder";
49
+ request = {};
50
+ response = {};
51
+ chunk = [];
52
+ handleCustomRequestEvent(_eventName, _eventInfo, data, _runId, _tags, _metadata) {
53
+ this.request = data;
54
+ }
55
+ handleCustomResponseEvent(_eventName, _eventInfo, data, _runId, _tags, _metadata) {
56
+ this.response = data;
57
+ }
58
+ handleCustomChunkEvent(_eventName, _eventInfo, data, _runId, _tags, _metadata) {
59
+ this.chunk.push(data);
60
+ }
61
+ };
62
+
63
+ //#endregion
64
+ exports.GoogleRequestCallbackHandler = GoogleRequestCallbackHandler;
65
+ exports.GoogleRequestLogger = GoogleRequestLogger;
66
+ exports.GoogleRequestRecorder = GoogleRequestRecorder;
67
+ //# sourceMappingURL=handler.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handler.cjs","names":["BaseCallbackHandler","eventName: string","data: any","runId: string","tags?: string[]","metadata?: Record<string, any>","_key: string","value: any","_eventInfo: GoogleCustomEventInfo","_runId: string","_metadata?: Record<string, any>","_eventName: string","_tags?: string[]"],"sources":["../../src/utils/handler.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { BaseCallbackHandler } from \"@langchain/core/callbacks/base\";\n\nexport interface GoogleCustomEventInfo {\n subEvent: string;\n module: string;\n}\n\nexport abstract class GoogleRequestCallbackHandler extends BaseCallbackHandler {\n customEventInfo(eventName: string): GoogleCustomEventInfo {\n const names = eventName.split(\"-\");\n return {\n subEvent: names[1],\n module: names[2],\n };\n }\n\n abstract handleCustomRequestEvent(\n eventName: string,\n eventInfo: GoogleCustomEventInfo,\n data: any,\n runId: string,\n tags?: string[],\n metadata?: Record<string, any>\n ): any;\n\n abstract handleCustomResponseEvent(\n eventName: string,\n eventInfo: GoogleCustomEventInfo,\n data: any,\n runId: string,\n tags?: string[],\n metadata?: Record<string, any>\n ): any;\n\n abstract handleCustomChunkEvent(\n eventName: string,\n eventInfo: GoogleCustomEventInfo,\n data: any,\n runId: string,\n tags?: string[],\n metadata?: Record<string, any>\n ): any;\n\n handleCustomEvent(\n eventName: string,\n data: any,\n runId: string,\n tags?: string[],\n metadata?: Record<string, any>\n ): any {\n if (!eventName) {\n return undefined;\n }\n const eventInfo = this.customEventInfo(eventName);\n switch (eventInfo.subEvent) {\n case \"request\":\n return this.handleCustomRequestEvent(\n eventName,\n eventInfo,\n data,\n runId,\n tags,\n metadata\n );\n case \"response\":\n return this.handleCustomResponseEvent(\n eventName,\n eventInfo,\n data,\n runId,\n tags,\n metadata\n );\n case \"chunk\":\n return this.handleCustomChunkEvent(\n eventName,\n eventInfo,\n data,\n runId,\n tags,\n metadata\n );\n default:\n console.error(\n `Unexpected eventInfo for ${eventName} ${JSON.stringify(\n eventInfo,\n null,\n 1\n )}`\n );\n }\n }\n}\n\nexport class GoogleRequestLogger extends GoogleRequestCallbackHandler {\n name: string = \"GoogleRequestLogger\";\n\n shortenStringLength = 40;\n\n log(eventName: string, data: any, tags?: string[]): undefined {\n const splitLen = this.shortenStringLength;\n const half = splitLen / 2;\n const replacer = (_key: string, value: any) => {\n if (\n typeof value === \"string\" &&\n splitLen > 0 &&\n value.length > splitLen\n ) {\n return `${value.substring(0, half)}...${value.substring(\n value.length - half\n )}`;\n }\n return value;\n };\n const tagStr = tags ? `[${tags}]` : \"[]\";\n console.log(`${eventName} ${tagStr} ${JSON.stringify(data, replacer, 1)}`);\n }\n\n handleCustomRequestEvent(\n eventName: string,\n _eventInfo: GoogleCustomEventInfo,\n data: any,\n _runId: string,\n tags?: string[],\n _metadata?: Record<string, any>\n ): any {\n this.log(eventName, data, tags);\n }\n\n handleCustomResponseEvent(\n eventName: string,\n _eventInfo: GoogleCustomEventInfo,\n data: any,\n _runId: string,\n tags?: string[],\n _metadata?: Record<string, any>\n ): any {\n this.log(eventName, data, tags);\n }\n\n handleCustomChunkEvent(\n eventName: string,\n _eventInfo: GoogleCustomEventInfo,\n data: any,\n _runId: string,\n tags?: string[],\n _metadata?: Record<string, any>\n ): any {\n this.log(eventName, data, tags);\n }\n}\n\nexport class GoogleRequestRecorder extends GoogleRequestCallbackHandler {\n name = \"GoogleRequestRecorder\";\n\n request: any = {};\n\n response: any = {};\n\n chunk: any[] = [];\n\n handleCustomRequestEvent(\n _eventName: string,\n _eventInfo: GoogleCustomEventInfo,\n data: any,\n _runId: string,\n _tags?: string[],\n _metadata?: Record<string, any>\n ): any {\n this.request = data;\n }\n\n handleCustomResponseEvent(\n _eventName: string,\n _eventInfo: GoogleCustomEventInfo,\n data: any,\n _runId: string,\n _tags?: string[],\n _metadata?: Record<string, any>\n ): any {\n this.response = data;\n }\n\n handleCustomChunkEvent(\n _eventName: string,\n _eventInfo: GoogleCustomEventInfo,\n data: any,\n _runId: string,\n _tags?: string[],\n _metadata?: Record<string, any>\n ): any {\n this.chunk.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;CAChC;CAED,0BACET,WACAO,YACAN,MACAO,QACAL,MACAM,WACK;EACL,KAAK,IAAI,WAAW,MAAM,KAAK;CAChC;CAED,uBACET,WACAO,YACAN,MACAO,QACAL,MACAM,WACK;EACL,KAAK,IAAI,WAAW,MAAM,KAAK;CAChC;AACF;AAED,IAAa,wBAAb,cAA2C,6BAA6B;CACtE,OAAO;CAEP,UAAe,CAAE;CAEjB,WAAgB,CAAE;CAElB,QAAe,CAAE;CAEjB,yBACEC,YACAH,YACAN,MACAO,QACAG,OACAF,WACK;EACL,KAAK,UAAU;CAChB;CAED,0BACEC,YACAH,YACAN,MACAO,QACAG,OACAF,WACK;EACL,KAAK,WAAW;CACjB;CAED,uBACEC,YACAH,YACAN,MACAO,QACAG,OACAF,WACK;EACL,KAAK,MAAM,KAAK,KAAK;CACtB;AACF"}
@@ -0,0 +1,34 @@
1
+ import { BaseCallbackHandler } from "@langchain/core/callbacks/base";
2
+
3
+ //#region src/utils/handler.d.ts
4
+ interface GoogleCustomEventInfo {
5
+ subEvent: string;
6
+ module: string;
7
+ }
8
+ declare abstract class GoogleRequestCallbackHandler extends BaseCallbackHandler {
9
+ customEventInfo(eventName: string): GoogleCustomEventInfo;
10
+ abstract handleCustomRequestEvent(eventName: string, eventInfo: GoogleCustomEventInfo, data: any, runId: string, tags?: string[], metadata?: Record<string, any>): any;
11
+ abstract handleCustomResponseEvent(eventName: string, eventInfo: GoogleCustomEventInfo, data: any, runId: string, tags?: string[], metadata?: Record<string, any>): any;
12
+ abstract handleCustomChunkEvent(eventName: string, eventInfo: GoogleCustomEventInfo, data: any, runId: string, tags?: string[], metadata?: Record<string, any>): any;
13
+ handleCustomEvent(eventName: string, data: any, runId: string, tags?: string[], metadata?: Record<string, any>): any;
14
+ }
15
+ declare class GoogleRequestLogger extends GoogleRequestCallbackHandler {
16
+ name: string;
17
+ shortenStringLength: number;
18
+ log(eventName: string, data: any, tags?: string[]): undefined;
19
+ handleCustomRequestEvent(eventName: string, _eventInfo: GoogleCustomEventInfo, data: any, _runId: string, tags?: string[], _metadata?: Record<string, any>): any;
20
+ handleCustomResponseEvent(eventName: string, _eventInfo: GoogleCustomEventInfo, data: any, _runId: string, tags?: string[], _metadata?: Record<string, any>): any;
21
+ handleCustomChunkEvent(eventName: string, _eventInfo: GoogleCustomEventInfo, data: any, _runId: string, tags?: string[], _metadata?: Record<string, any>): any;
22
+ }
23
+ declare class GoogleRequestRecorder extends GoogleRequestCallbackHandler {
24
+ name: string;
25
+ request: any;
26
+ response: any;
27
+ chunk: any[];
28
+ handleCustomRequestEvent(_eventName: string, _eventInfo: GoogleCustomEventInfo, data: any, _runId: string, _tags?: string[], _metadata?: Record<string, any>): any;
29
+ handleCustomResponseEvent(_eventName: string, _eventInfo: GoogleCustomEventInfo, data: any, _runId: string, _tags?: string[], _metadata?: Record<string, any>): any;
30
+ handleCustomChunkEvent(_eventName: string, _eventInfo: GoogleCustomEventInfo, data: any, _runId: string, _tags?: string[], _metadata?: Record<string, any>): any;
31
+ }
32
+ //#endregion
33
+ export { GoogleCustomEventInfo, GoogleRequestCallbackHandler, GoogleRequestLogger, GoogleRequestRecorder };
34
+ //# sourceMappingURL=handler.d.cts.map