@mshindi-labs/google 1.1.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.md +7 -4
  2. package/dist/calendar.cjs +1641 -0
  3. package/dist/calendar.cjs.map +1 -0
  4. package/dist/calendar.d.cts +161 -0
  5. package/dist/calendar.d.ts +161 -0
  6. package/dist/calendar.js +1641 -0
  7. package/dist/calendar.js.map +1 -0
  8. package/dist/{chunk-JVP7HHFU.js → chunk-4V5ZJNPI.js} +2 -2
  9. package/dist/{chunk-KJPQ3DMR.cjs → chunk-6PMJ6VB6.cjs} +6 -6
  10. package/dist/{chunk-KJPQ3DMR.cjs.map → chunk-6PMJ6VB6.cjs.map} +1 -1
  11. package/dist/{chunk-SIDO26T7.js → chunk-6RDWEYXZ.js} +11 -4
  12. package/dist/chunk-6RDWEYXZ.js.map +1 -0
  13. package/dist/chunk-AMBBE4TW.js +56 -0
  14. package/dist/chunk-AMBBE4TW.js.map +1 -0
  15. package/dist/{chunk-VN5VWVCT.cjs → chunk-DPAPYMB3.cjs} +63 -56
  16. package/dist/chunk-DPAPYMB3.cjs.map +1 -0
  17. package/dist/{chunk-RWT25QHA.js → chunk-FCHXM22B.js} +45 -3
  18. package/dist/{chunk-RWT25QHA.js.map → chunk-FCHXM22B.js.map} +1 -1
  19. package/dist/{chunk-V22QP2AM.cjs → chunk-JDA3ZRUY.cjs} +3 -3
  20. package/dist/{chunk-V22QP2AM.cjs.map → chunk-JDA3ZRUY.cjs.map} +1 -1
  21. package/dist/{chunk-SHDP4A3A.cjs → chunk-JZVDD4DL.cjs} +44 -2
  22. package/dist/chunk-JZVDD4DL.cjs.map +1 -0
  23. package/dist/chunk-S357VL5V.cjs +56 -0
  24. package/dist/chunk-S357VL5V.cjs.map +1 -0
  25. package/dist/{chunk-Z7O6GO3C.js → chunk-SXD5K23S.js} +2 -2
  26. package/dist/core.cjs +30 -18
  27. package/dist/core.cjs.map +1 -1
  28. package/dist/core.d.cts +23 -4
  29. package/dist/core.d.ts +23 -4
  30. package/dist/core.js +16 -4
  31. package/dist/core.js.map +1 -1
  32. package/dist/{create-google-CPGcK-3G.d.cts → create-google-Bo8_Nc1C.d.cts} +2 -1
  33. package/dist/{create-google-nP9f9jd9.d.ts → create-google-snvkHaEk.d.ts} +2 -1
  34. package/dist/{events-BsWOMtza.d.ts → events-BlC10ISp.d.cts} +31 -0
  35. package/dist/{events-BsWOMtza.d.cts → events-BlC10ISp.d.ts} +31 -0
  36. package/dist/gmail.cjs +48 -75
  37. package/dist/gmail.cjs.map +1 -1
  38. package/dist/gmail.d.cts +2 -2
  39. package/dist/gmail.d.ts +2 -2
  40. package/dist/gmail.js +15 -42
  41. package/dist/gmail.js.map +1 -1
  42. package/dist/postgres.cjs +8 -8
  43. package/dist/postgres.d.cts +1 -1
  44. package/dist/postgres.d.ts +1 -1
  45. package/dist/postgres.js +1 -1
  46. package/dist/testing.cjs +226 -13
  47. package/dist/testing.cjs.map +1 -1
  48. package/dist/testing.d.cts +91 -2
  49. package/dist/testing.d.ts +91 -2
  50. package/dist/testing.js +216 -3
  51. package/dist/testing.js.map +1 -1
  52. package/dist/transport-DHApc5oq.d.cts +103 -0
  53. package/dist/transport-DHApc5oq.d.ts +103 -0
  54. package/package.json +19 -4
  55. package/dist/chunk-SHDP4A3A.cjs.map +0 -1
  56. package/dist/chunk-SIDO26T7.js.map +0 -1
  57. package/dist/chunk-VN5VWVCT.cjs.map +0 -1
  58. /package/dist/{chunk-JVP7HHFU.js.map → chunk-4V5ZJNPI.js.map} +0 -0
  59. /package/dist/{chunk-Z7O6GO3C.js.map → chunk-SXD5K23S.js.map} +0 -0
package/dist/core.d.cts CHANGED
@@ -1,9 +1,9 @@
1
- export { B as BASE_SCOPES, C as ClientsApi, a as ConnectionsApi, b as CreateGoogleOptions, G as GoogleCore, c as GoogleService, O as OAuthApi, S as SERVICE_SCOPES, d as createGoogle, s as scopesFor } from './create-google-CPGcK-3G.cjs';
1
+ export { B as BASE_SCOPES, C as ClientsApi, a as ConnectionsApi, b as CreateGoogleOptions, G as GoogleCore, c as GoogleService, O as OAuthApi, S as SERVICE_SCOPES, d as createGoogle, s as scopesFor } from './create-google-Bo8_Nc1C.cjs';
2
2
  export { S as StaticKeyProvider } from './static-key-provider-CPNt4YvF.cjs';
3
3
  import { K as KeyProvider } from './key-provider-Cq_14Bh6.cjs';
4
4
  export { I as InvalidGrantError, O as OAuthGateway } from './key-provider-Cq_14Bh6.cjs';
5
- import { C as CredentialStore } from './events-BsWOMtza.cjs';
6
- export { A as AadRecord, a as ConnectionRecord, b as ConnectionStatus, c as ConnectionView, E as EncryptedValue, d as EncryptedValueRef, G as GoogleEvent, L as Logger, O as OAuthClientRecord, e as OAuthStateRecord } from './events-BsWOMtza.cjs';
5
+ import { C as CredentialStore } from './events-BlC10ISp.cjs';
6
+ export { A as AadRecord, a as ConnectionRecord, b as ConnectionStatus, c as ConnectionView, E as EncryptedValue, d as EncryptedValueRef, G as GoogleEvent, L as Logger, O as OAuthClientRecord, e as OAuthStateRecord } from './events-BlC10ISp.cjs';
7
7
 
