botinabox 2.4.3 → 2.5.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.
- package/LICENSE +21 -21
- package/README.md +190 -190
- package/bin/botinabox.mjs +2 -2
- package/dist/channels/slack/index.d.ts +1 -1
- package/dist/{chat-pipeline-BWrtVqEP.d.ts → chat-pipeline-DuNX5WoL.d.ts} +3 -0
- package/dist/cli.js +0 -0
- package/dist/index.d.ts +5 -2
- package/dist/index.js +59 -22
- package/package.json +100 -99
- package/dist/channels/discord/adapter.d.ts +0 -32
- package/dist/channels/discord/adapter.js +0 -70
- package/dist/channels/discord/inbound.d.ts +0 -25
- package/dist/channels/discord/inbound.js +0 -24
- package/dist/channels/discord/models.d.ts +0 -8
- package/dist/channels/discord/models.js +0 -5
- package/dist/channels/discord/outbound.d.ts +0 -14
- package/dist/channels/discord/outbound.js +0 -38
- package/dist/channels/slack/adapter.d.ts +0 -33
- package/dist/channels/slack/adapter.js +0 -74
- package/dist/channels/slack/inbound.d.ts +0 -59
- package/dist/channels/slack/inbound.js +0 -96
- package/dist/channels/slack/models.d.ts +0 -9
- package/dist/channels/slack/models.js +0 -5
- package/dist/channels/slack/outbound.d.ts +0 -12
- package/dist/channels/slack/outbound.js +0 -18
- package/dist/channels/slack/transcribe.d.ts +0 -41
- package/dist/channels/slack/transcribe.js +0 -106
- package/dist/channels/webhook/adapter.d.ts +0 -23
- package/dist/channels/webhook/adapter.js +0 -86
- package/dist/channels/webhook/hmac.d.ts +0 -13
- package/dist/channels/webhook/hmac.js +0 -26
- package/dist/channels/webhook/models.d.ts +0 -9
- package/dist/channels/webhook/models.js +0 -5
- package/dist/channels/webhook/server.d.ts +0 -20
- package/dist/channels/webhook/server.js +0 -91
- package/dist/chat-pipeline-C-XlLGNl.d.ts +0 -648
- package/dist/chat-pipeline-CR1KF6eX.d.ts +0 -652
- package/dist/chat-pipeline-DisuC8SB.d.ts +0 -643
- package/dist/chunk-2LGXQPEA.js +0 -41
- package/dist/chunk-3X3YKI4T.js +0 -357
- package/dist/chunk-D47AIFOD.js +0 -351
- package/dist/chunk-DSNJKNEW.js +0 -328
- package/dist/chunk-GS2JFL6I.js +0 -144
- package/dist/chunk-J6S6QMUY.js +0 -144
- package/dist/chunk-QLA6YOFN.js +0 -22
- package/dist/chunk-UACT2WXX.js +0 -381
- package/dist/cli/templates/config.yml.d.ts +0 -7
- package/dist/cli/templates/config.yml.js +0 -61
- package/dist/cli/templates/env.d.ts +0 -1
- package/dist/cli/templates/env.js +0 -30
- package/dist/cli/templates/index.ts.d.ts +0 -2
- package/dist/cli/templates/index.ts.js +0 -30
- package/dist/cli/templates/package.json.d.ts +0 -5
- package/dist/cli/templates/package.json.js +0 -28
- package/dist/connector-DDahQw-2.d.ts +0 -63
- package/dist/connectors/google/calendar-connector.d.ts +0 -40
- package/dist/connectors/google/calendar-connector.js +0 -243
- package/dist/connectors/google/gmail-connector.d.ts +0 -42
- package/dist/connectors/google/gmail-connector.js +0 -345
- package/dist/connectors/google/oauth.d.ts +0 -48
- package/dist/connectors/google/oauth.js +0 -112
- package/dist/connectors/google/types.d.ts +0 -78
- package/dist/connectors/google/types.js +0 -2
- package/dist/core/chat/auto-discovery.d.ts +0 -16
- package/dist/core/chat/auto-discovery.js +0 -54
- package/dist/core/chat/channel-registry.d.ts +0 -45
- package/dist/core/chat/channel-registry.js +0 -96
- package/dist/core/chat/chat-pipeline.d.ts +0 -113
- package/dist/core/chat/chat-pipeline.js +0 -395
- package/dist/core/chat/chat-responder.d.ts +0 -90
- package/dist/core/chat/chat-responder.js +0 -185
- package/dist/core/chat/formatter.d.ts +0 -11
- package/dist/core/chat/formatter.js +0 -60
- package/dist/core/chat/index.d.ts +0 -24
- package/dist/core/chat/index.js +0 -18
- package/dist/core/chat/message-interpreter.d.ts +0 -91
- package/dist/core/chat/message-interpreter.js +0 -166
- package/dist/core/chat/message-store.d.ts +0 -66
- package/dist/core/chat/message-store.js +0 -131
- package/dist/core/chat/notification-queue.d.ts +0 -34
- package/dist/core/chat/notification-queue.js +0 -111
- package/dist/core/chat/pipeline.d.ts +0 -38
- package/dist/core/chat/pipeline.js +0 -89
- package/dist/core/chat/policies.d.ts +0 -16
- package/dist/core/chat/policies.js +0 -25
- package/dist/core/chat/routing.d.ts +0 -17
- package/dist/core/chat/routing.js +0 -36
- package/dist/core/chat/session-key.d.ts +0 -30
- package/dist/core/chat/session-key.js +0 -65
- package/dist/core/chat/session-manager.d.ts +0 -17
- package/dist/core/chat/session-manager.js +0 -23
- package/dist/core/chat/text-chunker.d.ts +0 -9
- package/dist/core/chat/text-chunker.js +0 -48
- package/dist/core/chat/triage-router.d.ts +0 -75
- package/dist/core/chat/triage-router.js +0 -142
- package/dist/core/chat/types.d.ts +0 -5
- package/dist/core/chat/types.js +0 -5
- package/dist/core/config/defaults.d.ts +0 -2
- package/dist/core/config/defaults.js +0 -38
- package/dist/core/config/index.d.ts +0 -6
- package/dist/core/config/index.js +0 -4
- package/dist/core/config/interpolate.d.ts +0 -5
- package/dist/core/config/interpolate.js +0 -27
- package/dist/core/config/loader.d.ts +0 -24
- package/dist/core/config/loader.js +0 -59
- package/dist/core/config/schema.d.ts +0 -5
- package/dist/core/config/schema.js +0 -119
- package/dist/core/data/core-entity-contexts.d.ts +0 -14
- package/dist/core/data/core-entity-contexts.js +0 -197
- package/dist/core/data/core-migrations.d.ts +0 -5
- package/dist/core/data/core-migrations.js +0 -45
- package/dist/core/data/core-schema.d.ts +0 -6
- package/dist/core/data/core-schema.js +0 -454
- package/dist/core/data/data-store.d.ts +0 -67
- package/dist/core/data/data-store.js +0 -218
- package/dist/core/data/domain-entity-contexts.d.ts +0 -29
- package/dist/core/data/domain-entity-contexts.js +0 -321
- package/dist/core/data/domain-schema.d.ts +0 -36
- package/dist/core/data/domain-schema.js +0 -323
- package/dist/core/data/index.d.ts +0 -7
- package/dist/core/data/index.js +0 -7
- package/dist/core/data/types.d.ts +0 -111
- package/dist/core/data/types.js +0 -1
- package/dist/core/hooks/hook-bus.d.ts +0 -18
- package/dist/core/hooks/hook-bus.js +0 -120
- package/dist/core/hooks/index.d.ts +0 -2
- package/dist/core/hooks/index.js +0 -1
- package/dist/core/hooks/types.d.ts +0 -19
- package/dist/core/hooks/types.js +0 -1
- package/dist/core/index.d.ts +0 -4
- package/dist/core/index.js +0 -4
- package/dist/core/llm/auto-discovery.d.ts +0 -11
- package/dist/core/llm/auto-discovery.js +0 -49
- package/dist/core/llm/cost-tracker.d.ts +0 -6
- package/dist/core/llm/cost-tracker.js +0 -38
- package/dist/core/llm/index.d.ts +0 -4
- package/dist/core/llm/index.js +0 -3
- package/dist/core/llm/model-router.d.ts +0 -25
- package/dist/core/llm/model-router.js +0 -49
- package/dist/core/llm/provider-registry.d.ts +0 -9
- package/dist/core/llm/provider-registry.js +0 -25
- package/dist/core/llm/types.d.ts +0 -2
- package/dist/core/llm/types.js +0 -2
- package/dist/core/orchestrator/adapters/api-adapter.d.ts +0 -34
- package/dist/core/orchestrator/adapters/api-adapter.js +0 -88
- package/dist/core/orchestrator/adapters/cli-adapter.d.ts +0 -22
- package/dist/core/orchestrator/adapters/cli-adapter.js +0 -69
- package/dist/core/orchestrator/adapters/deterministic-adapter.d.ts +0 -35
- package/dist/core/orchestrator/adapters/deterministic-adapter.js +0 -75
- package/dist/core/orchestrator/adapters/env-whitelist.d.ts +0 -4
- package/dist/core/orchestrator/adapters/env-whitelist.js +0 -27
- package/dist/core/orchestrator/adapters/output-extractor.d.ts +0 -11
- package/dist/core/orchestrator/adapters/output-extractor.js +0 -59
- package/dist/core/orchestrator/adapters/process-manager.d.ts +0 -15
- package/dist/core/orchestrator/adapters/process-manager.js +0 -26
- package/dist/core/orchestrator/adapters/tool-loop.d.ts +0 -22
- package/dist/core/orchestrator/adapters/tool-loop.js +0 -66
- package/dist/core/orchestrator/agent-registry.d.ts +0 -31
- package/dist/core/orchestrator/agent-registry.js +0 -135
- package/dist/core/orchestrator/budget-controller.d.ts +0 -19
- package/dist/core/orchestrator/budget-controller.js +0 -73
- package/dist/core/orchestrator/chain-guard.d.ts +0 -14
- package/dist/core/orchestrator/chain-guard.js +0 -23
- package/dist/core/orchestrator/circuit-breaker.d.ts +0 -65
- package/dist/core/orchestrator/circuit-breaker.js +0 -159
- package/dist/core/orchestrator/claude-stream-parser.d.ts +0 -31
- package/dist/core/orchestrator/claude-stream-parser.js +0 -99
- package/dist/core/orchestrator/config-revisions.d.ts +0 -6
- package/dist/core/orchestrator/config-revisions.js +0 -17
- package/dist/core/orchestrator/dependency-resolver.d.ts +0 -20
- package/dist/core/orchestrator/dependency-resolver.js +0 -78
- package/dist/core/orchestrator/governance-gate.d.ts +0 -110
- package/dist/core/orchestrator/governance-gate.js +0 -170
- package/dist/core/orchestrator/learning-pipeline.d.ts +0 -109
- package/dist/core/orchestrator/learning-pipeline.js +0 -249
- package/dist/core/orchestrator/loop-detector.d.ts +0 -51
- package/dist/core/orchestrator/loop-detector.js +0 -133
- package/dist/core/orchestrator/ndjson-logger.d.ts +0 -6
- package/dist/core/orchestrator/ndjson-logger.js +0 -18
- package/dist/core/orchestrator/permission-relay.d.ts +0 -72
- package/dist/core/orchestrator/permission-relay.js +0 -164
- package/dist/core/orchestrator/run-manager.d.ts +0 -31
- package/dist/core/orchestrator/run-manager.js +0 -178
- package/dist/core/orchestrator/scheduler.d.ts +0 -70
- package/dist/core/orchestrator/scheduler.js +0 -198
- package/dist/core/orchestrator/secret-store.d.ts +0 -57
- package/dist/core/orchestrator/secret-store.js +0 -171
- package/dist/core/orchestrator/session-manager.d.ts +0 -13
- package/dist/core/orchestrator/session-manager.js +0 -66
- package/dist/core/orchestrator/task-queue.d.ts +0 -34
- package/dist/core/orchestrator/task-queue.js +0 -83
- package/dist/core/orchestrator/template-interpolate.d.ts +0 -5
- package/dist/core/orchestrator/template-interpolate.js +0 -18
- package/dist/core/orchestrator/user-registry.d.ts +0 -47
- package/dist/core/orchestrator/user-registry.js +0 -76
- package/dist/core/orchestrator/wakeup-queue.d.ts +0 -9
- package/dist/core/orchestrator/wakeup-queue.js +0 -45
- package/dist/core/orchestrator/workflow-engine.d.ts +0 -47
- package/dist/core/orchestrator/workflow-engine.js +0 -204
- package/dist/core/security/audit.d.ts +0 -20
- package/dist/core/security/audit.js +0 -33
- package/dist/core/security/column-validator.d.ts +0 -20
- package/dist/core/security/column-validator.js +0 -37
- package/dist/core/security/index.d.ts +0 -5
- package/dist/core/security/index.js +0 -5
- package/dist/core/security/process-env.d.ts +0 -13
- package/dist/core/security/process-env.js +0 -49
- package/dist/core/security/sanitizer.d.ts +0 -11
- package/dist/core/security/sanitizer.js +0 -39
- package/dist/core/security/types.d.ts +0 -11
- package/dist/core/security/types.js +0 -1
- package/dist/core/update/auto-update.d.ts +0 -21
- package/dist/core/update/auto-update.js +0 -102
- package/dist/core/update/backup-manager.d.ts +0 -7
- package/dist/core/update/backup-manager.js +0 -24
- package/dist/core/update/index.d.ts +0 -8
- package/dist/core/update/index.js +0 -6
- package/dist/core/update/migration-hooks.d.ts +0 -11
- package/dist/core/update/migration-hooks.js +0 -10
- package/dist/core/update/types.d.ts +0 -11
- package/dist/core/update/types.js +0 -1
- package/dist/core/update/update-checker.d.ts +0 -11
- package/dist/core/update/update-checker.js +0 -63
- package/dist/core/update/update-manager.d.ts +0 -25
- package/dist/core/update/update-manager.js +0 -101
- package/dist/core/update/version-utils.d.ts +0 -6
- package/dist/core/update/version-utils.js +0 -34
- package/dist/gmail-connector-2FVYTQJH.js +0 -6
- package/dist/gmail-connector-MNUBRNFM.js +0 -6
- package/dist/gmail-connector-PS2VLGNE.js +0 -6
- package/dist/gmail-connector-ULSMN6X2.js +0 -6
- package/dist/gmail-connector-URRFX6A3.js +0 -6
- package/dist/inbound-AFBUPSPG.js +0 -10
- package/dist/inbound-AFOHYNUY.js +0 -6
- package/dist/inbound-CGIXRXGC.js +0 -8
- package/dist/inbound-MCOLRH6U.js +0 -10
- package/dist/inbound-SNEMBLGA.js +0 -6
- package/dist/inbound-ZJHAYVMF.js +0 -10
- package/dist/provider-qqJYv9nv.d.ts +0 -75
- package/dist/providers/anthropic/models.d.ts +0 -2
- package/dist/providers/anthropic/models.js +0 -29
- package/dist/providers/anthropic/provider.d.ts +0 -13
- package/dist/providers/anthropic/provider.js +0 -119
- package/dist/providers/anthropic/tool-converter.d.ts +0 -10
- package/dist/providers/anthropic/tool-converter.js +0 -7
- package/dist/providers/ollama/provider.d.ts +0 -17
- package/dist/providers/ollama/provider.js +0 -185
- package/dist/providers/openai/models.d.ts +0 -2
- package/dist/providers/openai/models.js +0 -29
- package/dist/providers/openai/provider.d.ts +0 -13
- package/dist/providers/openai/provider.js +0 -163
- package/dist/providers/openai/tool-converter.d.ts +0 -10
- package/dist/providers/openai/tool-converter.js +0 -10
- package/dist/shared/constants.d.ts +0 -50
- package/dist/shared/constants.js +0 -64
- package/dist/shared/index.d.ts +0 -14
- package/dist/shared/index.js +0 -14
- package/dist/shared/types/agent.d.ts +0 -36
- package/dist/shared/types/agent.js +0 -2
- package/dist/shared/types/channel.d.ts +0 -70
- package/dist/shared/types/channel.js +0 -2
- package/dist/shared/types/config.d.ts +0 -111
- package/dist/shared/types/config.js +0 -2
- package/dist/shared/types/connector.d.ts +0 -77
- package/dist/shared/types/connector.js +0 -2
- package/dist/shared/types/execution.d.ts +0 -29
- package/dist/shared/types/execution.js +0 -2
- package/dist/shared/types/provider.d.ts +0 -73
- package/dist/shared/types/provider.js +0 -2
- package/dist/shared/types/task.d.ts +0 -47
- package/dist/shared/types/task.js +0 -2
- package/dist/shared/types/workflow.d.ts +0 -39
- package/dist/shared/types/workflow.js +0 -2
- package/dist/shared/utils.d.ts +0 -6
- package/dist/shared/utils.js +0 -13
- package/dist/update-check.d.ts +0 -5
- package/dist/update-check.js +0 -56
|
@@ -1,243 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Google Calendar connector — pulls calendar events.
|
|
3
|
-
*
|
|
4
|
-
* Produces `CalendarEventRecord` objects. Does NOT write to any database
|
|
5
|
-
* table; the consuming application decides how to store records.
|
|
6
|
-
*/
|
|
7
|
-
import { createOAuth2Client, createServiceAccountClient, getAuthUrl, exchangeCode, loadTokens, saveTokens, refreshIfNeeded, } from './oauth.js';
|
|
8
|
-
// ── Connector ──────────────────────────────────────────────────────
|
|
9
|
-
export class GoogleCalendarConnector {
|
|
10
|
-
id = 'google-calendar';
|
|
11
|
-
meta = {
|
|
12
|
-
displayName: 'Google Calendar',
|
|
13
|
-
provider: 'google',
|
|
14
|
-
dataType: 'calendar',
|
|
15
|
-
};
|
|
16
|
-
tokenLoader;
|
|
17
|
-
tokenSaver;
|
|
18
|
-
client = null;
|
|
19
|
-
config = null;
|
|
20
|
-
tokens = null;
|
|
21
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
22
|
-
calendar = null;
|
|
23
|
-
constructor(opts = {}) {
|
|
24
|
-
this.tokenLoader = opts.tokenLoader;
|
|
25
|
-
this.tokenSaver = opts.tokenSaver;
|
|
26
|
-
}
|
|
27
|
-
// ── Lifecycle ──────────────────────────────────────────────────
|
|
28
|
-
async connect(config) {
|
|
29
|
-
this.config = config;
|
|
30
|
-
const scopes = config.scopes ?? [
|
|
31
|
-
'https://www.googleapis.com/auth/calendar.readonly',
|
|
32
|
-
];
|
|
33
|
-
if (config.serviceAccount) {
|
|
34
|
-
this.client = await createServiceAccountClient(config.serviceAccount, scopes);
|
|
35
|
-
}
|
|
36
|
-
else if (config.oauth) {
|
|
37
|
-
this.client = await createOAuth2Client(config.oauth);
|
|
38
|
-
if (!this.tokenLoader) {
|
|
39
|
-
throw new Error('tokenLoader required for OAuth2 flow');
|
|
40
|
-
}
|
|
41
|
-
this.tokens = await loadTokens(this.tokenLoader, config.account);
|
|
42
|
-
if (!this.tokens) {
|
|
43
|
-
throw new Error(`No stored tokens for account ${config.account}. Complete the OAuth flow first.`);
|
|
44
|
-
}
|
|
45
|
-
this.tokens = await refreshIfNeeded(this.client, this.tokens, this.tokenSaver
|
|
46
|
-
? async (t) => saveTokens(this.tokenSaver, config.account, t)
|
|
47
|
-
: undefined);
|
|
48
|
-
this.client.setCredentials(this.tokens);
|
|
49
|
-
}
|
|
50
|
-
else {
|
|
51
|
-
throw new Error('Either serviceAccount or oauth config is required');
|
|
52
|
-
}
|
|
53
|
-
const { google } = await import('googleapis');
|
|
54
|
-
this.calendar = google.calendar({ version: 'v3', auth: this.client });
|
|
55
|
-
}
|
|
56
|
-
async disconnect() {
|
|
57
|
-
this.client = null;
|
|
58
|
-
this.calendar = null;
|
|
59
|
-
this.tokens = null;
|
|
60
|
-
this.config = null;
|
|
61
|
-
}
|
|
62
|
-
async healthCheck() {
|
|
63
|
-
try {
|
|
64
|
-
this.ensureConnected();
|
|
65
|
-
const res = await this.calendar.calendarList.list({ maxResults: 1 });
|
|
66
|
-
const primary = (res.data.items ?? []).find(
|
|
67
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
68
|
-
(c) => c.primary);
|
|
69
|
-
return { ok: true, account: primary?.id ?? this.config.account };
|
|
70
|
-
}
|
|
71
|
-
catch (err) {
|
|
72
|
-
return { ok: false, error: errorMessage(err) };
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
|
-
// ── Auth ───────────────────────────────────────────────────────
|
|
76
|
-
async authenticate(codeProvider) {
|
|
77
|
-
if (!this.config) {
|
|
78
|
-
return { success: false, error: 'Call connect() first to set config, or pass config and call authenticate() before connect().' };
|
|
79
|
-
}
|
|
80
|
-
try {
|
|
81
|
-
if (!this.config.oauth) {
|
|
82
|
-
return { success: false, error: 'OAuth config required for browser-based authenticate(). Use serviceAccount for headless auth.' };
|
|
83
|
-
}
|
|
84
|
-
if (!this.tokenSaver) {
|
|
85
|
-
return { success: false, error: 'tokenSaver required for authenticate() flow.' };
|
|
86
|
-
}
|
|
87
|
-
const client = await createOAuth2Client(this.config.oauth);
|
|
88
|
-
const scopes = this.config.scopes ?? [
|
|
89
|
-
'https://www.googleapis.com/auth/calendar.readonly',
|
|
90
|
-
];
|
|
91
|
-
const authUrl = getAuthUrl(client, scopes);
|
|
92
|
-
const code = await codeProvider(authUrl);
|
|
93
|
-
const tokens = await exchangeCode(client, code);
|
|
94
|
-
await saveTokens(this.tokenSaver, this.config.account, tokens);
|
|
95
|
-
this.tokens = tokens;
|
|
96
|
-
this.client = client;
|
|
97
|
-
this.client.setCredentials(tokens);
|
|
98
|
-
const { google } = await import('googleapis');
|
|
99
|
-
this.calendar = google.calendar({ version: 'v3', auth: this.client });
|
|
100
|
-
return { success: true, account: this.config.account };
|
|
101
|
-
}
|
|
102
|
-
catch (err) {
|
|
103
|
-
return { success: false, error: errorMessage(err) };
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
// ── Sync ───────────────────────────────────────────────────────
|
|
107
|
-
async sync(options) {
|
|
108
|
-
this.ensureConnected();
|
|
109
|
-
if (options?.cursor) {
|
|
110
|
-
return this.syncIncremental(options.cursor, options);
|
|
111
|
-
}
|
|
112
|
-
return this.syncFull(options);
|
|
113
|
-
}
|
|
114
|
-
/** Incremental sync using Calendar syncToken. */
|
|
115
|
-
async syncIncremental(syncToken, options) {
|
|
116
|
-
const calendarId = options?.filters?.calendarId ?? 'primary';
|
|
117
|
-
const records = [];
|
|
118
|
-
const errors = [];
|
|
119
|
-
let pageToken;
|
|
120
|
-
let nextSyncToken;
|
|
121
|
-
try {
|
|
122
|
-
do {
|
|
123
|
-
const res = await this.calendar.events.list({
|
|
124
|
-
calendarId,
|
|
125
|
-
syncToken,
|
|
126
|
-
...(pageToken ? { pageToken } : {}),
|
|
127
|
-
maxResults: options?.limit ? Math.min(options.limit - records.length, 250) : 250,
|
|
128
|
-
});
|
|
129
|
-
for (const event of res.data.items ?? []) {
|
|
130
|
-
try {
|
|
131
|
-
records.push(this.mapEvent(event, calendarId));
|
|
132
|
-
}
|
|
133
|
-
catch (err) {
|
|
134
|
-
errors.push({ id: event.id, error: errorMessage(err) });
|
|
135
|
-
}
|
|
136
|
-
if (options?.limit && records.length >= options.limit)
|
|
137
|
-
break;
|
|
138
|
-
}
|
|
139
|
-
pageToken = res.data.nextPageToken ?? undefined;
|
|
140
|
-
nextSyncToken = res.data.nextSyncToken ?? undefined;
|
|
141
|
-
} while (pageToken && (!options?.limit || records.length < options.limit));
|
|
142
|
-
}
|
|
143
|
-
catch (err) {
|
|
144
|
-
// If syncToken is expired/invalid, fall back to full sync
|
|
145
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
146
|
-
if (err?.code === 410) {
|
|
147
|
-
return this.syncFull(options);
|
|
148
|
-
}
|
|
149
|
-
throw err;
|
|
150
|
-
}
|
|
151
|
-
return {
|
|
152
|
-
records,
|
|
153
|
-
cursor: nextSyncToken,
|
|
154
|
-
hasMore: !!pageToken,
|
|
155
|
-
errors,
|
|
156
|
-
};
|
|
157
|
-
}
|
|
158
|
-
/** Full sync using timeMin. */
|
|
159
|
-
async syncFull(options) {
|
|
160
|
-
const calendarId = options?.filters?.calendarId ?? 'primary';
|
|
161
|
-
const records = [];
|
|
162
|
-
const errors = [];
|
|
163
|
-
const maxResults = options?.limit ?? 250;
|
|
164
|
-
const timeMin = options?.since
|
|
165
|
-
? new Date(options.since).toISOString()
|
|
166
|
-
: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString(); // default: 30 days ago
|
|
167
|
-
let pageToken;
|
|
168
|
-
let nextSyncToken;
|
|
169
|
-
do {
|
|
170
|
-
const res = await this.calendar.events.list({
|
|
171
|
-
calendarId,
|
|
172
|
-
timeMin,
|
|
173
|
-
singleEvents: true,
|
|
174
|
-
orderBy: 'startTime',
|
|
175
|
-
maxResults: Math.min(maxResults - records.length, 250),
|
|
176
|
-
...(pageToken ? { pageToken } : {}),
|
|
177
|
-
});
|
|
178
|
-
for (const event of res.data.items ?? []) {
|
|
179
|
-
try {
|
|
180
|
-
records.push(this.mapEvent(event, calendarId));
|
|
181
|
-
}
|
|
182
|
-
catch (err) {
|
|
183
|
-
errors.push({ id: event.id, error: errorMessage(err) });
|
|
184
|
-
}
|
|
185
|
-
if (records.length >= maxResults)
|
|
186
|
-
break;
|
|
187
|
-
}
|
|
188
|
-
pageToken = res.data.nextPageToken ?? undefined;
|
|
189
|
-
nextSyncToken = res.data.nextSyncToken ?? undefined;
|
|
190
|
-
} while (pageToken && records.length < maxResults);
|
|
191
|
-
return {
|
|
192
|
-
records,
|
|
193
|
-
cursor: nextSyncToken,
|
|
194
|
-
hasMore: !!pageToken,
|
|
195
|
-
errors,
|
|
196
|
-
};
|
|
197
|
-
}
|
|
198
|
-
// ── Internals ─────────────────────────────────────────────────
|
|
199
|
-
ensureConnected() {
|
|
200
|
-
if (!this.calendar || !this.config) {
|
|
201
|
-
throw new Error('GoogleCalendarConnector is not connected. Call connect() first.');
|
|
202
|
-
}
|
|
203
|
-
}
|
|
204
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
205
|
-
mapEvent(event, calendarId) {
|
|
206
|
-
const start = event.start ?? {};
|
|
207
|
-
const end = event.end ?? {};
|
|
208
|
-
const allDay = !!start.date;
|
|
209
|
-
const startAt = allDay
|
|
210
|
-
? new Date(start.date).toISOString()
|
|
211
|
-
: new Date(start.dateTime).toISOString();
|
|
212
|
-
const endAt = allDay
|
|
213
|
-
? new Date(end.date).toISOString()
|
|
214
|
-
: new Date(end.dateTime).toISOString();
|
|
215
|
-
const attendees = (event.attendees ?? []).map(
|
|
216
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
217
|
-
(a) => ({
|
|
218
|
-
email: a.email,
|
|
219
|
-
displayName: a.displayName,
|
|
220
|
-
responseStatus: a.responseStatus,
|
|
221
|
-
}));
|
|
222
|
-
return {
|
|
223
|
-
googleEventId: event.id,
|
|
224
|
-
calendarId,
|
|
225
|
-
account: this.config.account,
|
|
226
|
-
title: event.summary ?? '(No title)',
|
|
227
|
-
description: event.description ?? undefined,
|
|
228
|
-
location: event.location ?? undefined,
|
|
229
|
-
startAt,
|
|
230
|
-
endAt,
|
|
231
|
-
allDay,
|
|
232
|
-
timezone: start.timeZone ?? undefined,
|
|
233
|
-
status: event.status ?? 'confirmed',
|
|
234
|
-
organizerEmail: event.organizer?.email ?? '',
|
|
235
|
-
attendees,
|
|
236
|
-
recurrence: event.recurrence ?? undefined,
|
|
237
|
-
htmlLink: event.htmlLink ?? undefined,
|
|
238
|
-
};
|
|
239
|
-
}
|
|
240
|
-
}
|
|
241
|
-
function errorMessage(err) {
|
|
242
|
-
return err instanceof Error ? err.message : String(err);
|
|
243
|
-
}
|
|
@@ -1,42 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Gmail connector — pulls email metadata and optionally sends mail.
|
|
3
|
-
*
|
|
4
|
-
* Produces `EmailRecord` objects. Does NOT write to any database table;
|
|
5
|
-
* the consuming application decides how to store records.
|
|
6
|
-
*/
|
|
7
|
-
import type { Connector, ConnectorMeta, AuthResult, SyncOptions, SyncResult, PushResult } from '../../shared/types/connector.js';
|
|
8
|
-
import type { EmailRecord, GoogleConnectorConfig } from './types.js';
|
|
9
|
-
export interface GmailConnectorOpts {
|
|
10
|
-
/** Load persisted tokens for a given account key (OAuth2 flow only). */
|
|
11
|
-
tokenLoader?: (key: string) => Promise<string | null>;
|
|
12
|
-
/** Persist tokens for a given account key (OAuth2 flow only). */
|
|
13
|
-
tokenSaver?: (key: string, value: string) => Promise<void>;
|
|
14
|
-
}
|
|
15
|
-
export declare class GoogleGmailConnector implements Connector<EmailRecord> {
|
|
16
|
-
readonly id = "google-gmail";
|
|
17
|
-
readonly meta: ConnectorMeta;
|
|
18
|
-
private tokenLoader?;
|
|
19
|
-
private tokenSaver?;
|
|
20
|
-
private client;
|
|
21
|
-
private config;
|
|
22
|
-
private tokens;
|
|
23
|
-
private gmail;
|
|
24
|
-
constructor(opts?: GmailConnectorOpts);
|
|
25
|
-
connect(config: GoogleConnectorConfig): Promise<void>;
|
|
26
|
-
disconnect(): Promise<void>;
|
|
27
|
-
healthCheck(): Promise<{
|
|
28
|
-
ok: boolean;
|
|
29
|
-
account?: string;
|
|
30
|
-
error?: string;
|
|
31
|
-
}>;
|
|
32
|
-
authenticate(codeProvider: (authUrl: string) => Promise<string>): Promise<AuthResult>;
|
|
33
|
-
sync(options?: SyncOptions): Promise<SyncResult<EmailRecord>>;
|
|
34
|
-
/** Incremental sync using Gmail history API. */
|
|
35
|
-
private syncIncremental;
|
|
36
|
-
/** Full sync — list messages and fetch each one. */
|
|
37
|
-
private syncFull;
|
|
38
|
-
push(payload: EmailRecord): Promise<PushResult>;
|
|
39
|
-
private ensureConnected;
|
|
40
|
-
/** Fetch a single message by ID and parse into an EmailRecord. */
|
|
41
|
-
private fetchMessage;
|
|
42
|
-
}
|
|
@@ -1,345 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Gmail connector — pulls email metadata and optionally sends mail.
|
|
3
|
-
*
|
|
4
|
-
* Produces `EmailRecord` objects. Does NOT write to any database table;
|
|
5
|
-
* the consuming application decides how to store records.
|
|
6
|
-
*/
|
|
7
|
-
import { createOAuth2Client, createServiceAccountClient, getAuthUrl, exchangeCode, loadTokens, saveTokens, refreshIfNeeded, } from './oauth.js';
|
|
8
|
-
// ── Connector ──────────────────────────────────────────────────────
|
|
9
|
-
export class GoogleGmailConnector {
|
|
10
|
-
id = 'google-gmail';
|
|
11
|
-
meta = {
|
|
12
|
-
displayName: 'Google Gmail',
|
|
13
|
-
provider: 'google',
|
|
14
|
-
dataType: 'email',
|
|
15
|
-
};
|
|
16
|
-
tokenLoader;
|
|
17
|
-
tokenSaver;
|
|
18
|
-
client = null;
|
|
19
|
-
config = null;
|
|
20
|
-
tokens = null;
|
|
21
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
22
|
-
gmail = null;
|
|
23
|
-
constructor(opts = {}) {
|
|
24
|
-
this.tokenLoader = opts.tokenLoader;
|
|
25
|
-
this.tokenSaver = opts.tokenSaver;
|
|
26
|
-
}
|
|
27
|
-
// ── Lifecycle ──────────────────────────────────────────────────
|
|
28
|
-
async connect(config) {
|
|
29
|
-
this.config = config;
|
|
30
|
-
const scopes = config.scopes ?? [
|
|
31
|
-
'https://www.googleapis.com/auth/gmail.readonly',
|
|
32
|
-
];
|
|
33
|
-
if (config.serviceAccount) {
|
|
34
|
-
// Service account auth — headless, no browser
|
|
35
|
-
this.client = await createServiceAccountClient(config.serviceAccount, scopes);
|
|
36
|
-
}
|
|
37
|
-
else if (config.oauth) {
|
|
38
|
-
// OAuth2 user flow — requires tokens from prior browser auth
|
|
39
|
-
this.client = await createOAuth2Client(config.oauth);
|
|
40
|
-
if (!this.tokenLoader) {
|
|
41
|
-
throw new Error('tokenLoader required for OAuth2 flow');
|
|
42
|
-
}
|
|
43
|
-
this.tokens = await loadTokens(this.tokenLoader, config.account);
|
|
44
|
-
if (!this.tokens) {
|
|
45
|
-
throw new Error(`No stored tokens for account ${config.account}. Complete the OAuth flow first.`);
|
|
46
|
-
}
|
|
47
|
-
this.tokens = await refreshIfNeeded(this.client, this.tokens, this.tokenSaver
|
|
48
|
-
? async (t) => saveTokens(this.tokenSaver, config.account, t)
|
|
49
|
-
: undefined);
|
|
50
|
-
this.client.setCredentials(this.tokens);
|
|
51
|
-
}
|
|
52
|
-
else {
|
|
53
|
-
throw new Error('Either serviceAccount or oauth config is required');
|
|
54
|
-
}
|
|
55
|
-
const { google } = await import('googleapis');
|
|
56
|
-
this.gmail = google.gmail({ version: 'v1', auth: this.client });
|
|
57
|
-
}
|
|
58
|
-
async disconnect() {
|
|
59
|
-
this.client = null;
|
|
60
|
-
this.gmail = null;
|
|
61
|
-
this.tokens = null;
|
|
62
|
-
this.config = null;
|
|
63
|
-
}
|
|
64
|
-
async healthCheck() {
|
|
65
|
-
try {
|
|
66
|
-
this.ensureConnected();
|
|
67
|
-
const res = await this.gmail.users.getProfile({ userId: 'me' });
|
|
68
|
-
return { ok: true, account: res.data.emailAddress };
|
|
69
|
-
}
|
|
70
|
-
catch (err) {
|
|
71
|
-
return { ok: false, error: errorMessage(err) };
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
// ── Auth ───────────────────────────────────────────────────────
|
|
75
|
-
async authenticate(codeProvider) {
|
|
76
|
-
if (!this.config) {
|
|
77
|
-
return { success: false, error: 'Call connect() first to set config, or pass config and call authenticate() before connect().' };
|
|
78
|
-
}
|
|
79
|
-
try {
|
|
80
|
-
if (!this.config.oauth) {
|
|
81
|
-
return { success: false, error: 'OAuth config required for browser-based authenticate(). Use serviceAccount for headless auth.' };
|
|
82
|
-
}
|
|
83
|
-
if (!this.tokenSaver) {
|
|
84
|
-
return { success: false, error: 'tokenSaver required for authenticate() flow.' };
|
|
85
|
-
}
|
|
86
|
-
const client = await createOAuth2Client(this.config.oauth);
|
|
87
|
-
const scopes = this.config.scopes ?? [
|
|
88
|
-
'https://www.googleapis.com/auth/gmail.readonly',
|
|
89
|
-
'https://www.googleapis.com/auth/gmail.send',
|
|
90
|
-
];
|
|
91
|
-
const authUrl = getAuthUrl(client, scopes);
|
|
92
|
-
const code = await codeProvider(authUrl);
|
|
93
|
-
const tokens = await exchangeCode(client, code);
|
|
94
|
-
await saveTokens(this.tokenSaver, this.config.account, tokens);
|
|
95
|
-
this.tokens = tokens;
|
|
96
|
-
this.client = client;
|
|
97
|
-
this.client.setCredentials(tokens);
|
|
98
|
-
const { google } = await import('googleapis');
|
|
99
|
-
this.gmail = google.gmail({ version: 'v1', auth: this.client });
|
|
100
|
-
return { success: true, account: this.config.account };
|
|
101
|
-
}
|
|
102
|
-
catch (err) {
|
|
103
|
-
return { success: false, error: errorMessage(err) };
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
// ── Sync ───────────────────────────────────────────────────────
|
|
107
|
-
async sync(options) {
|
|
108
|
-
this.ensureConnected();
|
|
109
|
-
if (options?.cursor) {
|
|
110
|
-
return this.syncIncremental(options.cursor, options.limit);
|
|
111
|
-
}
|
|
112
|
-
return this.syncFull(options);
|
|
113
|
-
}
|
|
114
|
-
/** Incremental sync using Gmail history API. */
|
|
115
|
-
async syncIncremental(startHistoryId, limit) {
|
|
116
|
-
const records = [];
|
|
117
|
-
const errors = [];
|
|
118
|
-
const seenIds = new Set();
|
|
119
|
-
let pageToken;
|
|
120
|
-
let latestHistoryId = startHistoryId;
|
|
121
|
-
do {
|
|
122
|
-
const res = await this.gmail.users.history.list({
|
|
123
|
-
userId: 'me',
|
|
124
|
-
startHistoryId,
|
|
125
|
-
historyTypes: ['messageAdded'],
|
|
126
|
-
...(pageToken ? { pageToken } : {}),
|
|
127
|
-
});
|
|
128
|
-
latestHistoryId = res.data.historyId ?? latestHistoryId;
|
|
129
|
-
const histories = res.data.history ?? [];
|
|
130
|
-
for (const h of histories) {
|
|
131
|
-
for (const added of h.messagesAdded ?? []) {
|
|
132
|
-
const msgId = added.message?.id;
|
|
133
|
-
if (!msgId || seenIds.has(msgId))
|
|
134
|
-
continue;
|
|
135
|
-
seenIds.add(msgId);
|
|
136
|
-
try {
|
|
137
|
-
const record = await this.fetchMessage(msgId);
|
|
138
|
-
records.push(record);
|
|
139
|
-
}
|
|
140
|
-
catch (err) {
|
|
141
|
-
errors.push({ id: msgId, error: errorMessage(err) });
|
|
142
|
-
}
|
|
143
|
-
if (limit && records.length >= limit) {
|
|
144
|
-
return { records, cursor: latestHistoryId, hasMore: true, errors };
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
pageToken = res.data.nextPageToken ?? undefined;
|
|
149
|
-
} while (pageToken);
|
|
150
|
-
return { records, cursor: latestHistoryId, hasMore: false, errors };
|
|
151
|
-
}
|
|
152
|
-
/** Full sync — list messages and fetch each one. */
|
|
153
|
-
async syncFull(options) {
|
|
154
|
-
const records = [];
|
|
155
|
-
const errors = [];
|
|
156
|
-
const maxResults = options?.limit ?? 100;
|
|
157
|
-
let query = '';
|
|
158
|
-
if (options?.since) {
|
|
159
|
-
// Gmail `after:` uses epoch seconds
|
|
160
|
-
const epoch = Math.floor(new Date(options.since).getTime() / 1000);
|
|
161
|
-
query = `after:${epoch}`;
|
|
162
|
-
}
|
|
163
|
-
if (options?.filters?.q) {
|
|
164
|
-
query = query ? `${query} ${options.filters.q}` : String(options.filters.q);
|
|
165
|
-
}
|
|
166
|
-
let pageToken;
|
|
167
|
-
let collected = 0;
|
|
168
|
-
do {
|
|
169
|
-
const res = await this.gmail.users.messages.list({
|
|
170
|
-
userId: 'me',
|
|
171
|
-
maxResults: Math.min(maxResults - collected, 100),
|
|
172
|
-
...(query ? { q: query } : {}),
|
|
173
|
-
...(pageToken ? { pageToken } : {}),
|
|
174
|
-
});
|
|
175
|
-
const messages = res.data.messages ?? [];
|
|
176
|
-
for (const msg of messages) {
|
|
177
|
-
try {
|
|
178
|
-
const record = await this.fetchMessage(msg.id);
|
|
179
|
-
records.push(record);
|
|
180
|
-
}
|
|
181
|
-
catch (err) {
|
|
182
|
-
errors.push({ id: msg.id, error: errorMessage(err) });
|
|
183
|
-
}
|
|
184
|
-
collected++;
|
|
185
|
-
if (collected >= maxResults)
|
|
186
|
-
break;
|
|
187
|
-
}
|
|
188
|
-
pageToken = res.data.nextPageToken ?? undefined;
|
|
189
|
-
} while (pageToken && collected < maxResults);
|
|
190
|
-
// Get current historyId for future incremental syncs
|
|
191
|
-
const profile = await this.gmail.users.getProfile({ userId: 'me' });
|
|
192
|
-
const cursor = profile.data.historyId ?? undefined;
|
|
193
|
-
return {
|
|
194
|
-
records,
|
|
195
|
-
cursor,
|
|
196
|
-
hasMore: !!pageToken,
|
|
197
|
-
errors,
|
|
198
|
-
};
|
|
199
|
-
}
|
|
200
|
-
// ── Push (send email) ─────────────────────────────────────────
|
|
201
|
-
async push(payload) {
|
|
202
|
-
this.ensureConnected();
|
|
203
|
-
try {
|
|
204
|
-
const toHeader = payload.to.map(formatAddress).join(', ');
|
|
205
|
-
const ccHeader = payload.cc.length
|
|
206
|
-
? `Cc: ${payload.cc.map(formatAddress).join(', ')}\r\n`
|
|
207
|
-
: '';
|
|
208
|
-
const bccHeader = payload.bcc.length
|
|
209
|
-
? `Bcc: ${payload.bcc.map(formatAddress).join(', ')}\r\n`
|
|
210
|
-
: '';
|
|
211
|
-
const mime = [
|
|
212
|
-
`To: ${toHeader}\r\n`,
|
|
213
|
-
ccHeader,
|
|
214
|
-
bccHeader,
|
|
215
|
-
`Subject: ${payload.subject}\r\n`,
|
|
216
|
-
`Content-Type: text/plain; charset="UTF-8"\r\n`,
|
|
217
|
-
`\r\n`,
|
|
218
|
-
payload.body ?? '',
|
|
219
|
-
].join('');
|
|
220
|
-
const encoded = Buffer.from(mime)
|
|
221
|
-
.toString('base64')
|
|
222
|
-
.replace(/\+/g, '-')
|
|
223
|
-
.replace(/\//g, '_')
|
|
224
|
-
.replace(/=+$/, '');
|
|
225
|
-
const res = await this.gmail.users.messages.send({
|
|
226
|
-
userId: 'me',
|
|
227
|
-
requestBody: { raw: encoded },
|
|
228
|
-
});
|
|
229
|
-
return { success: true, externalId: res.data.id };
|
|
230
|
-
}
|
|
231
|
-
catch (err) {
|
|
232
|
-
return { success: false, error: errorMessage(err) };
|
|
233
|
-
}
|
|
234
|
-
}
|
|
235
|
-
// ── Internals ─────────────────────────────────────────────────
|
|
236
|
-
ensureConnected() {
|
|
237
|
-
if (!this.gmail || !this.config) {
|
|
238
|
-
throw new Error('GoogleGmailConnector is not connected. Call connect() first.');
|
|
239
|
-
}
|
|
240
|
-
}
|
|
241
|
-
/** Fetch a single message by ID and parse into an EmailRecord. */
|
|
242
|
-
async fetchMessage(messageId) {
|
|
243
|
-
const res = await this.gmail.users.messages.get({
|
|
244
|
-
userId: 'me',
|
|
245
|
-
id: messageId,
|
|
246
|
-
format: 'full',
|
|
247
|
-
});
|
|
248
|
-
const msg = res.data;
|
|
249
|
-
const headers = msg.payload?.headers ?? [];
|
|
250
|
-
const getHeader = (name) => headers.find((h) => h.name.toLowerCase() === name.toLowerCase())?.value ?? '';
|
|
251
|
-
return {
|
|
252
|
-
gmailId: msg.id,
|
|
253
|
-
threadId: msg.threadId,
|
|
254
|
-
account: this.config.account,
|
|
255
|
-
subject: getHeader('Subject'),
|
|
256
|
-
from: parseAddress(getHeader('From')),
|
|
257
|
-
to: parseAddressList(getHeader('To')),
|
|
258
|
-
cc: parseAddressList(getHeader('Cc')),
|
|
259
|
-
bcc: parseAddressList(getHeader('Bcc')),
|
|
260
|
-
date: new Date(getHeader('Date')).toISOString(),
|
|
261
|
-
snippet: msg.snippet ?? '',
|
|
262
|
-
body: extractPlainTextBody(msg.payload),
|
|
263
|
-
labels: msg.labelIds ?? [],
|
|
264
|
-
isRead: !(msg.labelIds ?? []).includes('UNREAD'),
|
|
265
|
-
};
|
|
266
|
-
}
|
|
267
|
-
}
|
|
268
|
-
// ── MIME body extraction ──────────────────────────────────────────
|
|
269
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
270
|
-
function extractPlainTextBody(payload) {
|
|
271
|
-
if (!payload)
|
|
272
|
-
return undefined;
|
|
273
|
-
// Single-part message: body is directly on the payload
|
|
274
|
-
if (payload.mimeType === 'text/plain' && payload.body?.data) {
|
|
275
|
-
return decodeBase64Url(payload.body.data);
|
|
276
|
-
}
|
|
277
|
-
// Multipart: recurse through parts, prefer text/plain
|
|
278
|
-
if (payload.parts) {
|
|
279
|
-
// First pass: look for text/plain
|
|
280
|
-
for (const part of payload.parts) {
|
|
281
|
-
if (part.mimeType === 'text/plain' && part.body?.data) {
|
|
282
|
-
return decodeBase64Url(part.body.data);
|
|
283
|
-
}
|
|
284
|
-
}
|
|
285
|
-
// Second pass: recurse into nested multipart
|
|
286
|
-
for (const part of payload.parts) {
|
|
287
|
-
if (part.mimeType?.startsWith('multipart/')) {
|
|
288
|
-
const result = extractPlainTextBody(part);
|
|
289
|
-
if (result)
|
|
290
|
-
return result;
|
|
291
|
-
}
|
|
292
|
-
}
|
|
293
|
-
}
|
|
294
|
-
return undefined;
|
|
295
|
-
}
|
|
296
|
-
function decodeBase64Url(data) {
|
|
297
|
-
const base64 = data.replace(/-/g, '+').replace(/_/g, '/');
|
|
298
|
-
return Buffer.from(base64, 'base64').toString('utf-8');
|
|
299
|
-
}
|
|
300
|
-
// ── Address parsing utilities ──────────────────────────────────────
|
|
301
|
-
/**
|
|
302
|
-
* Parse a single "Name <email>" or bare "email" string.
|
|
303
|
-
*/
|
|
304
|
-
function parseAddress(raw) {
|
|
305
|
-
const match = raw.match(/^(.+?)\s*<([^>]+)>$/);
|
|
306
|
-
if (match) {
|
|
307
|
-
return { name: match[1].replace(/^["']|["']$/g, '').trim(), email: match[2] };
|
|
308
|
-
}
|
|
309
|
-
return { email: raw.trim() };
|
|
310
|
-
}
|
|
311
|
-
/**
|
|
312
|
-
* Parse a comma-separated list of addresses.
|
|
313
|
-
*/
|
|
314
|
-
function parseAddressList(raw) {
|
|
315
|
-
if (!raw.trim())
|
|
316
|
-
return [];
|
|
317
|
-
const results = [];
|
|
318
|
-
let current = '';
|
|
319
|
-
let depth = 0;
|
|
320
|
-
for (const ch of raw) {
|
|
321
|
-
if (ch === '<')
|
|
322
|
-
depth++;
|
|
323
|
-
else if (ch === '>')
|
|
324
|
-
depth--;
|
|
325
|
-
else if (ch === ',' && depth === 0) {
|
|
326
|
-
if (current.trim())
|
|
327
|
-
results.push(parseAddress(current.trim()));
|
|
328
|
-
current = '';
|
|
329
|
-
continue;
|
|
330
|
-
}
|
|
331
|
-
current += ch;
|
|
332
|
-
}
|
|
333
|
-
if (current.trim())
|
|
334
|
-
results.push(parseAddress(current.trim()));
|
|
335
|
-
return results;
|
|
336
|
-
}
|
|
337
|
-
/**
|
|
338
|
-
* Format an EmailAddress back into "Name <email>" string.
|
|
339
|
-
*/
|
|
340
|
-
function formatAddress(addr) {
|
|
341
|
-
return addr.name ? `${addr.name} <${addr.email}>` : addr.email;
|
|
342
|
-
}
|
|
343
|
-
function errorMessage(err) {
|
|
344
|
-
return err instanceof Error ? err.message : String(err);
|
|
345
|
-
}
|
|
@@ -1,48 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Google OAuth2 helpers.
|
|
3
|
-
*
|
|
4
|
-
* Uses dynamic `import('googleapis')` so the package is only required
|
|
5
|
-
* at runtime by consumers who actually use the Google connectors.
|
|
6
|
-
*/
|
|
7
|
-
import type { GoogleOAuthConfig, GoogleServiceAccountConfig, GoogleTokens } from './types.js';
|
|
8
|
-
type OAuth2Client = any;
|
|
9
|
-
/**
|
|
10
|
-
* Create a Google OAuth2 client from app credentials.
|
|
11
|
-
*/
|
|
12
|
-
export declare function createOAuth2Client(config: GoogleOAuthConfig): Promise<OAuth2Client>;
|
|
13
|
-
/**
|
|
14
|
-
* Generate the consent screen URL for the given scopes.
|
|
15
|
-
*/
|
|
16
|
-
export declare function getAuthUrl(client: OAuth2Client, scopes: string[]): string;
|
|
17
|
-
/**
|
|
18
|
-
* Exchange an authorization code for tokens.
|
|
19
|
-
*/
|
|
20
|
-
export declare function exchangeCode(client: OAuth2Client, code: string): Promise<GoogleTokens>;
|
|
21
|
-
/**
|
|
22
|
-
* Create an authenticated client using a service account with
|
|
23
|
-
* domain-wide delegation (impersonation). No browser flow needed.
|
|
24
|
-
*/
|
|
25
|
-
export declare function createServiceAccountClient(config: GoogleServiceAccountConfig, scopes: string[]): Promise<OAuth2Client>;
|
|
26
|
-
/**
|
|
27
|
-
* Load persisted tokens via a generic getter callback.
|
|
28
|
-
*
|
|
29
|
-
* @param getter Reads a string value by key (e.g. SecretStore.get)
|
|
30
|
-
* @param accountKey Unique key prefix for this account
|
|
31
|
-
*/
|
|
32
|
-
export declare function loadTokens(getter: (key: string) => Promise<string | null>, accountKey: string): Promise<GoogleTokens | null>;
|
|
33
|
-
/**
|
|
34
|
-
* Persist tokens via a generic setter callback.
|
|
35
|
-
*
|
|
36
|
-
* @param setter Writes a string value by key (e.g. SecretStore.set)
|
|
37
|
-
* @param accountKey Unique key prefix for this account
|
|
38
|
-
* @param tokens Tokens to persist
|
|
39
|
-
*/
|
|
40
|
-
export declare function saveTokens(setter: (key: string, value: string) => Promise<void>, accountKey: string, tokens: GoogleTokens): Promise<void>;
|
|
41
|
-
/**
|
|
42
|
-
* Refresh the access token if it has expired (or is about to within 60 s).
|
|
43
|
-
*
|
|
44
|
-
* If the token was refreshed and a `saver` callback is provided, the new
|
|
45
|
-
* tokens are persisted automatically.
|
|
46
|
-
*/
|
|
47
|
-
export declare function refreshIfNeeded(client: OAuth2Client, tokens: GoogleTokens, saver?: (tokens: GoogleTokens) => Promise<void>): Promise<GoogleTokens>;
|
|
48
|
-
export {};
|