integrate-sdk 0.9.54-dev.0 → 0.9.56
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/dist/adapters/index.js +2364 -0
- package/dist/adapters/solid-start.js +2364 -0
- package/dist/adapters/svelte-kit.js +2364 -0
- package/dist/database/adapters/drizzle.d.ts +23 -0
- package/dist/database/adapters/drizzle.d.ts.map +1 -0
- package/dist/database/adapters/drizzle.js +646 -0
- package/dist/database/adapters/mongodb.d.ts +17 -0
- package/dist/database/adapters/mongodb.d.ts.map +1 -0
- package/dist/database/adapters/mongodb.js +643 -0
- package/dist/database/adapters/prisma.d.ts +18 -0
- package/dist/database/adapters/prisma.d.ts.map +1 -0
- package/dist/database/adapters/prisma.js +679 -0
- package/dist/database/index.d.ts +9 -0
- package/dist/database/index.d.ts.map +1 -0
- package/dist/database/index.js +1128 -0
- package/dist/server.js +3515 -1
- package/dist/src/config/types.d.ts +25 -1
- package/dist/src/config/types.d.ts.map +1 -1
- package/dist/src/database/adapters/drizzle.d.ts +23 -0
- package/dist/src/database/adapters/drizzle.d.ts.map +1 -0
- package/dist/src/database/adapters/mongodb.d.ts +17 -0
- package/dist/src/database/adapters/mongodb.d.ts.map +1 -0
- package/dist/src/database/adapters/prisma.d.ts +18 -0
- package/dist/src/database/adapters/prisma.d.ts.map +1 -0
- package/dist/src/database/factory.d.ts +9 -0
- package/dist/src/database/factory.d.ts.map +1 -0
- package/dist/src/database/index.d.ts +9 -0
- package/dist/src/database/index.d.ts.map +1 -0
- package/dist/src/database/schemas/drizzle.d.ts +508 -0
- package/dist/src/database/schemas/drizzle.d.ts.map +1 -0
- package/dist/src/database/token-store.d.ts +18 -0
- package/dist/src/database/token-store.d.ts.map +1 -0
- package/dist/src/database/trigger-store.d.ts +23 -0
- package/dist/src/database/trigger-store.d.ts.map +1 -0
- package/dist/src/database/types.d.ts +132 -0
- package/dist/src/database/types.d.ts.map +1 -0
- package/dist/src/integrations/integration-docs-metadata.d.ts +40 -0
- package/dist/src/integrations/integration-docs-metadata.d.ts.map +1 -0
- package/dist/src/server.d.ts +4 -3
- package/dist/src/server.d.ts.map +1 -1
- package/package.json +32 -5
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { DatabaseDriver, IntegrateAdapterHooks, IntegrateDatabaseAdapter } from "../types.js";
|
|
2
|
+
export type DrizzleProvider = "pg" | "mysql" | "sqlite";
|
|
3
|
+
export interface DrizzleIntegrateSchema {
|
|
4
|
+
providerToken: object;
|
|
5
|
+
trigger?: object;
|
|
6
|
+
}
|
|
7
|
+
export interface DrizzleAdapterConfig {
|
|
8
|
+
provider: DrizzleProvider;
|
|
9
|
+
schema: DrizzleIntegrateSchema;
|
|
10
|
+
hooks?: IntegrateAdapterHooks;
|
|
11
|
+
debugLogs?: boolean;
|
|
12
|
+
}
|
|
13
|
+
type DrizzleDb = {
|
|
14
|
+
select: (...args: any[]) => any;
|
|
15
|
+
insert: (...args: any[]) => any;
|
|
16
|
+
update: (...args: any[]) => any;
|
|
17
|
+
delete: (...args: any[]) => any;
|
|
18
|
+
};
|
|
19
|
+
export declare function createDrizzleDatabaseDriver(db: DrizzleDb, schema: DrizzleIntegrateSchema): DatabaseDriver;
|
|
20
|
+
export declare function drizzleAdapter(db: DrizzleDb, config: DrizzleAdapterConfig): IntegrateDatabaseAdapter;
|
|
21
|
+
export declare function drizzleAdapterCallbacks(db: DrizzleDb, config: DrizzleAdapterConfig): import("../types.js").IntegrateDatabaseCallbacks;
|
|
22
|
+
export {};
|
|
23
|
+
//# sourceMappingURL=drizzle.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"drizzle.d.ts","sourceRoot":"","sources":["../../../../src/database/adapters/drizzle.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAEV,cAAc,EAGd,qBAAqB,EACrB,wBAAwB,EAMzB,MAAM,aAAa,CAAC;AAErB,MAAM,MAAM,eAAe,GACvB,IAAI,GACJ,OAAO,GACP,QAAQ,CAAC;AAEb,MAAM,WAAW,sBAAsB;IACrC,aAAa,EAAE,MAAM,CAAC;IACtB,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,oBAAoB;IACnC,QAAQ,EAAE,eAAe,CAAC;IAC1B,MAAM,EAAE,sBAAsB,CAAC;IAC/B,KAAK,CAAC,EAAE,qBAAqB,CAAC;IAC9B,SAAS,CAAC,EAAE,OAAO,CAAC;CACrB;AAED,KAAK,SAAS,GAAG;IACf,MAAM,EAAE,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,GAAG,CAAC;IAChC,MAAM,EAAE,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,GAAG,CAAC;IAChC,MAAM,EAAE,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,GAAG,CAAC;IAChC,MAAM,EAAE,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,GAAG,CAAC;CACjC,CAAC;AAqOF,wBAAgB,2BAA2B,CACzC,EAAE,EAAE,SAAS,EACb,MAAM,EAAE,sBAAsB,GAC7B,cAAc,CAUhB;AAED,wBAAgB,cAAc,CAC5B,EAAE,EAAE,SAAS,EACb,MAAM,EAAE,oBAAoB,GAC3B,wBAAwB,CAQ1B;AAED,wBAAgB,uBAAuB,CACrC,EAAE,EAAE,SAAS,EACb,MAAM,EAAE,oBAAoB,oDAO7B"}
|
|
@@ -0,0 +1,646 @@
|
|
|
1
|
+
// src/database/adapters/drizzle.ts
|
|
2
|
+
import { and, count, desc, eq, ne, or } from "drizzle-orm";
|
|
3
|
+
|
|
4
|
+
// src/database/token-store.ts
|
|
5
|
+
var USABLE_ACCESS_TOKEN_BUFFER_MS = 30 * 1000;
|
|
6
|
+
var MIN_MEANINGFUL_EXPIRY_MS = Date.UTC(2000, 0, 1);
|
|
7
|
+
function getRowUpdatedAtMs(row) {
|
|
8
|
+
return row.updatedAt instanceof Date ? row.updatedAt.getTime() : 0;
|
|
9
|
+
}
|
|
10
|
+
function normalizeAccountEmail(value) {
|
|
11
|
+
if (!value)
|
|
12
|
+
return null;
|
|
13
|
+
const normalized = value.trim().toLowerCase();
|
|
14
|
+
return normalized.length > 0 ? normalized : null;
|
|
15
|
+
}
|
|
16
|
+
function normalizeAccountEmailHint(value) {
|
|
17
|
+
const normalized = normalizeAccountEmail(value);
|
|
18
|
+
if (!normalized)
|
|
19
|
+
return null;
|
|
20
|
+
return normalized.includes("@") ? normalized : null;
|
|
21
|
+
}
|
|
22
|
+
function normalizeAccountIdentifier(value) {
|
|
23
|
+
return normalizeAccountEmail(value);
|
|
24
|
+
}
|
|
25
|
+
function normalizeAccountIdHint(value) {
|
|
26
|
+
if (!value)
|
|
27
|
+
return null;
|
|
28
|
+
const normalized = value.trim().toLowerCase();
|
|
29
|
+
return normalized.length > 0 ? normalized : null;
|
|
30
|
+
}
|
|
31
|
+
function normalizeProviderTokenType(value) {
|
|
32
|
+
const normalized = value?.trim();
|
|
33
|
+
return normalized && normalized.length > 0 ? normalized : "Bearer";
|
|
34
|
+
}
|
|
35
|
+
function hasMeaningfulExpiresAt(value) {
|
|
36
|
+
if (!value)
|
|
37
|
+
return false;
|
|
38
|
+
const ms = value.getTime();
|
|
39
|
+
return Number.isFinite(ms) && ms >= MIN_MEANINGFUL_EXPIRY_MS;
|
|
40
|
+
}
|
|
41
|
+
function hasUsableAccessToken(row, now = Date.now(), bufferMs = USABLE_ACCESS_TOKEN_BUFFER_MS) {
|
|
42
|
+
if (!row.accessToken)
|
|
43
|
+
return false;
|
|
44
|
+
const expiresAt = row.expiresAt;
|
|
45
|
+
if (!hasMeaningfulExpiresAt(expiresAt))
|
|
46
|
+
return true;
|
|
47
|
+
return expiresAt.getTime() > now + bufferMs;
|
|
48
|
+
}
|
|
49
|
+
function parseScopes(scope) {
|
|
50
|
+
if (!scope)
|
|
51
|
+
return;
|
|
52
|
+
const scopes = scope.split(" ").map((item) => item.trim()).filter((item) => item.length > 0);
|
|
53
|
+
return scopes.length > 0 ? scopes : undefined;
|
|
54
|
+
}
|
|
55
|
+
function choosePreferredTokenRow(rows) {
|
|
56
|
+
if (rows.length === 0)
|
|
57
|
+
return;
|
|
58
|
+
const sorted = [...rows].sort((left, right) => getRowUpdatedAtMs(right) - getRowUpdatedAtMs(left));
|
|
59
|
+
return sorted.find((row) => hasUsableAccessToken(row)) ?? sorted.find((row) => Boolean(row.refreshToken)) ?? sorted[0];
|
|
60
|
+
}
|
|
61
|
+
function selectProviderTokenRow(rows, email, accountId) {
|
|
62
|
+
if (rows.length === 0) {
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
const normalizedEmail = normalizeAccountEmailHint(email);
|
|
66
|
+
const normalizedAccountId = normalizeAccountIdHint(accountId);
|
|
67
|
+
if (normalizedAccountId && normalizedEmail) {
|
|
68
|
+
const exactBoth = rows.filter((row) => normalizeAccountIdHint(row.accountId) === normalizedAccountId && normalizeAccountEmail(row.accountEmail) === normalizedEmail);
|
|
69
|
+
if (exactBoth.length > 0) {
|
|
70
|
+
return choosePreferredTokenRow(exactBoth);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
if (normalizedAccountId) {
|
|
74
|
+
const exactAccountId = rows.filter((row) => normalizeAccountIdHint(row.accountId) === normalizedAccountId);
|
|
75
|
+
if (exactAccountId.length > 0) {
|
|
76
|
+
return choosePreferredTokenRow(exactAccountId);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
if (normalizedEmail) {
|
|
80
|
+
const exactEmail = rows.filter((row) => normalizeAccountEmail(row.accountEmail) === normalizedEmail);
|
|
81
|
+
if (exactEmail.length > 0) {
|
|
82
|
+
return choosePreferredTokenRow(exactEmail);
|
|
83
|
+
}
|
|
84
|
+
} else if (email) {
|
|
85
|
+
const normalizedIdentifier = normalizeAccountIdentifier(email);
|
|
86
|
+
if (normalizedIdentifier) {
|
|
87
|
+
const identifierMatches = rows.filter((row) => normalizeAccountIdHint(row.accountId) === normalizedIdentifier);
|
|
88
|
+
if (identifierMatches.length > 0) {
|
|
89
|
+
return choosePreferredTokenRow(identifierMatches);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
if (normalizedAccountId || normalizedEmail) {
|
|
94
|
+
const legacyRows = rows.filter((row) => !normalizeAccountIdHint(row.accountId) && !normalizeAccountEmail(row.accountEmail));
|
|
95
|
+
if (legacyRows.length === 1) {
|
|
96
|
+
return choosePreferredTokenRow(legacyRows);
|
|
97
|
+
}
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
return choosePreferredTokenRow(rows);
|
|
101
|
+
}
|
|
102
|
+
function providerTokenRecordToData(row) {
|
|
103
|
+
const expiresAt = hasMeaningfulExpiresAt(row.expiresAt) ? row.expiresAt : null;
|
|
104
|
+
const expiresIn = expiresAt ? Math.max(0, Math.floor((expiresAt.getTime() - Date.now()) / 1000)) : 3600;
|
|
105
|
+
return {
|
|
106
|
+
accessToken: row.accessToken,
|
|
107
|
+
refreshToken: row.refreshToken ?? undefined,
|
|
108
|
+
tokenType: normalizeProviderTokenType(row.tokenType),
|
|
109
|
+
expiresIn,
|
|
110
|
+
expiresAt: expiresAt?.toISOString(),
|
|
111
|
+
scopes: parseScopes(row.scope),
|
|
112
|
+
email: row.accountEmail ?? undefined,
|
|
113
|
+
accountId: row.accountId ?? undefined
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
function defaultResolveAccountIdentity(provider, tokenData, emailHint) {
|
|
117
|
+
const accountEmail = normalizeAccountEmail(emailHint ?? tokenData.email ?? null);
|
|
118
|
+
let accountId = normalizeAccountIdHint(tokenData.accountId ?? null);
|
|
119
|
+
if (!accountId && accountEmail) {
|
|
120
|
+
accountId = `${provider}:${accountEmail}`;
|
|
121
|
+
}
|
|
122
|
+
return { accountEmail, accountId };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// src/database/trigger-store.ts
|
|
126
|
+
function toIsoString(value) {
|
|
127
|
+
if (!value)
|
|
128
|
+
return null;
|
|
129
|
+
if (value instanceof Date) {
|
|
130
|
+
return Number.isNaN(value.getTime()) ? null : value.toISOString();
|
|
131
|
+
}
|
|
132
|
+
const parsed = new Date(value);
|
|
133
|
+
return Number.isNaN(parsed.getTime()) ? null : parsed.toISOString();
|
|
134
|
+
}
|
|
135
|
+
function toDbSchedule(value) {
|
|
136
|
+
if (value.scheduleType && value.scheduleValue) {
|
|
137
|
+
return {
|
|
138
|
+
scheduleType: value.scheduleType,
|
|
139
|
+
scheduleValue: value.scheduleValue
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
if (value.schedule.type === "once") {
|
|
143
|
+
const runAt = toIsoString(value.schedule.runAt);
|
|
144
|
+
if (!runAt) {
|
|
145
|
+
throw new Error("Invalid trigger once schedule");
|
|
146
|
+
}
|
|
147
|
+
return {
|
|
148
|
+
scheduleType: "once",
|
|
149
|
+
scheduleValue: runAt
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
return {
|
|
153
|
+
scheduleType: "cron",
|
|
154
|
+
scheduleValue: value.schedule.expression
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
function toSdkSchedule(row) {
|
|
158
|
+
if (row.scheduleType === "once") {
|
|
159
|
+
return {
|
|
160
|
+
type: "once",
|
|
161
|
+
runAt: row.scheduleValue
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
return {
|
|
165
|
+
type: "cron",
|
|
166
|
+
expression: row.scheduleValue
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
function toSdkTrigger(row) {
|
|
170
|
+
return {
|
|
171
|
+
id: row.id,
|
|
172
|
+
userId: row.userId ?? undefined,
|
|
173
|
+
name: row.name ?? undefined,
|
|
174
|
+
description: row.description ?? undefined,
|
|
175
|
+
toolName: row.toolName,
|
|
176
|
+
toolArguments: row.toolArguments ?? {},
|
|
177
|
+
schedule: toSdkSchedule(row),
|
|
178
|
+
status: row.status,
|
|
179
|
+
provider: row.provider ?? undefined,
|
|
180
|
+
createdAt: row.createdAt.toISOString(),
|
|
181
|
+
updatedAt: row.updatedAt.toISOString(),
|
|
182
|
+
lastRunAt: toIsoString(row.lastRunAt) ?? undefined,
|
|
183
|
+
nextRunAt: toIsoString(row.nextRunAt) ?? undefined,
|
|
184
|
+
runCount: row.runCount,
|
|
185
|
+
lastError: row.lastError ?? undefined,
|
|
186
|
+
lastResult: row.lastResult ?? undefined
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
function toDbTriggerUpdates(updates) {
|
|
190
|
+
const dbUpdates = {
|
|
191
|
+
updatedAt: new Date
|
|
192
|
+
};
|
|
193
|
+
if (updates.name !== undefined)
|
|
194
|
+
dbUpdates.name = updates.name ?? null;
|
|
195
|
+
if (updates.description !== undefined) {
|
|
196
|
+
dbUpdates.description = updates.description ?? null;
|
|
197
|
+
}
|
|
198
|
+
if (updates.toolArguments !== undefined) {
|
|
199
|
+
dbUpdates.toolArguments = updates.toolArguments;
|
|
200
|
+
}
|
|
201
|
+
if (updates.status !== undefined)
|
|
202
|
+
dbUpdates.status = updates.status;
|
|
203
|
+
if (updates.provider !== undefined)
|
|
204
|
+
dbUpdates.provider = updates.provider ?? null;
|
|
205
|
+
if (updates.lastError !== undefined)
|
|
206
|
+
dbUpdates.lastError = updates.lastError ?? null;
|
|
207
|
+
if (updates.lastResult !== undefined) {
|
|
208
|
+
dbUpdates.lastResult = updates.lastResult ?? null;
|
|
209
|
+
}
|
|
210
|
+
if (updates.lastRunAt !== undefined) {
|
|
211
|
+
dbUpdates.lastRunAt = updates.lastRunAt ? new Date(updates.lastRunAt) : null;
|
|
212
|
+
}
|
|
213
|
+
if (updates.nextRunAt !== undefined) {
|
|
214
|
+
dbUpdates.nextRunAt = updates.nextRunAt ? new Date(updates.nextRunAt) : null;
|
|
215
|
+
}
|
|
216
|
+
if (updates.runCount !== undefined)
|
|
217
|
+
dbUpdates.runCount = updates.runCount;
|
|
218
|
+
if (updates.schedule) {
|
|
219
|
+
if (updates.schedule.type === "once") {
|
|
220
|
+
dbUpdates.scheduleType = "once";
|
|
221
|
+
dbUpdates.scheduleValue = new Date(updates.schedule.runAt).toISOString();
|
|
222
|
+
} else {
|
|
223
|
+
dbUpdates.scheduleType = "cron";
|
|
224
|
+
dbUpdates.scheduleValue = updates.schedule.expression;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
return dbUpdates;
|
|
228
|
+
}
|
|
229
|
+
function flattenedTriggerToCreateInput(triggerData, contextUserId) {
|
|
230
|
+
const schedule = toDbSchedule(triggerData);
|
|
231
|
+
return {
|
|
232
|
+
id: triggerData.id,
|
|
233
|
+
userId: contextUserId ?? triggerData.userId ?? null,
|
|
234
|
+
name: triggerData.name ?? null,
|
|
235
|
+
description: triggerData.description ?? null,
|
|
236
|
+
toolName: triggerData.toolName,
|
|
237
|
+
toolArguments: triggerData.toolArguments ?? {},
|
|
238
|
+
scheduleType: schedule.scheduleType,
|
|
239
|
+
scheduleValue: schedule.scheduleValue,
|
|
240
|
+
status: triggerData.status ?? "active",
|
|
241
|
+
provider: triggerData.provider ?? null,
|
|
242
|
+
nextRunAt: triggerData.nextRunAt ? new Date(triggerData.nextRunAt) : null
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// src/database/factory.ts
|
|
247
|
+
function log(debug, message, error) {
|
|
248
|
+
if (!debug)
|
|
249
|
+
return;
|
|
250
|
+
if (error !== undefined) {
|
|
251
|
+
console.error(`[Integrate SDK] ${message}`, error);
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
console.log(`[Integrate SDK] ${message}`);
|
|
255
|
+
}
|
|
256
|
+
async function authorizeTriggerRow(row, context, hooks) {
|
|
257
|
+
if (!row)
|
|
258
|
+
return null;
|
|
259
|
+
const repaired = hooks?.authorizeTrigger ? await hooks.authorizeTrigger(row, context) : row;
|
|
260
|
+
if (!repaired)
|
|
261
|
+
return null;
|
|
262
|
+
if (context?.userId && repaired.userId !== context.userId) {
|
|
263
|
+
return null;
|
|
264
|
+
}
|
|
265
|
+
return repaired;
|
|
266
|
+
}
|
|
267
|
+
function createDatabaseAdapterCallbacks(options) {
|
|
268
|
+
const { driver, hooks, debugLogs } = options;
|
|
269
|
+
const getProviderToken = async (provider, email, context) => {
|
|
270
|
+
const userId = context?.userId;
|
|
271
|
+
if (!userId) {
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
const accountEmailHint = normalizeAccountEmailHint(email) ?? normalizeAccountEmailHint(typeof context?.accountEmail === "string" ? context.accountEmail : null);
|
|
275
|
+
const accountIdHint = normalizeAccountIdHint(typeof context?.accountId === "string" ? context.accountId : null);
|
|
276
|
+
try {
|
|
277
|
+
const rows = await driver.tokens.listProviderTokens(userId, provider);
|
|
278
|
+
const selectedRow = selectProviderTokenRow(rows, accountEmailHint ?? undefined, accountIdHint ?? undefined);
|
|
279
|
+
if (!selectedRow) {
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
return providerTokenRecordToData(selectedRow);
|
|
283
|
+
} catch (error) {
|
|
284
|
+
log(debugLogs, "Error fetching provider token:", error);
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
};
|
|
288
|
+
const setProviderToken = async (provider, tokenData, email, context) => {
|
|
289
|
+
const userId = context?.userId;
|
|
290
|
+
if (!userId) {
|
|
291
|
+
console.error("[Integrate SDK] Cannot save token: No userId in context");
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
const accountEmail = normalizeAccountEmailHint(email) ?? normalizeAccountEmail(tokenData?.email ?? null);
|
|
295
|
+
if (tokenData === null) {
|
|
296
|
+
try {
|
|
297
|
+
await driver.tokens.deleteProviderTokens({
|
|
298
|
+
userId,
|
|
299
|
+
provider,
|
|
300
|
+
accountEmail,
|
|
301
|
+
accountId: normalizeAccountIdHint(typeof context?.accountId === "string" ? context.accountId : null)
|
|
302
|
+
});
|
|
303
|
+
await hooks?.onTokenChange?.({ userId, provider, action: "remove" });
|
|
304
|
+
} catch (error) {
|
|
305
|
+
log(debugLogs, "Error deleting provider token:", error);
|
|
306
|
+
throw error;
|
|
307
|
+
}
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
try {
|
|
311
|
+
const resolvedIdentity = hooks?.resolveAccountIdentity ? await hooks.resolveAccountIdentity(provider, tokenData, accountEmail, context) : defaultResolveAccountIdentity(provider, tokenData, accountEmail);
|
|
312
|
+
const resolvedAccountEmail = resolvedIdentity.accountEmail;
|
|
313
|
+
const resolvedAccountId = normalizeAccountIdHint(resolvedIdentity.accountId) ?? normalizeAccountIdHint(typeof context?.accountId === "string" ? context.accountId : null) ?? null;
|
|
314
|
+
const rows = await driver.tokens.listProviderTokens(userId, provider);
|
|
315
|
+
let existing = selectProviderTokenRow(rows, resolvedAccountEmail ?? accountEmail ?? undefined, resolvedAccountId ?? undefined) ?? rows.find((row) => {
|
|
316
|
+
const sameEmail = resolvedAccountEmail && normalizeAccountEmail(row.accountEmail) === resolvedAccountEmail;
|
|
317
|
+
const sameAccountId = resolvedAccountId && normalizeAccountIdHint(row.accountId) === resolvedAccountId;
|
|
318
|
+
return Boolean(sameEmail || sameAccountId);
|
|
319
|
+
}) ?? (rows.length === 1 ? rows[0] : undefined);
|
|
320
|
+
const parsedExpiresAt = tokenData.expiresAt ? new Date(tokenData.expiresAt) : null;
|
|
321
|
+
const expiresAt = hasMeaningfulExpiresAt(parsedExpiresAt) ? parsedExpiresAt : null;
|
|
322
|
+
const scope = tokenData.scopes?.join(" ") ?? null;
|
|
323
|
+
const saved = await driver.tokens.upsertProviderToken({
|
|
324
|
+
existingId: existing?.id,
|
|
325
|
+
id: existing?.id ?? `${userId}-${provider}-${resolvedAccountEmail ?? "default"}-${Date.now()}`,
|
|
326
|
+
userId,
|
|
327
|
+
provider,
|
|
328
|
+
accountEmail: resolvedAccountEmail,
|
|
329
|
+
accountId: resolvedAccountId,
|
|
330
|
+
accessToken: tokenData.accessToken,
|
|
331
|
+
refreshToken: tokenData.refreshToken ?? null,
|
|
332
|
+
tokenType: normalizeProviderTokenType(tokenData.tokenType),
|
|
333
|
+
expiresAt,
|
|
334
|
+
scope
|
|
335
|
+
});
|
|
336
|
+
await driver.tokens.deleteDuplicateProviderTokens({
|
|
337
|
+
keepId: saved.id,
|
|
338
|
+
userId,
|
|
339
|
+
provider,
|
|
340
|
+
accountEmail: resolvedAccountEmail,
|
|
341
|
+
accountId: resolvedAccountId
|
|
342
|
+
});
|
|
343
|
+
await hooks?.onTokenChange?.({ userId, provider, action: "set" });
|
|
344
|
+
} catch (error) {
|
|
345
|
+
log(debugLogs, "Error saving provider token:", error);
|
|
346
|
+
throw error;
|
|
347
|
+
}
|
|
348
|
+
};
|
|
349
|
+
const removeProviderToken = async (provider, email, context) => {
|
|
350
|
+
const userId = context?.userId;
|
|
351
|
+
if (!userId) {
|
|
352
|
+
console.error("[Integrate SDK] Cannot delete token: No userId in context");
|
|
353
|
+
return;
|
|
354
|
+
}
|
|
355
|
+
try {
|
|
356
|
+
await driver.tokens.deleteProviderTokens({
|
|
357
|
+
userId,
|
|
358
|
+
provider,
|
|
359
|
+
accountEmail: normalizeAccountEmail(email)
|
|
360
|
+
});
|
|
361
|
+
await hooks?.onTokenChange?.({ userId, provider, action: "remove" });
|
|
362
|
+
} catch (error) {
|
|
363
|
+
log(debugLogs, "Error deleting provider token:", error);
|
|
364
|
+
throw error;
|
|
365
|
+
}
|
|
366
|
+
};
|
|
367
|
+
const callbacks = {
|
|
368
|
+
getProviderToken,
|
|
369
|
+
setProviderToken,
|
|
370
|
+
removeProviderToken
|
|
371
|
+
};
|
|
372
|
+
if (driver.triggers) {
|
|
373
|
+
const triggerDriver = driver.triggers;
|
|
374
|
+
const triggers = {
|
|
375
|
+
create: async (triggerData, context) => {
|
|
376
|
+
try {
|
|
377
|
+
const created = await triggerDriver.createTrigger(flattenedTriggerToCreateInput(triggerData, context?.userId));
|
|
378
|
+
return toSdkTrigger(created);
|
|
379
|
+
} catch (error) {
|
|
380
|
+
log(debugLogs, "Error creating trigger:", error);
|
|
381
|
+
throw error;
|
|
382
|
+
}
|
|
383
|
+
},
|
|
384
|
+
get: async (triggerId, context) => {
|
|
385
|
+
try {
|
|
386
|
+
const found = await triggerDriver.getTriggerById(triggerId);
|
|
387
|
+
const authorized = await authorizeTriggerRow(found, context, hooks);
|
|
388
|
+
return authorized ? toSdkTrigger(authorized) : null;
|
|
389
|
+
} catch (error) {
|
|
390
|
+
log(debugLogs, "Error getting trigger:", error);
|
|
391
|
+
throw error;
|
|
392
|
+
}
|
|
393
|
+
},
|
|
394
|
+
list: async (params, context) => {
|
|
395
|
+
try {
|
|
396
|
+
const { rows, total } = await triggerDriver.listTriggers({
|
|
397
|
+
userId: context?.userId,
|
|
398
|
+
status: params.status,
|
|
399
|
+
toolName: params.toolName,
|
|
400
|
+
limit: params.limit ?? 20,
|
|
401
|
+
offset: params.offset ?? 0
|
|
402
|
+
});
|
|
403
|
+
const triggers2 = [];
|
|
404
|
+
for (const row of rows) {
|
|
405
|
+
const authorized = await authorizeTriggerRow(row, context, hooks);
|
|
406
|
+
if (authorized) {
|
|
407
|
+
triggers2.push(toSdkTrigger(authorized));
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
return { triggers: triggers2, total };
|
|
411
|
+
} catch (error) {
|
|
412
|
+
log(debugLogs, "Error listing triggers:", error);
|
|
413
|
+
throw error;
|
|
414
|
+
}
|
|
415
|
+
},
|
|
416
|
+
update: async (triggerId, updates, context) => {
|
|
417
|
+
try {
|
|
418
|
+
const existing = await triggerDriver.getTriggerById(triggerId);
|
|
419
|
+
const authorized = await authorizeTriggerRow(existing, context, hooks);
|
|
420
|
+
if (!authorized) {
|
|
421
|
+
throw new Error(`Trigger not found: ${triggerId}`);
|
|
422
|
+
}
|
|
423
|
+
const updated = await triggerDriver.updateTrigger(authorized.id, toDbTriggerUpdates(updates));
|
|
424
|
+
if (!updated) {
|
|
425
|
+
throw new Error(`Trigger not found: ${triggerId}`);
|
|
426
|
+
}
|
|
427
|
+
return toSdkTrigger(updated);
|
|
428
|
+
} catch (error) {
|
|
429
|
+
log(debugLogs, "Error updating trigger:", error);
|
|
430
|
+
throw error;
|
|
431
|
+
}
|
|
432
|
+
},
|
|
433
|
+
delete: async (triggerId, context) => {
|
|
434
|
+
try {
|
|
435
|
+
const existing = await triggerDriver.getTriggerById(triggerId);
|
|
436
|
+
const authorized = await authorizeTriggerRow(existing, context, hooks);
|
|
437
|
+
if (!authorized) {
|
|
438
|
+
return;
|
|
439
|
+
}
|
|
440
|
+
await triggerDriver.deleteTrigger(authorized.id);
|
|
441
|
+
} catch (error) {
|
|
442
|
+
log(debugLogs, "Error deleting trigger:", error);
|
|
443
|
+
throw error;
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
};
|
|
447
|
+
callbacks.triggers = triggers;
|
|
448
|
+
}
|
|
449
|
+
return callbacks;
|
|
450
|
+
}
|
|
451
|
+
function createDatabaseAdapterFactory(createDriver, options) {
|
|
452
|
+
return () => createDatabaseAdapterCallbacks({
|
|
453
|
+
driver: createDriver(),
|
|
454
|
+
hooks: options?.hooks,
|
|
455
|
+
debugLogs: options?.debugLogs
|
|
456
|
+
});
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
// src/database/adapters/drizzle.ts
|
|
460
|
+
function mapProviderTokenRow(row) {
|
|
461
|
+
return {
|
|
462
|
+
id: String(row.id),
|
|
463
|
+
userId: String(row.userId),
|
|
464
|
+
provider: String(row.provider),
|
|
465
|
+
accountEmail: row.accountEmail ?? null,
|
|
466
|
+
accountId: row.accountId ?? null,
|
|
467
|
+
accessToken: String(row.accessToken),
|
|
468
|
+
refreshToken: row.refreshToken ?? null,
|
|
469
|
+
tokenType: String(row.tokenType ?? "Bearer"),
|
|
470
|
+
expiresAt: row.expiresAt ?? null,
|
|
471
|
+
scope: row.scope ?? null,
|
|
472
|
+
createdAt: row.createdAt,
|
|
473
|
+
updatedAt: row.updatedAt
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
function mapTriggerRow(row) {
|
|
477
|
+
return {
|
|
478
|
+
id: String(row.id),
|
|
479
|
+
userId: row.userId ?? null,
|
|
480
|
+
name: row.name ?? null,
|
|
481
|
+
description: row.description ?? null,
|
|
482
|
+
toolName: String(row.toolName),
|
|
483
|
+
toolArguments: row.toolArguments ?? {},
|
|
484
|
+
scheduleType: row.scheduleType,
|
|
485
|
+
scheduleValue: String(row.scheduleValue),
|
|
486
|
+
status: String(row.status),
|
|
487
|
+
provider: row.provider ?? null,
|
|
488
|
+
lastRunAt: row.lastRunAt ?? null,
|
|
489
|
+
nextRunAt: row.nextRunAt ?? null,
|
|
490
|
+
runCount: Number(row.runCount ?? 0),
|
|
491
|
+
lastError: row.lastError ?? null,
|
|
492
|
+
lastResult: row.lastResult ?? null,
|
|
493
|
+
createdAt: row.createdAt,
|
|
494
|
+
updatedAt: row.updatedAt
|
|
495
|
+
};
|
|
496
|
+
}
|
|
497
|
+
function createDrizzleTokenDriver(db, table) {
|
|
498
|
+
const t = table;
|
|
499
|
+
return {
|
|
500
|
+
async listProviderTokens(userId, provider) {
|
|
501
|
+
const rows = await db.select().from(table).where(and(eq(t.userId, userId), eq(t.provider, provider))).orderBy(desc(t.updatedAt)).limit(32);
|
|
502
|
+
return rows.map((row) => mapProviderTokenRow(row));
|
|
503
|
+
},
|
|
504
|
+
async upsertProviderToken(input) {
|
|
505
|
+
const now = new Date;
|
|
506
|
+
const values = {
|
|
507
|
+
id: input.existingId ?? input.id,
|
|
508
|
+
userId: input.userId,
|
|
509
|
+
provider: input.provider,
|
|
510
|
+
accountEmail: input.accountEmail,
|
|
511
|
+
accountId: input.accountId,
|
|
512
|
+
accessToken: input.accessToken,
|
|
513
|
+
refreshToken: input.refreshToken,
|
|
514
|
+
tokenType: input.tokenType,
|
|
515
|
+
expiresAt: input.expiresAt,
|
|
516
|
+
scope: input.scope,
|
|
517
|
+
updatedAt: now,
|
|
518
|
+
...input.existingId ? {} : { createdAt: now }
|
|
519
|
+
};
|
|
520
|
+
if (input.existingId) {
|
|
521
|
+
const [updated] = await db.update(table).set(values).where(eq(t.id, input.existingId)).returning();
|
|
522
|
+
return mapProviderTokenRow(updated);
|
|
523
|
+
}
|
|
524
|
+
const [created] = await db.insert(table).values(values).returning();
|
|
525
|
+
return mapProviderTokenRow(created);
|
|
526
|
+
},
|
|
527
|
+
async deleteProviderTokens(input) {
|
|
528
|
+
const conditions = [
|
|
529
|
+
eq(t.userId, input.userId),
|
|
530
|
+
eq(t.provider, input.provider)
|
|
531
|
+
];
|
|
532
|
+
if (input.accountEmail) {
|
|
533
|
+
conditions.push(eq(t.accountEmail, input.accountEmail));
|
|
534
|
+
} else if (input.accountId) {
|
|
535
|
+
conditions.push(eq(t.accountId, input.accountId));
|
|
536
|
+
}
|
|
537
|
+
await db.delete(table).where(and(...conditions));
|
|
538
|
+
},
|
|
539
|
+
async deleteDuplicateProviderTokens(input) {
|
|
540
|
+
const normalizedEmail = normalizeAccountEmail(input.accountEmail);
|
|
541
|
+
const normalizedAccountId = normalizeAccountIdHint(input.accountId);
|
|
542
|
+
if (!normalizedEmail && !normalizedAccountId) {
|
|
543
|
+
return;
|
|
544
|
+
}
|
|
545
|
+
const duplicateConditions = [
|
|
546
|
+
eq(t.userId, input.userId),
|
|
547
|
+
eq(t.provider, input.provider),
|
|
548
|
+
ne(t.id, input.keepId)
|
|
549
|
+
];
|
|
550
|
+
const identityConditions = [];
|
|
551
|
+
if (normalizedEmail) {
|
|
552
|
+
identityConditions.push(eq(t.accountEmail, normalizedEmail));
|
|
553
|
+
}
|
|
554
|
+
if (normalizedAccountId) {
|
|
555
|
+
identityConditions.push(eq(t.accountId, normalizedAccountId));
|
|
556
|
+
}
|
|
557
|
+
if (identityConditions.length === 0) {
|
|
558
|
+
return;
|
|
559
|
+
}
|
|
560
|
+
await db.delete(table).where(and(...duplicateConditions, or(...identityConditions)));
|
|
561
|
+
}
|
|
562
|
+
};
|
|
563
|
+
}
|
|
564
|
+
function createDrizzleTriggerDriver(db, table) {
|
|
565
|
+
const t = table;
|
|
566
|
+
return {
|
|
567
|
+
async createTrigger(input) {
|
|
568
|
+
const now = new Date;
|
|
569
|
+
const [created] = await db.insert(table).values({
|
|
570
|
+
id: input.id,
|
|
571
|
+
userId: input.userId,
|
|
572
|
+
name: input.name ?? null,
|
|
573
|
+
description: input.description ?? null,
|
|
574
|
+
toolName: input.toolName,
|
|
575
|
+
toolArguments: input.toolArguments,
|
|
576
|
+
scheduleType: input.scheduleType,
|
|
577
|
+
scheduleValue: input.scheduleValue,
|
|
578
|
+
status: input.status,
|
|
579
|
+
provider: input.provider ?? null,
|
|
580
|
+
nextRunAt: input.nextRunAt ?? null,
|
|
581
|
+
createdAt: now,
|
|
582
|
+
updatedAt: now
|
|
583
|
+
}).returning();
|
|
584
|
+
return mapTriggerRow(created);
|
|
585
|
+
},
|
|
586
|
+
async getTriggerById(triggerId) {
|
|
587
|
+
const [found] = await db.select().from(table).where(eq(t.id, triggerId)).limit(1);
|
|
588
|
+
return found ? mapTriggerRow(found) : null;
|
|
589
|
+
},
|
|
590
|
+
async listTriggers(query) {
|
|
591
|
+
const conditions = [];
|
|
592
|
+
if (query.userId) {
|
|
593
|
+
conditions.push(eq(t.userId, query.userId));
|
|
594
|
+
}
|
|
595
|
+
if (query.status) {
|
|
596
|
+
conditions.push(eq(t.status, query.status));
|
|
597
|
+
}
|
|
598
|
+
if (query.toolName) {
|
|
599
|
+
conditions.push(eq(t.toolName, query.toolName));
|
|
600
|
+
}
|
|
601
|
+
const whereClause = conditions.length > 0 ? and(...conditions) : undefined;
|
|
602
|
+
const rows = await db.select().from(table).where(whereClause).limit(query.limit).offset(query.offset);
|
|
603
|
+
const [totalResult] = await db.select({ count: count() }).from(table).where(whereClause);
|
|
604
|
+
return {
|
|
605
|
+
rows: rows.map((row) => mapTriggerRow(row)),
|
|
606
|
+
total: Number(totalResult?.count ?? 0)
|
|
607
|
+
};
|
|
608
|
+
},
|
|
609
|
+
async updateTrigger(triggerId, updates) {
|
|
610
|
+
const [updated] = await db.update(table).set(updates).where(eq(t.id, triggerId)).returning();
|
|
611
|
+
return updated ? mapTriggerRow(updated) : null;
|
|
612
|
+
},
|
|
613
|
+
async deleteTrigger(triggerId) {
|
|
614
|
+
await db.delete(table).where(eq(t.id, triggerId));
|
|
615
|
+
}
|
|
616
|
+
};
|
|
617
|
+
}
|
|
618
|
+
function createDrizzleDatabaseDriver(db, schema) {
|
|
619
|
+
const driver = {
|
|
620
|
+
tokens: createDrizzleTokenDriver(db, schema.providerToken)
|
|
621
|
+
};
|
|
622
|
+
if (schema.trigger) {
|
|
623
|
+
driver.triggers = createDrizzleTriggerDriver(db, schema.trigger);
|
|
624
|
+
}
|
|
625
|
+
return driver;
|
|
626
|
+
}
|
|
627
|
+
function drizzleAdapter(db, config) {
|
|
628
|
+
config.provider;
|
|
629
|
+
const driver = () => createDrizzleDatabaseDriver(db, config.schema);
|
|
630
|
+
return createDatabaseAdapterFactory(driver, {
|
|
631
|
+
hooks: config.hooks,
|
|
632
|
+
debugLogs: config.debugLogs
|
|
633
|
+
});
|
|
634
|
+
}
|
|
635
|
+
function drizzleAdapterCallbacks(db, config) {
|
|
636
|
+
return createDatabaseAdapterCallbacks({
|
|
637
|
+
driver: createDrizzleDatabaseDriver(db, config.schema),
|
|
638
|
+
hooks: config.hooks,
|
|
639
|
+
debugLogs: config.debugLogs
|
|
640
|
+
});
|
|
641
|
+
}
|
|
642
|
+
export {
|
|
643
|
+
drizzleAdapterCallbacks,
|
|
644
|
+
drizzleAdapter,
|
|
645
|
+
createDrizzleDatabaseDriver
|
|
646
|
+
};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { DatabaseDriver, IntegrateAdapterHooks, IntegrateDatabaseAdapter } from "../types.js";
|
|
2
|
+
export interface MongoCollectionNames {
|
|
3
|
+
providerTokens?: string;
|
|
4
|
+
triggers?: string;
|
|
5
|
+
}
|
|
6
|
+
export interface MongoAdapterConfig {
|
|
7
|
+
client?: import("mongodb").MongoClient;
|
|
8
|
+
collectionNames?: MongoCollectionNames;
|
|
9
|
+
hooks?: IntegrateAdapterHooks;
|
|
10
|
+
debugLogs?: boolean;
|
|
11
|
+
}
|
|
12
|
+
type MongoDb = import("mongodb").Db;
|
|
13
|
+
export declare function createMongoDatabaseDriver(db: MongoDb, config: MongoAdapterConfig): DatabaseDriver;
|
|
14
|
+
export declare function mongodbAdapter(db: MongoDb, config?: MongoAdapterConfig): IntegrateDatabaseAdapter;
|
|
15
|
+
export declare function mongodbAdapterCallbacks(db: MongoDb, config?: MongoAdapterConfig): import("../types.js").IntegrateDatabaseCallbacks;
|
|
16
|
+
export {};
|
|
17
|
+
//# sourceMappingURL=mongodb.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mongodb.d.ts","sourceRoot":"","sources":["../../../../src/database/adapters/mongodb.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAEV,cAAc,EAGd,qBAAqB,EACrB,wBAAwB,EAMzB,MAAM,aAAa,CAAC;AAErB,MAAM,WAAW,oBAAoB;IACnC,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,kBAAkB;IACjC,MAAM,CAAC,EAAE,OAAO,SAAS,EAAE,WAAW,CAAC;IACvC,eAAe,CAAC,EAAE,oBAAoB,CAAC;IACvC,KAAK,CAAC,EAAE,qBAAqB,CAAC;IAC9B,SAAS,CAAC,EAAE,OAAO,CAAC;CACrB;AAED,KAAK,OAAO,GAAG,OAAO,SAAS,EAAE,EAAE,CAAC;AAoNpC,wBAAgB,yBAAyB,CACvC,EAAE,EAAE,OAAO,EACX,MAAM,EAAE,kBAAkB,GACzB,cAAc,CAehB;AAED,wBAAgB,cAAc,CAC5B,EAAE,EAAE,OAAO,EACX,MAAM,GAAE,kBAAuB,GAC9B,wBAAwB,CAQ1B;AAED,wBAAgB,uBAAuB,CACrC,EAAE,EAAE,OAAO,EACX,MAAM,GAAE,kBAAuB,oDAOhC"}
|