8
8
  interface GoogleErrorOptions {
9
9
  tenantId?: string;
@@ -79,6 +79,25 @@ declare class MissingPeerDependencyError extends GoogleLibError {
79
79
  declare class InvalidConfigError extends GoogleLibError {
80
80
  constructor(message: string, opts?: GoogleErrorOptions);
81
81
  }
82
+ declare class InvalidEventError extends GoogleLibError {
83
+ readonly field: string;
84
+ constructor(field: string, message?: string, opts?: GoogleErrorOptions);
85
+ }
86
+ declare class EventNotFoundError extends GoogleLibError {
87
+ constructor(message?: string, opts?: GoogleErrorOptions);
88
+ }
89
+ declare class EventNotManagedError extends GoogleLibError {
90
+ constructor(message?: string, opts?: GoogleErrorOptions);
91
+ }
92
+ declare class EventCancelledError extends GoogleLibError {
93
+ constructor(message?: string, opts?: GoogleErrorOptions);
94
+ }
95
+ declare class EventConflictError extends GoogleLibError {
96
+ constructor(message?: string, opts?: GoogleErrorOptions);
97
+ }
98
+ declare class ConferencingUnavailableError extends GoogleLibError {
99
+ constructor(message?: string, opts?: GoogleErrorOptions);
100
+ }
82
101
 
83
102
  type GcpKmsClientLike = {
84
103
  encrypt(req: {
@@ -170,4 +189,4 @@ declare function verifyAll(opts: {
170
189
  failed: OpsFailure[];
171
190
  }>;
172
191
 
173
- export { type AwsKmsClientLike, type AwsKmsCommands, AwsKmsKeyProvider, ConnectionNotFoundError, ConnectionRevokedError, CredentialIntegrityError, CredentialStore, DailyQuotaExceededError, type GcpKmsClientLike, GcpKmsKeyProvider, GoogleApiError, type GoogleErrorOptions, GoogleLibError, InvalidConfigError, InvalidMessageError, InvalidOAuthStateError, KeyProvider, KeyProviderUnavailableError, MessageTooLargeError, MissingPeerDependencyError, MissingScopeError, NoRefreshTokenError, OAuthClientNotConfiguredError, OAuthConsentDeniedError, type OpsFailure, RateLimitedError, SendOutcomeUnknownError, UnexpectedAccountError, rewrapAll, verifyAll };
192
+ export { type AwsKmsClientLike, type AwsKmsCommands, AwsKmsKeyProvider, ConferencingUnavailableError, ConnectionNotFoundError, ConnectionRevokedError, CredentialIntegrityError, CredentialStore, DailyQuotaExceededError, EventCancelledError, EventConflictError, EventNotFoundError, EventNotManagedError, type GcpKmsClientLike, GcpKmsKeyProvider, GoogleApiError, type GoogleErrorOptions, GoogleLibError, InvalidConfigError, InvalidEventError, InvalidMessageError, InvalidOAuthStateError, KeyProvider, KeyProviderUnavailableError, MessageTooLargeError, MissingPeerDependencyError, MissingScopeError, NoRefreshTokenError, OAuthClientNotConfiguredError, OAuthConsentDeniedError, type OpsFailure, RateLimitedError, SendOutcomeUnknownError, UnexpectedAccountError, rewrapAll, verifyAll };
package/dist/core.d.ts CHANGED
@@ -1,9 +1,9 @@
1
- export { B as BASE_SCOPES, C as ClientsApi, a as ConnectionsApi, b as CreateGoogleOptions, G as GoogleCore, c as GoogleService, O as OAuthApi, S as SERVICE_SCOPES, d as createGoogle, s as scopesFor } from './create-google-nP9f9jd9.js';
1
+ export { B as BASE_SCOPES, C as ClientsApi, a as ConnectionsApi, b as CreateGoogleOptions, G as GoogleCore, c as GoogleService, O as OAuthApi, S as SERVICE_SCOPES, d as createGoogle, s as scopesFor } from './create-google-snvkHaEk.js';
2
2
  export { S as StaticKeyProvider } from './static-key-provider-BhyRhY6-.js';
3
3
  import { K as KeyProvider } from './key-provider-Cq_14Bh6.js';
4
4
  export { I as InvalidGrantError, O as OAuthGateway } from './key-provider-Cq_14Bh6.js';
5
- import { C as CredentialStore } from './events-BsWOMtza.js';
6
- export { A as AadRecord, a as ConnectionRecord, b as ConnectionStatus, c as ConnectionView, E as EncryptedValue, d as EncryptedValueRef, G as GoogleEvent, L as Logger, O as OAuthClientRecord, e as OAuthStateRecord } from './events-BsWOMtza.js';
5
+ import { C as CredentialStore } from './events-BlC10ISp.js';
6
+ export { A as AadRecord, a as ConnectionRecord, b as ConnectionStatus, c as ConnectionView, E as EncryptedValue, d as EncryptedValueRef, G as GoogleEvent, L as Logger, O as OAuthClientRecord, e as OAuthStateRecord } from './events-BlC10ISp.js';
7
7
 
8
8
  interface GoogleErrorOptions {
9
9
  tenantId?: string;
@@ -79,6 +79,25 @@ declare class MissingPeerDependencyError extends GoogleLibError {
79
79
  declare class InvalidConfigError extends GoogleLibError {
80
80
  constructor(message: string, opts?: GoogleErrorOptions);
81
81
  }
82
+ declare class InvalidEventError extends GoogleLibError {
83
+ readonly field: string;
84
+ constructor(field: string, message?: string, opts?: GoogleErrorOptions);
85
+ }
86
+ declare class EventNotFoundError extends GoogleLibError {
87
+ constructor(message?: string, opts?: GoogleErrorOptions);
88
+ }
89
+ declare class EventNotManagedError extends GoogleLibError {
90
+ constructor(message?: string, opts?: GoogleErrorOptions);
91
+ }
92
+ declare class EventCancelledError extends GoogleLibError {
93
+ constructor(message?: string, opts?: GoogleErrorOptions);
94
+ }
95
+ declare class EventConflictError extends GoogleLibError {
96
+ constructor(message?: string, opts?: GoogleErrorOptions);
97
+ }
98
+ declare class ConferencingUnavailableError extends GoogleLibError {
99
+ constructor(message?: string, opts?: GoogleErrorOptions);
100
+ }
82
101
 
83
102
  type GcpKmsClientLike = {
84
103
  encrypt(req: {
@@ -170,4 +189,4 @@ declare function verifyAll(opts: {
170
189
  failed: OpsFailure[];
171
190
  }>;
172
191
 
173
- export { type AwsKmsClientLike, type AwsKmsCommands, AwsKmsKeyProvider, ConnectionNotFoundError, ConnectionRevokedError, CredentialIntegrityError, CredentialStore, DailyQuotaExceededError, type GcpKmsClientLike, GcpKmsKeyProvider, GoogleApiError, type GoogleErrorOptions, GoogleLibError, InvalidConfigError, InvalidMessageError, InvalidOAuthStateError, KeyProvider, KeyProviderUnavailableError, MessageTooLargeError, MissingPeerDependencyError, MissingScopeError, NoRefreshTokenError, OAuthClientNotConfiguredError, OAuthConsentDeniedError, type OpsFailure, RateLimitedError, SendOutcomeUnknownError, UnexpectedAccountError, rewrapAll, verifyAll };
192
+ export { type AwsKmsClientLike, type AwsKmsCommands, AwsKmsKeyProvider, ConferencingUnavailableError, ConnectionNotFoundError, ConnectionRevokedError, CredentialIntegrityError, CredentialStore, DailyQuotaExceededError, EventCancelledError, EventConflictError, EventNotFoundError, EventNotManagedError, type GcpKmsClientLike, GcpKmsKeyProvider, GoogleApiError, type GoogleErrorOptions, GoogleLibError, InvalidConfigError, InvalidEventError, InvalidMessageError, InvalidOAuthStateError, KeyProvider, KeyProviderUnavailableError, MessageTooLargeError, MissingPeerDependencyError, MissingScopeError, NoRefreshTokenError, OAuthClientNotConfiguredError, OAuthConsentDeniedError, type OpsFailure, RateLimitedError, SendOutcomeUnknownError, UnexpectedAccountError, rewrapAll, verifyAll };
package/dist/core.js CHANGED
@@ -6,22 +6,28 @@ import {
6
6
  decryptValue,
7
7
  rewrapValue,
8
8
  scopesFor
9
- } from "./chunk-SIDO26T7.js";
9
+ } from "./chunk-6RDWEYXZ.js";
10
10
  import {
11
11
  StaticKeyProvider
12
- } from "./chunk-JVP7HHFU.js";
12
+ } from "./chunk-4V5ZJNPI.js";
13
13
  import {
14
14
  InvalidGrantError,
15
15
  loadPeer
16
- } from "./chunk-Z7O6GO3C.js";
16
+ } from "./chunk-SXD5K23S.js";
17
17
  import {
18
+ ConferencingUnavailableError,
18
19
  ConnectionNotFoundError,
19
20
  ConnectionRevokedError,
20
21
  CredentialIntegrityError,
21
22
  DailyQuotaExceededError,
23
+ EventCancelledError,
24
+ EventConflictError,
25
+ EventNotFoundError,
26
+ EventNotManagedError,
22
27
  GoogleApiError,
23
28
  GoogleLibError,
24
29
  InvalidConfigError,
30
+ InvalidEventError,
25
31
  InvalidMessageError,
26
32
  InvalidOAuthStateError,
27
33
  KeyProviderUnavailableError,
@@ -34,7 +40,7 @@ import {
34
40
  RateLimitedError,
35
41
  SendOutcomeUnknownError,
36
42
  UnexpectedAccountError
37
- } from "./chunk-RWT25QHA.js";
43
+ } from "./chunk-FCHXM22B.js";
38
44
 
39
45
  // src/core/crypto/kms-errors.ts
40
46
  var NET_CODES = /* @__PURE__ */ new Set([
@@ -258,14 +264,20 @@ async function verifyAll(opts) {
258
264
  export {
259
265
  AwsKmsKeyProvider,
260
266
  BASE_SCOPES,
267
+ ConferencingUnavailableError,
261
268
  ConnectionNotFoundError,
262
269
  ConnectionRevokedError,
263
270
  CredentialIntegrityError,
264
271
  DailyQuotaExceededError,
272
+ EventCancelledError,
273
+ EventConflictError,
274
+ EventNotFoundError,
275
+ EventNotManagedError,
265
276
  GcpKmsKeyProvider,
266
277
  GoogleApiError,
267
278
  GoogleLibError,
268
279
  InvalidConfigError,
280
+ InvalidEventError,
269
281
  InvalidGrantError,
270
282
  InvalidMessageError,
271
283
  InvalidOAuthStateError,
package/dist/core.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/crypto/kms-errors.ts","../src/core/crypto/gcp-kms.ts","../src/core/crypto/aws-kms.ts","../src/core/ops.ts"],"sourcesContent":["import {\n CredentialIntegrityError,\n KeyProviderUnavailableError,\n} from \"../errors.js\";\n\nconst NET_CODES = new Set([\n \"ECONNREFUSED\",\n \"ECONNRESET\",\n \"ETIMEDOUT\",\n \"ENOTFOUND\",\n \"EAI_AGAIN\",\n]);\n// gRPC: DEADLINE_EXCEEDED, RESOURCE_EXHAUSTED, UNAVAILABLE.\nconst GRPC_CODES = new Set([4, 8, 14]);\n\n/** True for transport/availability failures (retryable), false otherwise. */\nexport function isKmsAvailabilityError(err: unknown): boolean {\n if (typeof err !== \"object\" || err === null) return false;\n const e = err as {\n code?: unknown;\n name?: unknown;\n $metadata?: { httpStatusCode?: unknown };\n };\n if (typeof e.code === \"string\" && NET_CODES.has(e.code)) return true;\n if (typeof e.code === \"number\" && GRPC_CODES.has(e.code)) return true;\n if (e.name === \"ThrottlingException\" || e.name === \"TimeoutError\") {\n return true;\n }\n const status = e.$metadata?.httpStatusCode;\n return typeof status === \"number\" && status >= 500;\n}\n\n/** Maps a KMS client failure to the library error; the cause is redacted. */\nexport function mapKmsError(err: unknown): Error {\n return isKmsAvailabilityError(err)\n ? new KeyProviderUnavailableError(undefined, { cause: err })\n : new CredentialIntegrityError(undefined, { cause: err });\n}\n","import { CredentialIntegrityError } from \"../errors.js\";\nimport { loadPeer } from \"../peer.js\";\nimport { mapKmsError } from \"./kms-errors.js\";\nimport type { KeyProvider } from \"./key-provider.js\";\n\nconst PREFIX = \"gcp-kms:\";\n\nexport type GcpKmsClientLike = {\n encrypt(req: {\n name: string;\n plaintext: Uint8Array;\n additionalAuthenticatedData: Uint8Array;\n }): Promise<[{ ciphertext?: Uint8Array | string | null }]>;\n decrypt(req: {\n name: string;\n ciphertext: Uint8Array;\n additionalAuthenticatedData: Uint8Array;\n }): Promise<[{ plaintext?: Uint8Array | string | null }]>;\n};\n\n/** Wraps DEKs with a Cloud KMS symmetric key. kid is `gcp-kms:<keyName>`. */\nexport class GcpKmsKeyProvider implements KeyProvider {\n readonly currentKeyId: string;\n readonly #keyName: string;\n #client: GcpKmsClientLike | undefined;\n #loading: Promise<GcpKmsClientLike> | undefined;\n\n constructor(opts: { keyName: string; client?: GcpKmsClientLike }) {\n this.#keyName = opts.keyName;\n this.currentKeyId = PREFIX + opts.keyName;\n this.#client = opts.client;\n }\n\n async #getClient(): Promise<GcpKmsClientLike> {\n if (this.#client) return this.#client;\n this.#loading ??= loadPeer<{\n KeyManagementServiceClient: new () => GcpKmsClientLike;\n }>(\"@google-cloud/kms\", \"@google-cloud/kms\").then(\n (m) => (this.#client = new m.KeyManagementServiceClient()),\n (err) => {\n this.#loading = undefined;\n throw err;\n },\n );\n return this.#loading;\n }\n\n async wrap(\n dek: Uint8Array,\n aad: string,\n ): Promise<{ kid: string; wdek: Uint8Array }> {\n const client = await this.#getClient();\n let res: [{ ciphertext?: Uint8Array | string | null }];\n try {\n res = await client.encrypt({\n name: this.#keyName,\n plaintext: dek,\n additionalAuthenticatedData: Buffer.from(aad, \"utf8\"),\n });\n } catch (err) {\n throw mapKmsError(err);\n }\n const ciphertext = res?.[0]?.ciphertext;\n if (ciphertext == null || ciphertext.length === 0) {\n throw new CredentialIntegrityError();\n }\n return { kid: this.currentKeyId, wdek: toBytes(ciphertext) };\n }\n\n async unwrap(\n kid: string,\n wdek: Uint8Array,\n aad: string,\n ): Promise<Uint8Array> {\n if (!kid.startsWith(PREFIX) || kid.length === PREFIX.length) {\n throw new CredentialIntegrityError();\n }\n const client = await this.#getClient();\n let res: [{ plaintext?: Uint8Array | string | null }];\n try {\n res = await client.decrypt({\n name: kid.slice(PREFIX.length),\n ciphertext: wdek,\n additionalAuthenticatedData: Buffer.from(aad, \"utf8\"),\n });\n } catch (err) {\n throw mapKmsError(err);\n }\n const plaintext = res?.[0]?.plaintext;\n if (plaintext == null || plaintext.length === 0) {\n throw new CredentialIntegrityError();\n }\n // Return the response buffer itself: the caller zeroes what it receives.\n return toBytes(plaintext);\n }\n}\n\nfunction toBytes(v: Uint8Array | string): Uint8Array {\n return typeof v === \"string\" ? Buffer.from(v, \"base64\") : v;\n}\n","import { CredentialIntegrityError } from \"../errors.js\";\nimport { loadPeer } from \"../peer.js\";\nimport { mapKmsError } from \"./kms-errors.js\";\nimport type { KeyProvider } from \"./key-provider.js\";\n\nconst PREFIX = \"aws-kms:\";\nconst CONTEXT_KEY = \"mshindi-google\";\n\nexport type AwsKmsClientLike = {\n send(\n cmd: unknown,\n ): Promise<{ CiphertextBlob?: Uint8Array; Plaintext?: Uint8Array }>;\n};\n\nexport type AwsKmsCommands = {\n EncryptCommand: new (input: any) => unknown;\n DecryptCommand: new (input: any) => unknown;\n};\n\ntype AwsKmsModule = AwsKmsCommands & { KMSClient: new () => AwsKmsClientLike };\n\n/** Wraps DEKs with an AWS KMS symmetric key. kid is `aws-kms:<keyId>`. */\nexport class AwsKmsKeyProvider implements KeyProvider {\n readonly currentKeyId: string;\n readonly #keyId: string;\n #client: AwsKmsClientLike | undefined;\n #commands: AwsKmsCommands | undefined;\n #sdk: Promise<AwsKmsModule> | undefined;\n\n /**\n * AWS SDK v3 `send` needs real Command instances, so the SDK is loaded\n * lazily via loadPeer only when `client` or `commands` is not injected.\n * Inject both (e.g. in tests) to avoid loading it at all.\n */\n constructor(opts: {\n keyId: string;\n client?: AwsKmsClientLike;\n commands?: AwsKmsCommands;\n }) {\n this.#keyId = opts.keyId;\n this.currentKeyId = PREFIX + opts.keyId;\n this.#client = opts.client;\n this.#commands = opts.commands;\n }\n\n async #load(): Promise<{\n sdk: AwsKmsCommands;\n client: AwsKmsClientLike;\n }> {\n if (this.#client && this.#commands) {\n return { sdk: this.#commands, client: this.#client };\n }\n this.#sdk ??= loadPeer<AwsKmsModule>(\n \"@aws-sdk/client-kms\",\n \"@aws-sdk/client-kms\",\n ).catch((err) => {\n this.#sdk = undefined;\n throw err;\n });\n const sdk = await this.#sdk;\n this.#commands ??= sdk;\n this.#client ??= new sdk.KMSClient();\n return { sdk: this.#commands, client: this.#client };\n }\n\n async wrap(\n dek: Uint8Array,\n aad: string,\n ): Promise<{ kid: string; wdek: Uint8Array }> {\n const { sdk, client } = await this.#load();\n let res: { CiphertextBlob?: Uint8Array };\n try {\n res = await client.send(\n new sdk.EncryptCommand({\n KeyId: this.#keyId,\n Plaintext: dek,\n EncryptionContext: { [CONTEXT_KEY]: aad },\n }),\n );\n } catch (err) {\n throw mapKmsError(err);\n }\n if (!res?.CiphertextBlob || res.CiphertextBlob.length === 0) {\n throw new CredentialIntegrityError();\n }\n return { kid: this.currentKeyId, wdek: res.CiphertextBlob };\n }\n\n async unwrap(\n kid: string,\n wdek: Uint8Array,\n aad: string,\n ): Promise<Uint8Array> {\n if (!kid.startsWith(PREFIX) || kid.length === PREFIX.length) {\n throw new CredentialIntegrityError();\n }\n const { sdk, client } = await this.#load();\n let res: { Plaintext?: Uint8Array };\n try {\n res = await client.send(\n new sdk.DecryptCommand({\n // KeyId makes a wrong-key ciphertext fail closed.\n KeyId: kid.slice(PREFIX.length),\n CiphertextBlob: wdek,\n EncryptionContext: { [CONTEXT_KEY]: aad },\n }),\n );\n } catch (err) {\n throw mapKmsError(err);\n }\n if (!res?.Plaintext || res.Plaintext.length === 0) {\n throw new CredentialIntegrityError();\n }\n // Return the response buffer itself: the caller zeroes what it receives.\n return res.Plaintext;\n }\n}\n","import { buildAad, decryptValue, rewrapValue } from \"./crypto/envelope.js\";\nimport type { KeyProvider } from \"./crypto/key-provider.js\";\nimport { GoogleLibError } from \"./errors.js\";\nimport type { CredentialStore } from \"./store.js\";\nimport type { EncryptedValueRef } from \"./types.js\";\n\nconst DEFAULT_BATCH_SIZE = 100;\n\nexport type OpsFailure = { record: string; error: string };\n\nconst label = (ref: EncryptedValueRef): string =>\n `${ref.record}:${ref.recordId}.${ref.field}`;\n\nconst aadOf = (ref: EncryptedValueRef): string =>\n buildAad({\n tenantId: ref.tenantId,\n record: ref.record,\n recordId: ref.recordId,\n field: ref.field,\n });\n\n/** Error code only: never a message, cause, or plaintext. */\nconst codeOf = (err: unknown): string =>\n err instanceof GoogleLibError ? err.code : \"unknown\";\n\n/**\n * Re-wraps every stored DEK under the provider's current key. Idempotent and\n * resumable: values already on the current key (or outside `fromKeyId`) are skipped.\n */\nexport async function rewrapAll(opts: {\n store: CredentialStore;\n keyProvider: KeyProvider;\n fromKeyId?: string;\n batchSize?: number;\n}): Promise<{ rewrapped: number; skipped: number; failed: OpsFailure[] }> {\n const { store, keyProvider, fromKeyId } = opts;\n const result = {\n rewrapped: 0,\n skipped: 0,\n failed: [] as OpsFailure[],\n };\n for await (const ref of store.iterateEncryptedValues(\n opts.batchSize ?? DEFAULT_BATCH_SIZE,\n )) {\n if (\n ref.value.kid === keyProvider.currentKeyId ||\n (fromKeyId !== undefined && ref.value.kid !== fromKeyId)\n ) {\n result.skipped++;\n continue;\n }\n try {\n const next = await rewrapValue(ref.value, aadOf(ref), keyProvider);\n // A CAS miss means a concurrent writer changed it; a rerun will pick it up.\n if (await store.replaceEncryptedValue(ref, next)) result.rewrapped++;\n else result.skipped++;\n } catch (err) {\n result.failed.push({ record: label(ref), error: codeOf(err) });\n }\n }\n return result;\n}\n\n/** Fully decrypts every stored value (plaintext discarded immediately) to prove integrity. */\nexport async function verifyAll(opts: {\n store: CredentialStore;\n keyProvider: KeyProvider;\n batchSize?: number;\n}): Promise<{ ok: number; failed: OpsFailure[] }> {\n const result = { ok: 0, failed: [] as OpsFailure[] };\n for await (const ref of opts.store.iterateEncryptedValues(\n opts.batchSize ?? DEFAULT_BATCH_SIZE,\n )) {\n try {\n await decryptValue(ref.value, aadOf(ref), opts.keyProvider);\n result.ok++;\n } catch (err) {\n result.failed.push({ record: label(ref), error: codeOf(err) });\n }\n }\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,IAAM,YAAY,oBAAI,IAAI;AAAA,EACxB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAED,IAAM,aAAa,oBAAI,IAAI,CAAC,GAAG,GAAG,EAAE,CAAC;AAG9B,SAAS,uBAAuB,KAAuB;AAC5D,MAAI,OAAO,QA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AChD,QAAM,SAAS,EAAE,IAAI,GAAG,QAAQ,CAAC,EAAkB;AACnD,mBAAiB,OAAO,KAAK,MAAM;AAAA,IACjC,KAAK,aAAa;AAAA,EACpB,GAAG;AACD,QAAI;AACF,YAAM,aAAa,IAAI,OAAO,MAAM,GAAG,GAAG,KAAK,WAAW;AAC1D,aAAO;AAAA,IACT,SAAS,KAAK;AACZ,aAAO,OAAO,KAAK,EAAE,QAAQ,MAAM,GAAG,GAAG,OAAO,OAAO,GAAG,EAAE,CAAC;AAAA,IAC/D;AAAA,EACF;AACA,SAAO;AACT;","names":["PREFIX"]}
1
+ {"version":3,"sources":["../src/core/crypto/kms-errors.ts","../src/core/crypto/gcp-kms.ts","../src/core/crypto/aws-kms.ts","../src/core/ops.ts"],"sourcesContent":["import {\n CredentialIntegrityError,\n KeyProviderUnavailableError,\n} from \"../errors.js\";\n\nconst NET_CODES = new Set([\n \"ECONNREFUSED\",\n \"ECONNRESET\",\n \"ETIMEDOUT\",\n \"ENOTFOUND\",\n \"EAI_AGAIN\",\n]);\n// gRPC: DEADLINE_EXCEEDED, RESOURCE_EXHAUSTED, UNAVAILABLE.\nconst GRPC_CODES = new Set([4, 8, 14]);\n\n/** True for transport/availability failures (retryable), false otherwise. */\nexport function isKmsAvailabilityError(err: unknown): boolean {\n if (typeof err !== \"object\" || err === null) return false;\n const e = err as {\n code?: unknown;\n name?: unknown;\n $metadata?: { httpStatusCode?: unknown };\n };\n if (typeof e.code === \"string\" && NET_CODES.has(e.code)) return true;\n if (typeof e.code === \"number\" && GRPC_CODES.has(e.code)) return true;\n if (e.name === \"ThrottlingException\" || e.name === \"TimeoutError\") {\n return true;\n }\n const status = e.$metadata?.httpStatusCode;\n return typeof status === \"number\" && status >= 500;\n}\n\n/** Maps a KMS client failure to the library error; the cause is redacted. */\nexport function mapKmsError(err: unknown): Error {\n return isKmsAvailabilityError(err)\n ? new KeyProviderUnavailableError(undefined, { cause: err })\n : new CredentialIntegrityError(undefined, { cause: err });\n}\n","import { CredentialIntegrityError } from \"../errors.js\";\nimport { loadPeer } from \"../peer.js\";\nimport { mapKmsError } from \"./kms-errors.js\";\nimport type { KeyProvider } from \"./key-provider.js\";\n\nconst PREFIX = \"gcp-kms:\";\n\nexport type GcpKmsClientLike = {\n encrypt(req: {\n name: string;\n plaintext: Uint8Array;\n additionalAuthenticatedData: Uint8Array;\n }): Promise<[{ ciphertext?: Uint8Array | string | null }]>;\n decrypt(req: {\n name: string;\n ciphertext: Uint8Array;\n additionalAuthenticatedData: Uint8Array;\n }): Promise<[{ plaintext?: Uint8Array | string | null }]>;\n};\n\n/** Wraps DEKs with a Cloud KMS symmetric key. kid is `gcp-kms:<keyName>`. */\nexport class GcpKmsKeyProvider implements KeyProvider {\n readonly currentKeyId: string;\n readonly #keyName: string;\n #client: GcpKmsClientLike | undefined;\n #loading: Promise<GcpKmsClientLike> | undefined;\n\n constructor(opts: { keyName: string; client?: GcpKmsClientLike }) {\n this.#keyName = opts.keyName;\n this.currentKeyId = PREFIX + opts.keyName;\n this.#client = opts.client;\n }\n\n async #getClient(): Promise<GcpKmsClientLike> {\n if (this.#client) return this.#client;\n this.#loading ??= loadPeer<{\n KeyManagementServiceClient: new () => GcpKmsClientLike;\n }>(\"@google-cloud/kms\", \"@google-cloud/kms\").then(\n (m) => (this.#client = new m.KeyManagementServiceClient()),\n (err) => {\n this.#loading = undefined;\n throw err;\n },\n );\n return this.#loading;\n }\n\n async wrap(\n dek: Uint8Array,\n aad: string,\n ): Promise<{ kid: string; wdek: Uint8Array }> {\n const client = await this.#getClient();\n let res: [{ ciphertext?: Uint8Array | string | null }];\n try {\n res = await client.encrypt({\n name: this.#keyName,\n plaintext: dek,\n additionalAuthenticatedData: Buffer.from(aad, \"utf8\"),\n });\n } catch (err) {\n throw mapKmsError(err);\n }\n const ciphertext = res?.[0]?.ciphertext;\n if (ciphertext == null || ciphertext.length === 0) {\n throw new CredentialIntegrityError();\n }\n return { kid: this.currentKeyId, wdek: toBytes(ciphertext) };\n }\n\n async unwrap(\n kid: string,\n wdek: Uint8Array,\n aad: string,\n ): Promise<Uint8Array> {\n if (!kid.startsWith(PREFIX) || kid.length === PREFIX.length) {\n throw new CredentialIntegrityError();\n }\n const client = await this.#getClient();\n let res: [{ plaintext?: Uint8Array | string | null }];\n try {\n res = await client.decrypt({\n name: kid.slice(PREFIX.length),\n ciphertext: wdek,\n additionalAuthenticatedData: Buffer.from(aad, \"utf8\"),\n });\n } catch (err) {\n throw mapKmsError(err);\n }\n const plaintext = res?.[0]?.plaintext;\n if (plaintext == null || plaintext.length === 0) {\n throw new CredentialIntegrityError();\n }\n // Return the response buffer itself: the caller zeroes what it receives.\n return toBytes(plaintext);\n }\n}\n\nfunction toBytes(v: Uint8Array | string): Uint8Array {\n return typeof v === \"string\" ? Buffer.from(v, \"base64\") : v;\n}\n","import { CredentialIntegrityError } from \"../errors.js\";\nimport { loadPeer } from \"../peer.js\";\nimport { mapKmsError } from \"./kms-errors.js\";\nimport type { KeyProvider } from \"./key-provider.js\";\n\nconst PREFIX = \"aws-kms:\";\nconst CONTEXT_KEY = \"mshindi-google\";\n\nexport type AwsKmsClientLike = {\n send(\n cmd: unknown,\n ): Promise<{ CiphertextBlob?: Uint8Array; Plaintext?: Uint8Array }>;\n};\n\nexport type AwsKmsCommands = {\n EncryptCommand: new (input: any) => unknown;\n DecryptCommand: new (input: any) => unknown;\n};\n\ntype AwsKmsModule = AwsKmsCommands & { KMSClient: new () => AwsKmsClientLike };\n\n/** Wraps DEKs with an AWS KMS symmetric key. kid is `aws-kms:<keyId>`. */\nexport class AwsKmsKeyProvider implements KeyProvider {\n readonly currentKeyId: string;\n readonly #keyId: string;\n #client: AwsKmsClientLike | undefined;\n #commands: AwsKmsCommands | undefined;\n #sdk: Promise<AwsKmsModule> | undefined;\n\n /**\n * AWS SDK v3 `send` needs real Command instances, so the SDK is loaded\n * lazily via loadPeer only when `client` or `commands` is not injected.\n * Inject both (e.g. in tests) to avoid loading it at all.\n */\n constructor(opts: {\n keyId: string;\n client?: AwsKmsClientLike;\n commands?: AwsKmsCommands;\n }) {\n this.#keyId = opts.keyId;\n this.currentKeyId = PREFIX + opts.keyId;\n this.#client = opts.client;\n this.#commands = opts.commands;\n }\n\n async #load(): Promise<{\n sdk: AwsKmsCommands;\n client: AwsKmsClientLike;\n }> {\n if (this.#client && this.#commands) {\n return { sdk: this.#commands, client: this.#client };\n }\n this.#sdk ??= loadPeer<AwsKmsModule>(\n \"@aws-sdk/client-kms\",\n \"@aws-sdk/client-kms\",\n ).catch((err) => {\n this.#sdk = undefined;\n throw err;\n });\n const sdk = await this.#sdk;\n this.#commands ??= sdk;\n this.#client ??= new sdk.KMSClient();\n return { sdk: this.#commands, client: this.#client };\n }\n\n async wrap(\n dek: Uint8Array,\n aad: string,\n ): Promise<{ kid: string; wdek: Uint8Array }> {\n const { sdk, client } = await this.#load();\n let res: { CiphertextBlob?: Uint8Array };\n try {\n res = await client.send(\n new sdk.EncryptCommand({\n KeyId: this.#keyId,\n Plaintext: dek,\n EncryptionContext: { [CONTEXT_KEY]: aad },\n }),\n );\n } catch (err) {\n throw mapKmsError(err);\n }\n if (!res?.CiphertextBlob || res.CiphertextBlob.length === 0) {\n throw new CredentialIntegrityError();\n }\n return { kid: this.currentKeyId, wdek: res.CiphertextBlob };\n }\n\n async unwrap(\n kid: string,\n wdek: Uint8Array,\n aad: string,\n ): Promise<Uint8Array> {\n if (!kid.startsWith(PREFIX) || kid.length === PREFIX.length) {\n throw new CredentialIntegrityError();\n }\n const { sdk, client } = await this.#load();\n let res: { Plaintext?: Uint8Array };\n try {\n res = await client.send(\n new sdk.DecryptCommand({\n // KeyId makes a wrong-key ciphertext fail closed.\n KeyId: kid.slice(PREFIX.length),\n CiphertextBlob: wdek,\n EncryptionContext: { [CONTEXT_KEY]: aad },\n }),\n );\n } catch (err) {\n throw mapKmsError(err);\n }\n if (!res?.Plaintext || res.Plaintext.length === 0) {\n throw new CredentialIntegrityError();\n }\n // Return the response buffer itself: the caller zeroes what it receives.\n return res.Plaintext;\n }\n}\n","import { buildAad, decryptValue, rewrapValue } from \"./crypto/envelope.js\";\nimport type { KeyProvider } from \"./crypto/key-provider.js\";\nimport { GoogleLibError } from \"./errors.js\";\nimport type { CredentialStore } from \"./store.js\";\nimport type { EncryptedValueRef } from \"./types.js\";\n\nconst DEFAULT_BATCH_SIZE = 100;\n\nexport type OpsFailure = { record: string; error: string };\n\nconst label = (ref: EncryptedValueRef): string =>\n `${ref.record}:${ref.recordId}.${ref.field}`;\n\nconst aadOf = (ref: EncryptedValueRef): string =>\n buildAad({\n tenantId: ref.tenantId,\n record: ref.record,\n recordId: ref.recordId,\n field: ref.field,\n });\n\n/** Error code only: never a message, cause, or plaintext. */\nconst codeOf = (err: unknown): string =>\n err instanceof GoogleLibError ? err.code : \"unknown\";\n\n/**\n * Re-wraps every stored DEK under the provider's current key. Idempotent and\n * resumable: values already on the current key (or outside `fromKeyId`) are skipped.\n */\nexport async function rewrapAll(opts: {\n store: CredentialStore;\n keyProvider: KeyProvider;\n fromKeyId?: string;\n batchSize?: number;\n}): Promise<{ rewrapped: number; skipped: number; failed: OpsFailure[] }> {\n const { store, keyProvider, fromKeyId } = opts;\n const result = {\n rewrapped: 0,\n skipped: 0,\n failed: [] as OpsFailure[],\n };\n for await (const ref of store.iterateEncryptedValues(\n opts.batchSize ?? DEFAULT_BATCH_SIZE,\n )) {\n if (\n ref.value.kid === keyProvider.currentKeyId ||\n (fromKeyId !== undefined && ref.value.kid !== fromKeyId)\n ) {\n result.skipped++;\n continue;\n }\n try {\n const next = await rewrapValue(ref.value, aadOf(ref), keyProvider);\n // A CAS miss means a concurrent writer changed it; a rerun will pick it up.\n if (await store.replaceEncryptedValue(ref, next)) result.rewrapped++;\n else result.skipped++;\n } catch (err) {\n result.failed.push({ record: label(ref), error: codeOf(err) });\n }\n }\n return result;\n}\n\n/** Fully decrypts every stored value (plaintext discarded immediately) to prove integrity. */\nexport async function verifyAll(opts: {\n store: CredentialStore;\n keyProvider: KeyProvider;\n batchSize?: number;\n}): Promise<{ ok: number; failed: OpsFailure[] }> {\n const result = { ok: 0, failed: [] as OpsFailure[] };\n for await (const ref of opts.store.iterateEncryptedValues(\n opts.batchSize ?? DEFAULT_BATCH_SIZE,\n )) {\n try {\n await decryptValue(ref.value, aadOf(ref), opts.keyProvider);\n result.ok++;\n } catch (err) {\n result.failed.push({ record: label(ref), error: codeOf(err) });\n }\n }\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,IAAM,YAAY,oBAAI,IAAI;AAAA,EACxB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAED,IAAM,aAAa,oBAAI,IAAI,CAAC,GAAG,GAAG,EAAE,CAAC;AAG9B,SAAS,uBAAuB,KAAuB;AAC5D,MAAI,OAAO,QAAQ,YAAY,QAAQ,KAAM,QAAO;AACpD,QAAM,IAAI;AAKV,MAAI,OAAO,EAAE,SAAS,YAAY,UAAU,IAAI,EAAE,IAAI,EAAG,QAAO;AAChE,MAAI,OAAO,EAAE,SAAS,YAAY,WAAW,IAAI,EAAE,IAAI,EAAG,QAAO;AACjE,MAAI,EAAE,SAAS,yBAAyB,EAAE,SAAS,gBAAgB;AACjE,WAAO;AAAA,EACT;AACA,QAAM,SAAS,EAAE,WAAW;AAC5B,SAAO,OAAO,WAAW,YAAY,UAAU;AACjD;AAGO,SAAS,YAAY,KAAqB;AAC/C,SAAO,uBAAuB,GAAG,IAC7B,IAAI,4BAA4B,QAAW,EAAE,OAAO,IAAI,CAAC,IACzD,IAAI,yBAAyB,QAAW,EAAE,OAAO,IAAI,CAAC;AAC5D;;;AChCA,IAAM,SAAS;AAgBR,IAAM,oBAAN,MAA+C;AAAA,EAC3C;AAAA,EACA;AAAA,EACT;AAAA,EACA;AAAA,EAEA,YAAY,MAAsD;AAChE,SAAK,WAAW,KAAK;AACrB,SAAK,eAAe,SAAS,KAAK;AAClC,S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ACX,SAAS;AAAA,IACT,QAAQ,CAAC;AAAA,EACX;AACA,mBAAiB,OAAO,MAAM;AAAA,IAC5B,KAAK,aAAa;AAAA,EACpB,GAAG;AACD,QACE,IAAI,MAAM,QAAQ,YAAY,gBAC7B,cAAc,UAAa,IAAI,MAAM,QAAQ,WAC9C;AACA,aAAO;AACP;AAAA,IACF;AACA,QAAI;AACF,YAAM,OAAO,MAAM,YAAY,IAAI,OAAO,MAAM,GAAG,GAAG,WAAW;AAEjE,UAAI,MAAM,MAAM,sBAAsB,KAAK,IAAI,EAAG,QAAO;AAAA,UACpD,QAAO;AAAA,IACd,SAAS,KAAK;AACZ,aAAO,OAAO,KAAK,EAAE,QAAQ,MAAM,GAAG,GAAG,OAAO,OAAO,GAAG,EAAE,CAAC;AAAA,IAC/D;AAAA,EACF;AACA,SAAO;AACT;AAGA,eAAsB,UAAU,MAIkB;AAChD,QAAM,SAAS,EAAE,IAAI,GAAG,QAAQ,CAAC,EAAkB;AACnD,mBAAiB,OAAO,KAAK,MAAM;AAAA,IACjC,KAAK,aAAa;AAAA,EACpB,GAAG;AACD,QAAI;AACF,YAAM,aAAa,IAAI,OAAO,MAAM,GAAG,GAAG,KAAK,WAAW;AAC1D,aAAO;AAAA,IACT,SAAS,KAAK;AACZ,aAAO,OAAO,KAAK,EAAE,QAAQ,MAAM,GAAG,GAAG,OAAO,OAAO,GAAG,EAAE,CAAC;AAAA,IAC/D;AAAA,EACF;AACA,SAAO;AACT;","names":["PREFIX"]}
@@ -1,5 +1,5 @@
1
1
  import { K as KeyProvider, O as OAuthGateway } from './key-provider-Cq_14Bh6.cjs';
2
- import { a as ConnectionRecord, c as ConnectionView, C as CredentialStore, G as GoogleEvent, L as Logger, f as Emit } from './events-BsWOMtza.cjs';
2
+ import { a as ConnectionRecord, c as ConnectionView, C as CredentialStore, f as Emit, L as Logger, G as GoogleEvent } from './events-BlC10ISp.cjs';
3
3
 
4
4
  type TokenManager = {
5
5
  getAccessToken(tenantId: string, connectionId: string, opts?: {
@@ -32,6 +32,7 @@ type ClientsApi = {
32
32
  declare const BASE_SCOPES: readonly string[];
33
33
  declare const SERVICE_SCOPES: {
34
34
  readonly gmail: readonly ["https://www.googleapis.com/auth/gmail.send"];
35
+ readonly calendar: readonly ["https://www.googleapis.com/auth/calendar.events.owned", "https://www.googleapis.com/auth/calendar.events.freebusy"];
35
36
  };
36
37
  type GoogleService = keyof typeof SERVICE_SCOPES;
37
38
  /** Base scopes plus every requested service's scopes, de-duplicated. */
@@ -1,5 +1,5 @@
1
1
  import { K as KeyProvider, O as OAuthGateway } from './key-provider-Cq_14Bh6.js';
2
- import { a as ConnectionRecord, c as ConnectionView, C as CredentialStore, G as GoogleEvent, L as Logger, f as Emit } from './events-BsWOMtza.js';
2
+ import { a as ConnectionRecord, c as ConnectionView, C as CredentialStore, f as Emit, L as Logger, G as GoogleEvent } from './events-BlC10ISp.js';
3
3
 
4
4
  type TokenManager = {
5
5
  getAccessToken(tenantId: string, connectionId: string, opts?: {
@@ -32,6 +32,7 @@ type ClientsApi = {
32
32
  declare const BASE_SCOPES: readonly string[];
33
33
  declare const SERVICE_SCOPES: {
34
34
  readonly gmail: readonly ["https://www.googleapis.com/auth/gmail.send"];
35
+ readonly calendar: readonly ["https://www.googleapis.com/auth/calendar.events.owned", "https://www.googleapis.com/auth/calendar.events.freebusy"];
35
36
  };
36
37
  type GoogleService = keyof typeof SERVICE_SCOPES;
37
38
  /** Base scopes plus every requested service's scopes, de-duplicated. */
@@ -152,6 +152,37 @@ type GoogleEvent = {
152
152
  bcc: string[];
153
153
  subject: string;
154
154
  at: Date;
155
+ } | {
156
+ type: "calendar_event.created" | "calendar_event.cancelled";
157
+ tenantId: string;
158
+ actorId: string;
159
+ connectionId: string;
160
+ eventId: string;
161
+ attendees: string[];
162
+ title: string;
163
+ start: Date;
164
+ end: Date;
165
+ at: Date;
166
+ } | {
167
+ type: "calendar_event.updated";
168
+ tenantId: string;
169
+ actorId: string;
170
+ connectionId: string;
171
+ eventId: string;
172
+ attendees: string[];
173
+ title: string;
174
+ start: Date;
175
+ end: Date;
176
+ changed: string[];
177
+ at: Date;
178
+ } | {
179
+ type: "calendar_event.failed";
180
+ tenantId: string;
181
+ actorId: string;
182
+ connectionId: string;
183
+ operation: "create" | "update" | "cancel";
184
+ errorCode: string;
185
+ at: Date;
155
186
  };
156
187
  type Emit = (e: GoogleEvent, perCall?: {
157
188
  redactRecipients?: boolean;
@@ -152,6 +152,37 @@ type GoogleEvent = {
152
152
  bcc: string[];
153
153
  subject: string;
154
154
  at: Date;
155
+ } | {
156
+ type: "calendar_event.created" | "calendar_event.cancelled";
157
+ tenantId: string;
158
+ actorId: string;
159
+ connectionId: string;
160
+ eventId: string;
161
+ attendees: string[];
162
+ title: string;
163
+ start: Date;
164
+ end: Date;
165
+ at: Date;
166
+ } | {
167
+ type: "calendar_event.updated";
168
+ tenantId: string;
169
+ actorId: string;
170
+ connectionId: string;
171
+ eventId: string;
172
+ attendees: string[];
173
+ title: string;
174
+ start: Date;
175
+ end: Date;
176
+ changed: string[];
177
+ at: Date;
178
+ } | {
179
+ type: "calendar_event.failed";
180
+ tenantId: string;
181
+ actorId: string;
182
+ connectionId: string;
183
+ operation: "create" | "update" | "cancel";
184
+ errorCode: string;
185
+ at: Date;
155
186
  };
156
187
  type Emit = (e: GoogleEvent, perCall?: {
157
188
  redactRecipients?: boolean;
package/dist/gmail.cjs CHANGED
@@ -2,20 +2,29 @@
2
2
 
3
3
 
4
4
 
5
- var _chunkVN5VWVCTcjs = require('./chunk-VN5VWVCT.cjs');
6
5
 
7
6
 
8
- var _chunkV22QP2AMcjs = require('./chunk-V22QP2AM.cjs');
9
7
 
10
8
 
9
+ var _chunkS357VL5Vcjs = require('./chunk-S357VL5V.cjs');
11
10
 
12
11
 
13
12
 
14
13
 
14
+ var _chunkDPAPYMB3cjs = require('./chunk-DPAPYMB3.cjs');
15
15
 
16
16
 
17
+ var _chunkJDA3ZRUYcjs = require('./chunk-JDA3ZRUY.cjs');
17
18
 
18
- var _chunkSHDP4A3Acjs = require('./chunk-SHDP4A3A.cjs');
19
+
20
+
21
+
22
+
23
+
24
+
25
+
26
+
27
+ var _chunkJZVDD4DLcjs = require('./chunk-JZVDD4DL.cjs');
19
28
 
20
29
  // src/gmail/mime.ts
21
30
  var _crypto = require('crypto');
@@ -35,7 +44,7 @@ async function readLimited(stream, alreadyCounted) {
35
44
  const buf = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
36
45
  total += buf.length;
37
46
  if (total > MAX_ATTACHMENT_BYTES) {
38
- throw new (0, _chunkSHDP4A3Acjs.MessageTooLargeError)(total, MAX_ATTACHMENT_BYTES);
47
+ throw new (0, _chunkJZVDD4DLcjs.MessageTooLargeError)(total, MAX_ATTACHMENT_BYTES);
39
48
  }
40
49
  chunks.push(buf);
41
50
  }
@@ -52,13 +61,13 @@ async function buildMime(msg, from) {
52
61
  if (Buffer.isBuffer(a.content)) total += a.content.length;
53
62
  }
54
63
  if (total > MAX_ATTACHMENT_BYTES) {
55
- throw new (0, _chunkSHDP4A3Acjs.MessageTooLargeError)(total, MAX_ATTACHMENT_BYTES);
64
+ throw new (0, _chunkJZVDD4DLcjs.MessageTooLargeError)(total, MAX_ATTACHMENT_BYTES);
56
65
  }
57
66
  const htmlToText = msg.text === null && msg.html !== null ? unwrap(
58
- await _chunkV22QP2AMcjs.loadPeer.call(void 0, "html-to-text", "html-to-text")
67
+ await _chunkJDA3ZRUYcjs.loadPeer.call(void 0, "html-to-text", "html-to-text")
59
68
  ) : null;
60
69
  const MailComposer = unwrap(
61
- await _chunkV22QP2AMcjs.loadPeer.call(void 0,
70
+ await _chunkJDA3ZRUYcjs.loadPeer.call(void 0,
62
71
  "nodemailer/lib/mail-composer/index.js",
63
72
  "nodemailer"
64
73
  )
@@ -126,78 +135,50 @@ var OUTCOME_UNKNOWN_CODES = /* @__PURE__ */ new Set([
126
135
  "ESOCKETTIMEDOUT"
127
136
  ]);
128
137
  var RATE_REASONS = /* @__PURE__ */ new Set(["rateLimitExceeded", "userRateLimitExceeded"]);
129
- var asErr = (err) => typeof err === "object" && err !== null ? err : {};
130
- function readStatus(e) {
131
- const s = _nullishCoalesce(_nullishCoalesce(_optionalChain([e, 'access', _6 => _6.response, 'optionalAccess', _7 => _7.status]), () => ( e.status)), () => ( e.code));
132
- return typeof s === "number" ? s : null;
133
- }
134
- function readReason(e) {
135
- const r = _nullishCoalesce(_optionalChain([e, 'access', _8 => _8.response, 'optionalAccess', _9 => _9.data, 'optionalAccess', _10 => _10.error, 'optionalAccess', _11 => _11.errors, 'optionalAccess', _12 => _12[0], 'optionalAccess', _13 => _13.reason]), () => ( _optionalChain([e, 'access', _14 => _14.errors, 'optionalAccess', _15 => _15[0], 'optionalAccess', _16 => _16.reason])));
136
- return typeof r === "string" ? r : null;
137
- }
138
- function readNetCode(e) {
139
- const c = _nullishCoalesce(e.code, () => ( _optionalChain([e, 'access', _17 => _17.cause, 'optionalAccess', _18 => _18.code])));
140
- return typeof c === "string" ? c : null;
141
- }
142
- function readMessages(e) {
143
- const a = typeof e.message === "string" ? e.message : "";
144
- const b = _optionalChain([e, 'access', _19 => _19.response, 'optionalAccess', _20 => _20.data, 'optionalAccess', _21 => _21.error, 'optionalAccess', _22 => _22.message]);
145
- return `${a} ${typeof b === "string" ? b : ""}`;
146
- }
147
- function readRetryAfterMs(e) {
148
- const raw = _optionalChain([e, 'access', _23 => _23.response, 'optionalAccess', _24 => _24.headers, 'optionalAccess', _25 => _25["retry-after"]]);
149
- const v = Array.isArray(raw) ? raw[0] : raw;
150
- if (typeof v !== "string" && typeof v !== "number") return null;
151
- const s = String(v).trim();
152
- if (s === "") return null;
153
- if (/^\d+(\.\d+)?$/.test(s)) return Math.round(Number(s) * 1e3);
154
- const at = Date.parse(s);
155
- return Number.isNaN(at) ? null : Math.max(0, at - Date.now());
156
- }
157
138
  function classifySendError(err) {
158
- if (err instanceof _chunkSHDP4A3Acjs.GoogleLibError) return { kind: "fail", error: err };
159
- const e = asErr(err);
160
- const status = readStatus(e);
161
- const reason = readReason(e);
162
- const code = readNetCode(e);
139
+ if (err instanceof _chunkJZVDD4DLcjs.GoogleLibError) return { kind: "fail", error: err };
140
+ const e = _chunkS357VL5Vcjs.asErr.call(void 0, err);
141
+ const status = _chunkS357VL5Vcjs.readStatus.call(void 0, e);
142
+ const reason = _chunkS357VL5Vcjs.readReason.call(void 0, e);
143
+ const code = _chunkS357VL5Vcjs.readNetCode.call(void 0, e);
163
144
  const opts = { cause: err };
164
- if (reason === "dailyLimitExceeded" || /sending limit/i.test(readMessages(e))) {
145
+ if (reason === "dailyLimitExceeded" || /sending limit/i.test(_chunkS357VL5Vcjs.readMessages.call(void 0, e))) {
165
146
  return {
166
147
  kind: "fail",
167
- error: new (0, _chunkSHDP4A3Acjs.DailyQuotaExceededError)(void 0, opts)
148
+ error: new (0, _chunkJZVDD4DLcjs.DailyQuotaExceededError)(void 0, opts)
168
149
  };
169
150
  }
170
151
  if (status === 429 || status === 403 && reason !== null && RATE_REASONS.has(reason)) {
171
- return { kind: "retry", delayMs: readRetryAfterMs(e) };
152
+ return { kind: "retry", delayMs: _chunkS357VL5Vcjs.readRetryAfterMs.call(void 0, e) };
172
153
  }
173
154
  if (status === 401) return { kind: "unauthorized" };
174
155
  if (status === 400) {
175
156
  return {
176
157
  kind: "fail",
177
- error: new (0, _chunkSHDP4A3Acjs.InvalidMessageError)("message", void 0, opts)
158
+ error: new (0, _chunkJZVDD4DLcjs.InvalidMessageError)("message", void 0, opts)
178
159
  };
179
160
  }
180
161
  if (status !== null && status >= 500) {
181
162
  return {
182
163
  kind: "fail",
183
- error: new (0, _chunkSHDP4A3Acjs.SendOutcomeUnknownError)(void 0, opts)
164
+ error: new (0, _chunkJZVDD4DLcjs.SendOutcomeUnknownError)(void 0, opts)
184
165
  };
185
166
  }
186
167
  if (code !== null && (PRE_SEND_CODES.has(code) || code.startsWith("ERR_TLS_") || code.startsWith("CERT_"))) {
187
168
  return { kind: "retry", delayMs: null };
188
169
  }
189
- if (code !== null && OUTCOME_UNKNOWN_CODES.has(code) || code === "ABORT_ERR" || e.name === "AbortError" || /socket hang up/i.test(readMessages(e))) {
170
+ if (code !== null && OUTCOME_UNKNOWN_CODES.has(code) || code === "ABORT_ERR" || e.name === "AbortError" || /socket hang up/i.test(_chunkS357VL5Vcjs.readMessages.call(void 0, e))) {
190
171
  return {
191
172
  kind: "fail",
192
- error: new (0, _chunkSHDP4A3Acjs.SendOutcomeUnknownError)(void 0, opts)
173
+ error: new (0, _chunkJZVDD4DLcjs.SendOutcomeUnknownError)(void 0, opts)
193
174
  };
194
175
  }
195
176
  if (status !== null) {
196
- return { kind: "fail", error: new (0, _chunkSHDP4A3Acjs.GoogleApiError)(status, reason, opts) };
177
+ return { kind: "fail", error: new (0, _chunkJZVDD4DLcjs.GoogleApiError)(status, reason, opts) };
197
178
  }
198
179
  return {
199
180
  kind: "fail",
200
- error: new (0, _chunkSHDP4A3Acjs.SendOutcomeUnknownError)(void 0, opts)
181
+ error: new (0, _chunkJZVDD4DLcjs.SendOutcomeUnknownError)(void 0, opts)
201
182
  };
202
183
  }
203
184
  var defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
@@ -215,14 +196,14 @@ async function withSendRetry(fn, opts = {}) {
215
196
  if (c.kind === "fail") throw c.error;
216
197
  if (c.kind === "unauthorized") throw new SendUnauthorizedSignal();
217
198
  if (c.delayMs !== null && c.delayMs > capMs) {
218
- throw new (0, _chunkSHDP4A3Acjs.RateLimitedError)(c.delayMs, { cause: err });
199
+ throw new (0, _chunkJZVDD4DLcjs.RateLimitedError)(c.delayMs, { cause: err });
219
200
  }
220
201
  if (attempt + 1 >= maxAttempts) {
221
- const e = asErr(err);
222
- if (readStatus(e) !== null) {
223
- throw new (0, _chunkSHDP4A3Acjs.RateLimitedError)(c.delayMs, { cause: err });
202
+ const e = _chunkS357VL5Vcjs.asErr.call(void 0, err);
203
+ if (_chunkS357VL5Vcjs.readStatus.call(void 0, e) !== null) {
204
+ throw new (0, _chunkJZVDD4DLcjs.RateLimitedError)(c.delayMs, { cause: err });
224
205
  }
225
- throw new (0, _chunkSHDP4A3Acjs.GoogleApiError)(0, readNetCode(e), { cause: err });
206
+ throw new (0, _chunkJZVDD4DLcjs.GoogleApiError)(0, _chunkS357VL5Vcjs.readNetCode.call(void 0, e), { cause: err });
226
207
  }
227
208
  await sleep(
228
209
  _nullishCoalesce(c.delayMs, () => ( random() * Math.min(capMs, baseMs * 2 ** attempt)))
@@ -238,7 +219,7 @@ var UPLOAD_THRESHOLD_BYTES = 5242880;
238
219
  function createGmailApiTransport() {
239
220
  return {
240
221
  async send({ accessToken, raw, threadId }) {
241
- const mod = await _chunkV22QP2AMcjs.loadPeer.call(void 0, "@googleapis/gmail");
222
+ const mod = await _chunkJDA3ZRUYcjs.loadPeer.call(void 0, "@googleapis/gmail");
242
223
  const { gmail } = mod.gmail ? mod : mod.default;
243
224
  const auth = new (0, _googleauthlibrary.OAuth2Client)();
244
225
  auth.setCredentials({ access_token: accessToken });
@@ -252,7 +233,7 @@ function createGmailApiTransport() {
252
233
  requestBody: { ...thread },
253
234
  media: { mimeType: "message/rfc822", body: _stream.Readable.from(raw) }
254
235
  });
255
- if (!_optionalChain([data, 'optionalAccess', _26 => _26.id])) throw new (0, _chunkSHDP4A3Acjs.SendOutcomeUnknownError)();
236
+ if (!_optionalChain([data, 'optionalAccess', _6 => _6.id])) throw new (0, _chunkJZVDD4DLcjs.SendOutcomeUnknownError)();
256
237
  return {
257
238
  messageId: data.id,
258
239
  threadId: data.threadId || threadId || data.id
@@ -264,14 +245,12 @@ function createGmailApiTransport() {
264
245
  // src/gmail/validate.ts
265
246
  var _path = require('path');
266
247
  var LINE_BREAKS = /[\r\n\0]/;
267
- var ADDRESS_FORBIDDEN = /[\s\u0000-\u001f\u007f-\u009f<>,;"()[\]\\]/;
268
248
  var HEADER_NAME = /^X-[A-Za-z0-9-]+$/;
269
249
  var CONTENT_TYPE = /^[A-Za-z0-9!#$&^_.+-]+\/[A-Za-z0-9!#$&^_.+-]+$/;
270
- var MAX_ADDRESS = 254;
271
250
  var MSG_ID = /^[\x21-\x7e]+$/;
272
251
  var THREAD_ID = /^[A-Za-z0-9_-]+$/;
273
252
  function fail(field) {
274
- throw new (0, _chunkSHDP4A3Acjs.InvalidMessageError)(field);
253
+ throw new (0, _chunkJZVDD4DLcjs.InvalidMessageError)(field);
275
254
  }
276
255
  function clean(value, field) {
277
256
  if (typeof value !== "string" || LINE_BREAKS.test(value)) fail(field);
@@ -282,15 +261,9 @@ function matching(value, pattern, field) {
282
261
  return value;
283
262
  }
284
263
  function parseAddress(raw, field) {
285
- const v = clean(raw, field);
286
- if (v.length > MAX_ADDRESS || ADDRESS_FORBIDDEN.test(v)) fail(field);
287
- const parts = v.split("@");
288
- if (parts.length !== 2) fail(field);
289
- const [local, domain] = parts;
290
- if (!local || !domain.includes(".")) fail(field);
291
- if (domain.startsWith(".") || domain.endsWith(".") || domain.includes(".."))
292
- fail(field);
293
- return `${local}@${domain.toLowerCase()}`;
264
+ const v = _chunkS357VL5Vcjs.normalizeEmail.call(void 0, raw);
265
+ if (v === null) fail(field);
266
+ return v;
294
267
  }
295
268
  function parseMailAddress(a, path) {
296
269
  if (typeof a === "string")
@@ -357,7 +330,7 @@ function validateSendInput(input, opts) {
357
330
  )
358
331
  };
359
332
  return {
360
- fromName: _chunkVN5VWVCTcjs.sanitizeDisplayName.call(void 0, _nullishCoalesce(input.fromName, () => ( null))),
333
+ fromName: _chunkDPAPYMB3cjs.sanitizeDisplayName.call(void 0, _nullishCoalesce(input.fromName, () => ( null))),
361
334
  to,
362
335
  cc,
363
336
  bcc,
@@ -377,10 +350,10 @@ function createGmail(google, opts = {}) {
377
350
  const blocked = _nullishCoalesce(opts.blockedAttachmentExtensions, () => ( []));
378
351
  return {
379
352
  async send(input) {
380
- const { store, tokens, emit, now, logger } = google[_chunkVN5VWVCTcjs.internals];
353
+ const { store, tokens, emit, now, logger } = google[_chunkDPAPYMB3cjs.internals];
381
354
  for (const field of ["tenantId", "connectionId", "actorId"]) {
382
355
  if (typeof input[field] !== "string" || input[field] === "") {
383
- throw new (0, _chunkSHDP4A3Acjs.InvalidMessageError)(field);
356
+ throw new (0, _chunkJZVDD4DLcjs.InvalidMessageError)(field);
384
357
  }
385
358
  }
386
359
  const { tenantId, connectionId, actorId } = input;
@@ -394,7 +367,7 @@ function createGmail(google, opts = {}) {
394
367
  try {
395
368
  const first = await tokens.getAccessToken(tenantId, connectionId);
396
369
  const connection = first.connection;
397
- _chunkVN5VWVCTcjs.assertServiceScopes.call(void 0, connection.scopes, ["gmail"], {
370
+ _chunkDPAPYMB3cjs.assertServiceScopes.call(void 0, connection.scopes, ["gmail"], {
398
371
  tenantId,
399
372
  connectionId
400
373
  });
@@ -431,7 +404,7 @@ function createGmail(google, opts = {}) {
431
404
  reason: "unauthorized",
432
405
  at: now()
433
406
  });
434
- throw new (0, _chunkSHDP4A3Acjs.ConnectionRevokedError)("unauthorized", {
407
+ throw new (0, _chunkJZVDD4DLcjs.ConnectionRevokedError)("unauthorized", {
435
408
  tenantId,
436
409
  connectionId
437
410
  });
@@ -441,7 +414,7 @@ function createGmail(google, opts = {}) {
441
414
  await store.touchConnection(tenantId, connectionId, now());
442
415
  } catch (e2) {
443
416
  try {
444
- _optionalChain([logger, 'optionalAccess', _27 => _27.warn, 'call', _28 => _28("google touchConnection failed")]);
417
+ _optionalChain([logger, 'optionalAccess', _7 => _7.warn, 'call', _8 => _8("google touchConnection failed")]);
445
418
  } catch (e3) {
446
419
  }
447
420
  }
@@ -468,7 +441,7 @@ function createGmail(google, opts = {}) {
468
441
  tenantId,
469
442
  actorId,
470
443
  connectionId,
471
- errorCode: err instanceof _chunkSHDP4A3Acjs.GoogleLibError ? err.code : "unknown",
444
+ errorCode: err instanceof _chunkJZVDD4DLcjs.GoogleLibError ? err.code : "unknown",
472
445
  ...addrs,
473
446
  subject: msg.subject,
474
447
  at: now()