fireflies-api 0.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 -0
- package/README.md +64 -0
- package/dist/action-items-CC9yUxHY.d.cts +380 -0
- package/dist/action-items-CC9yUxHY.d.ts +380 -0
- package/dist/cli/index.cjs +3909 -0
- package/dist/cli/index.cjs.map +1 -0
- package/dist/cli/index.d.cts +2 -0
- package/dist/cli/index.d.ts +2 -0
- package/dist/cli/index.js +3906 -0
- package/dist/cli/index.js.map +1 -0
- package/dist/index.cjs +3389 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +966 -0
- package/dist/index.d.ts +966 -0
- package/dist/index.js +3344 -0
- package/dist/index.js.map +1 -0
- package/dist/middleware/express.cjs +2491 -0
- package/dist/middleware/express.cjs.map +1 -0
- package/dist/middleware/express.d.cts +36 -0
- package/dist/middleware/express.d.ts +36 -0
- package/dist/middleware/express.js +2489 -0
- package/dist/middleware/express.js.map +1 -0
- package/dist/middleware/fastify.cjs +2501 -0
- package/dist/middleware/fastify.cjs.map +1 -0
- package/dist/middleware/fastify.d.cts +66 -0
- package/dist/middleware/fastify.d.ts +66 -0
- package/dist/middleware/fastify.js +2498 -0
- package/dist/middleware/fastify.js.map +1 -0
- package/dist/middleware/hono.cjs +2493 -0
- package/dist/middleware/hono.cjs.map +1 -0
- package/dist/middleware/hono.d.cts +37 -0
- package/dist/middleware/hono.d.ts +37 -0
- package/dist/middleware/hono.js +2490 -0
- package/dist/middleware/hono.js.map +1 -0
- package/dist/schemas/index.cjs +307 -0
- package/dist/schemas/index.cjs.map +1 -0
- package/dist/schemas/index.d.cts +926 -0
- package/dist/schemas/index.d.ts +926 -0
- package/dist/schemas/index.js +268 -0
- package/dist/schemas/index.js.map +1 -0
- package/dist/speaker-analytics-Dr46LKyP.d.ts +275 -0
- package/dist/speaker-analytics-l45LXqO1.d.cts +275 -0
- package/dist/types-BX-3JcRI.d.cts +41 -0
- package/dist/types-C_XxdRd1.d.cts +1546 -0
- package/dist/types-CaHcwnKw.d.ts +41 -0
- package/dist/types-DIPZmUl3.d.ts +1546 -0
- package/package.json +126 -0
|
@@ -0,0 +1,2490 @@
|
|
|
1
|
+
import { io } from 'socket.io-client';
|
|
2
|
+
import { createHmac, timingSafeEqual } from 'crypto';
|
|
3
|
+
|
|
4
|
+
// src/errors.ts
|
|
5
|
+
var FirefliesError = class extends Error {
|
|
6
|
+
code = "FIREFLIES_ERROR";
|
|
7
|
+
status;
|
|
8
|
+
constructor(message, options) {
|
|
9
|
+
super(message, { cause: options?.cause });
|
|
10
|
+
this.name = "FirefliesError";
|
|
11
|
+
this.status = options?.status;
|
|
12
|
+
}
|
|
13
|
+
};
|
|
14
|
+
var AuthenticationError = class extends FirefliesError {
|
|
15
|
+
code = "AUTHENTICATION_ERROR";
|
|
16
|
+
constructor(message = "Invalid or missing API key") {
|
|
17
|
+
super(message, { status: 401 });
|
|
18
|
+
this.name = "AuthenticationError";
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
var RateLimitError = class extends FirefliesError {
|
|
22
|
+
code = "RATE_LIMIT_ERROR";
|
|
23
|
+
/** Suggested wait time in milliseconds before retrying. */
|
|
24
|
+
retryAfter;
|
|
25
|
+
constructor(message = "Rate limit exceeded", retryAfter) {
|
|
26
|
+
super(message, { status: 429 });
|
|
27
|
+
this.name = "RateLimitError";
|
|
28
|
+
this.retryAfter = retryAfter;
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
var NotFoundError = class extends FirefliesError {
|
|
32
|
+
code = "NOT_FOUND";
|
|
33
|
+
constructor(message = "Resource not found") {
|
|
34
|
+
super(message, { status: 404 });
|
|
35
|
+
this.name = "NotFoundError";
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
var ValidationError = class extends FirefliesError {
|
|
39
|
+
code = "VALIDATION_ERROR";
|
|
40
|
+
constructor(message) {
|
|
41
|
+
super(message, { status: 400 });
|
|
42
|
+
this.name = "ValidationError";
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
var GraphQLError = class extends FirefliesError {
|
|
46
|
+
code = "GRAPHQL_ERROR";
|
|
47
|
+
errors;
|
|
48
|
+
constructor(message, errors) {
|
|
49
|
+
super(message);
|
|
50
|
+
this.name = "GraphQLError";
|
|
51
|
+
this.errors = errors;
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
var TimeoutError = class extends FirefliesError {
|
|
55
|
+
code = "TIMEOUT_ERROR";
|
|
56
|
+
constructor(message = "Request timed out") {
|
|
57
|
+
super(message, { status: 408 });
|
|
58
|
+
this.name = "TimeoutError";
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
var NetworkError = class extends FirefliesError {
|
|
62
|
+
code = "NETWORK_ERROR";
|
|
63
|
+
constructor(message, cause) {
|
|
64
|
+
super(message, { cause });
|
|
65
|
+
this.name = "NetworkError";
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
var RealtimeError = class extends FirefliesError {
|
|
69
|
+
code = "REALTIME_ERROR";
|
|
70
|
+
constructor(message, options) {
|
|
71
|
+
super(message, options);
|
|
72
|
+
this.name = "RealtimeError";
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
var ConnectionError = class extends RealtimeError {
|
|
76
|
+
code = "CONNECTION_ERROR";
|
|
77
|
+
constructor(message = "Failed to establish realtime connection", options) {
|
|
78
|
+
super(message, options);
|
|
79
|
+
this.name = "ConnectionError";
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
var StreamClosedError = class extends RealtimeError {
|
|
83
|
+
code = "STREAM_CLOSED";
|
|
84
|
+
constructor(message = "Stream has been closed") {
|
|
85
|
+
super(message);
|
|
86
|
+
this.name = "StreamClosedError";
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
var WebhookVerificationError = class extends FirefliesError {
|
|
90
|
+
code = "WEBHOOK_VERIFICATION_FAILED";
|
|
91
|
+
constructor(message) {
|
|
92
|
+
super(message, { status: 401 });
|
|
93
|
+
this.name = "WebhookVerificationError";
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
var WebhookParseError = class extends FirefliesError {
|
|
97
|
+
code = "WEBHOOK_PARSE_FAILED";
|
|
98
|
+
constructor(message) {
|
|
99
|
+
super(message, { status: 400 });
|
|
100
|
+
this.name = "WebhookParseError";
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
function parseErrorResponse(status, body, defaultMessage) {
|
|
104
|
+
const message = extractErrorMessage(body) ?? defaultMessage;
|
|
105
|
+
switch (status) {
|
|
106
|
+
case 401:
|
|
107
|
+
return new AuthenticationError(message);
|
|
108
|
+
case 404:
|
|
109
|
+
return new NotFoundError(message);
|
|
110
|
+
case 429: {
|
|
111
|
+
const retryAfter = extractRetryAfter(body);
|
|
112
|
+
return new RateLimitError(message, retryAfter);
|
|
113
|
+
}
|
|
114
|
+
case 400:
|
|
115
|
+
return new ValidationError(message);
|
|
116
|
+
default:
|
|
117
|
+
return new FirefliesError(message, { status });
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
function extractErrorMessage(body) {
|
|
121
|
+
if (typeof body === "object" && body !== null) {
|
|
122
|
+
const obj = body;
|
|
123
|
+
if (typeof obj.message === "string") {
|
|
124
|
+
return obj.message;
|
|
125
|
+
}
|
|
126
|
+
if (typeof obj.error === "string") {
|
|
127
|
+
return obj.error;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return void 0;
|
|
131
|
+
}
|
|
132
|
+
function extractRetryAfter(body) {
|
|
133
|
+
if (typeof body === "object" && body !== null) {
|
|
134
|
+
const obj = body;
|
|
135
|
+
if (typeof obj.retryAfter === "number") {
|
|
136
|
+
return obj.retryAfter;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
return void 0;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// src/utils/rate-limit-tracker.ts
|
|
143
|
+
var RATE_LIMIT_REMAINING_HEADER = "x-ratelimit-remaining-api";
|
|
144
|
+
var RATE_LIMIT_LIMIT_HEADER = "x-ratelimit-limit-api";
|
|
145
|
+
var RATE_LIMIT_RESET_HEADER = "x-ratelimit-reset-api";
|
|
146
|
+
var RateLimitTracker = class {
|
|
147
|
+
_remaining;
|
|
148
|
+
_limit;
|
|
149
|
+
_resetInSeconds;
|
|
150
|
+
_updatedAt;
|
|
151
|
+
warningThreshold;
|
|
152
|
+
/**
|
|
153
|
+
* Create a new RateLimitTracker.
|
|
154
|
+
* @param warningThreshold - Threshold below which isLow returns true
|
|
155
|
+
*/
|
|
156
|
+
constructor(warningThreshold = 10) {
|
|
157
|
+
this._remaining = void 0;
|
|
158
|
+
this._limit = void 0;
|
|
159
|
+
this._resetInSeconds = void 0;
|
|
160
|
+
this._updatedAt = 0;
|
|
161
|
+
this.warningThreshold = warningThreshold;
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Get the current rate limit state.
|
|
165
|
+
*/
|
|
166
|
+
get state() {
|
|
167
|
+
return {
|
|
168
|
+
remaining: this._remaining,
|
|
169
|
+
limit: this._limit,
|
|
170
|
+
resetInSeconds: this._resetInSeconds,
|
|
171
|
+
updatedAt: this._updatedAt
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Check if remaining requests are below the warning threshold.
|
|
176
|
+
* Returns false if remaining is undefined (header not received).
|
|
177
|
+
*/
|
|
178
|
+
get isLow() {
|
|
179
|
+
return this._remaining !== void 0 && this._remaining < this.warningThreshold;
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Update state from response headers.
|
|
183
|
+
* Extracts x-ratelimit-remaining-api, x-ratelimit-limit-api, and x-ratelimit-reset-api headers.
|
|
184
|
+
*
|
|
185
|
+
* @param headers - Response headers (Headers object or plain object)
|
|
186
|
+
*/
|
|
187
|
+
update(headers) {
|
|
188
|
+
const remaining = this.getHeader(headers, RATE_LIMIT_REMAINING_HEADER);
|
|
189
|
+
if (remaining !== null) {
|
|
190
|
+
const parsed = Number.parseInt(remaining, 10);
|
|
191
|
+
if (!Number.isNaN(parsed) && parsed >= 0) {
|
|
192
|
+
this._remaining = parsed;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
const limit = this.getHeader(headers, RATE_LIMIT_LIMIT_HEADER);
|
|
196
|
+
if (limit !== null) {
|
|
197
|
+
const parsed = Number.parseInt(limit, 10);
|
|
198
|
+
if (!Number.isNaN(parsed) && parsed >= 0) {
|
|
199
|
+
this._limit = parsed;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
const reset = this.getHeader(headers, RATE_LIMIT_RESET_HEADER);
|
|
203
|
+
if (reset !== null) {
|
|
204
|
+
const parsed = Number.parseInt(reset, 10);
|
|
205
|
+
if (!Number.isNaN(parsed) && parsed >= 0) {
|
|
206
|
+
this._resetInSeconds = parsed;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
this._updatedAt = Date.now();
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Reset the tracker to initial state.
|
|
213
|
+
*/
|
|
214
|
+
reset() {
|
|
215
|
+
this._remaining = void 0;
|
|
216
|
+
this._limit = void 0;
|
|
217
|
+
this._resetInSeconds = void 0;
|
|
218
|
+
this._updatedAt = 0;
|
|
219
|
+
}
|
|
220
|
+
/**
|
|
221
|
+
* Calculate the delay to apply before the next request.
|
|
222
|
+
* Returns 0 if throttling is disabled or not needed.
|
|
223
|
+
*
|
|
224
|
+
* Uses linear interpolation: more delay as remaining approaches 0.
|
|
225
|
+
* - remaining >= startThreshold: no delay
|
|
226
|
+
* - remaining = 0: maxDelay
|
|
227
|
+
* - remaining in between: proportional delay
|
|
228
|
+
*
|
|
229
|
+
* @param config - Throttle configuration
|
|
230
|
+
* @returns Delay in milliseconds
|
|
231
|
+
*/
|
|
232
|
+
getThrottleDelay(config) {
|
|
233
|
+
if (!config?.enabled) {
|
|
234
|
+
return 0;
|
|
235
|
+
}
|
|
236
|
+
if (this._remaining === void 0) {
|
|
237
|
+
return 0;
|
|
238
|
+
}
|
|
239
|
+
const startThreshold = Math.max(1, config.startThreshold ?? 20);
|
|
240
|
+
let minDelay = config.minDelay ?? 100;
|
|
241
|
+
let maxDelay = config.maxDelay ?? 2e3;
|
|
242
|
+
if (minDelay > maxDelay) {
|
|
243
|
+
[minDelay, maxDelay] = [maxDelay, minDelay];
|
|
244
|
+
}
|
|
245
|
+
if (this._remaining >= startThreshold) {
|
|
246
|
+
return 0;
|
|
247
|
+
}
|
|
248
|
+
if (this._remaining <= 0) {
|
|
249
|
+
return maxDelay;
|
|
250
|
+
}
|
|
251
|
+
const ratio = 1 - this._remaining / startThreshold;
|
|
252
|
+
return Math.round(minDelay + ratio * (maxDelay - minDelay));
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* Extract a header value from Headers object or plain object.
|
|
256
|
+
* For plain objects, performs case-insensitive key lookup.
|
|
257
|
+
*/
|
|
258
|
+
getHeader(headers, name) {
|
|
259
|
+
if (headers instanceof Headers) {
|
|
260
|
+
return headers.get(name);
|
|
261
|
+
}
|
|
262
|
+
const lowerName = name.toLowerCase();
|
|
263
|
+
for (const key of Object.keys(headers)) {
|
|
264
|
+
if (key.toLowerCase() === lowerName) {
|
|
265
|
+
return headers[key] ?? null;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
return null;
|
|
269
|
+
}
|
|
270
|
+
};
|
|
271
|
+
|
|
272
|
+
// src/utils/retry.ts
|
|
273
|
+
var DEFAULT_OPTIONS = {
|
|
274
|
+
maxRetries: 3,
|
|
275
|
+
baseDelay: 1e3,
|
|
276
|
+
maxDelay: 3e4
|
|
277
|
+
};
|
|
278
|
+
async function retry(fn, options) {
|
|
279
|
+
const maxRetries = options?.maxRetries ?? DEFAULT_OPTIONS.maxRetries;
|
|
280
|
+
const baseDelay = options?.baseDelay ?? DEFAULT_OPTIONS.baseDelay;
|
|
281
|
+
const maxDelay = options?.maxDelay ?? DEFAULT_OPTIONS.maxDelay;
|
|
282
|
+
const shouldRetry = options?.shouldRetry ?? isRetryableError;
|
|
283
|
+
let lastError;
|
|
284
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
285
|
+
try {
|
|
286
|
+
return await fn();
|
|
287
|
+
} catch (error) {
|
|
288
|
+
lastError = error;
|
|
289
|
+
if (attempt >= maxRetries || !shouldRetry(error, attempt)) {
|
|
290
|
+
throw error;
|
|
291
|
+
}
|
|
292
|
+
const delay = calculateDelay(error, attempt, baseDelay, maxDelay);
|
|
293
|
+
await sleep(delay);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
throw lastError;
|
|
297
|
+
}
|
|
298
|
+
function isRetryableError(error) {
|
|
299
|
+
if (error instanceof RateLimitError) {
|
|
300
|
+
return true;
|
|
301
|
+
}
|
|
302
|
+
if (error instanceof TimeoutError) {
|
|
303
|
+
return true;
|
|
304
|
+
}
|
|
305
|
+
if (error instanceof NetworkError) {
|
|
306
|
+
return true;
|
|
307
|
+
}
|
|
308
|
+
if (error instanceof Error && "status" in error && typeof error.status === "number") {
|
|
309
|
+
return error.status >= 500 && error.status < 600;
|
|
310
|
+
}
|
|
311
|
+
return false;
|
|
312
|
+
}
|
|
313
|
+
function calculateDelay(error, attempt, baseDelay, maxDelay) {
|
|
314
|
+
if (error instanceof RateLimitError && error.retryAfter !== void 0) {
|
|
315
|
+
return Math.min(error.retryAfter, maxDelay);
|
|
316
|
+
}
|
|
317
|
+
const exponentialDelay = baseDelay * 2 ** attempt;
|
|
318
|
+
const jitter = Math.random() * 0.1 * exponentialDelay;
|
|
319
|
+
return Math.min(exponentialDelay + jitter, maxDelay);
|
|
320
|
+
}
|
|
321
|
+
function sleep(ms) {
|
|
322
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
// src/graphql/client.ts
|
|
326
|
+
var DEFAULT_BASE_URL = "https://api.fireflies.ai/graphql";
|
|
327
|
+
var DEFAULT_TIMEOUT = 3e4;
|
|
328
|
+
var GraphQLClient = class {
|
|
329
|
+
apiKey;
|
|
330
|
+
baseUrl;
|
|
331
|
+
timeout;
|
|
332
|
+
retryOptions;
|
|
333
|
+
rateLimitTracker;
|
|
334
|
+
rateLimitConfig;
|
|
335
|
+
lastWarningRemaining;
|
|
336
|
+
constructor(config) {
|
|
337
|
+
if (!config.apiKey) {
|
|
338
|
+
throw new FirefliesError("API key is required");
|
|
339
|
+
}
|
|
340
|
+
this.apiKey = config.apiKey;
|
|
341
|
+
this.baseUrl = config.baseUrl ?? DEFAULT_BASE_URL;
|
|
342
|
+
this.timeout = config.timeout ?? DEFAULT_TIMEOUT;
|
|
343
|
+
this.retryOptions = buildRetryOptions(config.retry);
|
|
344
|
+
if (config.rateLimit) {
|
|
345
|
+
const warningThreshold = config.rateLimit.warningThreshold ?? 10;
|
|
346
|
+
this.rateLimitTracker = new RateLimitTracker(warningThreshold);
|
|
347
|
+
this.rateLimitConfig = config.rateLimit;
|
|
348
|
+
} else {
|
|
349
|
+
this.rateLimitTracker = null;
|
|
350
|
+
this.rateLimitConfig = null;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
/**
|
|
354
|
+
* Get the current rate limit state.
|
|
355
|
+
* Returns undefined if rate limit tracking is not configured.
|
|
356
|
+
*/
|
|
357
|
+
get rateLimitState() {
|
|
358
|
+
return this.rateLimitTracker?.state;
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* Execute a GraphQL query or mutation.
|
|
362
|
+
*
|
|
363
|
+
* @param query - GraphQL query string
|
|
364
|
+
* @param variables - Optional query variables
|
|
365
|
+
* @returns The data from the GraphQL response
|
|
366
|
+
* @throws GraphQLError if the response contains errors
|
|
367
|
+
* @throws AuthenticationError if the API key is invalid
|
|
368
|
+
* @throws RateLimitError if rate limits are exceeded
|
|
369
|
+
*/
|
|
370
|
+
async execute(query, variables) {
|
|
371
|
+
return retry(() => this.executeOnce(query, variables), this.retryOptions);
|
|
372
|
+
}
|
|
373
|
+
async executeOnce(query, variables) {
|
|
374
|
+
await this.applyThrottleDelay();
|
|
375
|
+
const controller = new AbortController();
|
|
376
|
+
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
|
|
377
|
+
try {
|
|
378
|
+
const response = await fetch(this.baseUrl, {
|
|
379
|
+
method: "POST",
|
|
380
|
+
headers: {
|
|
381
|
+
"Content-Type": "application/json",
|
|
382
|
+
Authorization: `Bearer ${this.apiKey}`
|
|
383
|
+
},
|
|
384
|
+
body: JSON.stringify({ query, variables }),
|
|
385
|
+
signal: controller.signal
|
|
386
|
+
});
|
|
387
|
+
clearTimeout(timeoutId);
|
|
388
|
+
this.updateRateLimitState(response.headers);
|
|
389
|
+
if (!response.ok) {
|
|
390
|
+
const body = await this.safeParseJson(response);
|
|
391
|
+
if (response.status === 429) {
|
|
392
|
+
const retryAfter = this.parseRetryAfter(response.headers);
|
|
393
|
+
this.invokeRateLimitedCallback(retryAfter);
|
|
394
|
+
throw parseErrorResponse(
|
|
395
|
+
response.status,
|
|
396
|
+
body,
|
|
397
|
+
`GraphQL request failed with status ${response.status}`
|
|
398
|
+
);
|
|
399
|
+
}
|
|
400
|
+
throw parseErrorResponse(
|
|
401
|
+
response.status,
|
|
402
|
+
body,
|
|
403
|
+
`GraphQL request failed with status ${response.status}`
|
|
404
|
+
);
|
|
405
|
+
}
|
|
406
|
+
const json = await response.json();
|
|
407
|
+
if (json.errors && json.errors.length > 0) {
|
|
408
|
+
throw this.parseGraphQLErrors(json.errors);
|
|
409
|
+
}
|
|
410
|
+
if (json.data === void 0) {
|
|
411
|
+
throw new FirefliesError("GraphQL response missing data field");
|
|
412
|
+
}
|
|
413
|
+
return json.data;
|
|
414
|
+
} catch (error) {
|
|
415
|
+
clearTimeout(timeoutId);
|
|
416
|
+
if (error instanceof FirefliesError) {
|
|
417
|
+
throw error;
|
|
418
|
+
}
|
|
419
|
+
if (error instanceof Error) {
|
|
420
|
+
if (error.name === "AbortError") {
|
|
421
|
+
throw new TimeoutError(`Request timed out after ${this.timeout}ms`);
|
|
422
|
+
}
|
|
423
|
+
throw new NetworkError(`Network request failed: ${error.message}`, error);
|
|
424
|
+
}
|
|
425
|
+
throw new NetworkError("Unknown network error occurred", error);
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
async safeParseJson(response) {
|
|
429
|
+
try {
|
|
430
|
+
return await response.json();
|
|
431
|
+
} catch {
|
|
432
|
+
return null;
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
/**
|
|
436
|
+
* Apply throttle delay before request if configured.
|
|
437
|
+
*/
|
|
438
|
+
async applyThrottleDelay() {
|
|
439
|
+
if (!this.rateLimitTracker || !this.rateLimitConfig?.throttle) {
|
|
440
|
+
return;
|
|
441
|
+
}
|
|
442
|
+
const delay = this.rateLimitTracker.getThrottleDelay(this.rateLimitConfig.throttle);
|
|
443
|
+
if (delay > 0) {
|
|
444
|
+
await sleep2(delay);
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
/**
|
|
448
|
+
* Update rate limit state from response headers and invoke callbacks.
|
|
449
|
+
*/
|
|
450
|
+
updateRateLimitState(headers) {
|
|
451
|
+
if (!this.rateLimitTracker || !this.rateLimitConfig) {
|
|
452
|
+
return;
|
|
453
|
+
}
|
|
454
|
+
const wasLow = this.rateLimitTracker.isLow;
|
|
455
|
+
this.rateLimitTracker.update(headers);
|
|
456
|
+
const state = this.rateLimitTracker.state;
|
|
457
|
+
this.safeCallback(() => this.rateLimitConfig?.onUpdate?.(state));
|
|
458
|
+
if (this.rateLimitTracker.isLow) {
|
|
459
|
+
const shouldWarn = !wasLow || // Just crossed threshold
|
|
460
|
+
state.remaining !== void 0 && this.lastWarningRemaining !== void 0 && state.remaining < this.lastWarningRemaining;
|
|
461
|
+
if (shouldWarn) {
|
|
462
|
+
this.lastWarningRemaining = state.remaining;
|
|
463
|
+
this.safeCallback(() => this.rateLimitConfig?.onWarning?.(state));
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
/**
|
|
468
|
+
* Parse Retry-After header value.
|
|
469
|
+
*/
|
|
470
|
+
parseRetryAfter(headers) {
|
|
471
|
+
const value = headers.get("retry-after");
|
|
472
|
+
if (!value) return void 0;
|
|
473
|
+
const parsed = Number.parseInt(value, 10);
|
|
474
|
+
return Number.isNaN(parsed) ? void 0 : parsed;
|
|
475
|
+
}
|
|
476
|
+
/**
|
|
477
|
+
* Invoke the onRateLimited callback.
|
|
478
|
+
*/
|
|
479
|
+
invokeRateLimitedCallback(retryAfter) {
|
|
480
|
+
if (!this.rateLimitTracker || !this.rateLimitConfig?.onRateLimited) {
|
|
481
|
+
return;
|
|
482
|
+
}
|
|
483
|
+
const state = this.rateLimitTracker.state;
|
|
484
|
+
this.safeCallback(() => this.rateLimitConfig?.onRateLimited?.(state, retryAfter));
|
|
485
|
+
}
|
|
486
|
+
/**
|
|
487
|
+
* Safely invoke a callback, catching any errors to prevent user code from breaking the SDK.
|
|
488
|
+
*/
|
|
489
|
+
safeCallback(fn) {
|
|
490
|
+
try {
|
|
491
|
+
fn();
|
|
492
|
+
} catch {
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
parseGraphQLErrors(errors) {
|
|
496
|
+
const firstError = errors[0];
|
|
497
|
+
if (!firstError) {
|
|
498
|
+
return new GraphQLError("Unknown GraphQL error", errors);
|
|
499
|
+
}
|
|
500
|
+
const message = firstError.message;
|
|
501
|
+
if (message.toLowerCase().includes("unauthorized") || message.toLowerCase().includes("authentication")) {
|
|
502
|
+
return parseErrorResponse(401, { message }, message);
|
|
503
|
+
}
|
|
504
|
+
if (message.toLowerCase().includes("not found")) {
|
|
505
|
+
return parseErrorResponse(404, { message }, message);
|
|
506
|
+
}
|
|
507
|
+
return new GraphQLError(message, errors);
|
|
508
|
+
}
|
|
509
|
+
};
|
|
510
|
+
function buildRetryOptions(config) {
|
|
511
|
+
if (!config) {
|
|
512
|
+
return {};
|
|
513
|
+
}
|
|
514
|
+
return {
|
|
515
|
+
maxRetries: config.maxRetries,
|
|
516
|
+
baseDelay: config.baseDelay,
|
|
517
|
+
maxDelay: config.maxDelay
|
|
518
|
+
};
|
|
519
|
+
}
|
|
520
|
+
function sleep2(ms) {
|
|
521
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
// src/graphql/mutations/audio.ts
|
|
525
|
+
function createAudioAPI(client) {
|
|
526
|
+
return {
|
|
527
|
+
async upload(params) {
|
|
528
|
+
const mutation = `
|
|
529
|
+
mutation UploadAudio($input: AudioUploadInput!) {
|
|
530
|
+
uploadAudio(input: $input) {
|
|
531
|
+
success
|
|
532
|
+
title
|
|
533
|
+
message
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
`;
|
|
537
|
+
const data = await client.execute(mutation, {
|
|
538
|
+
input: params
|
|
539
|
+
});
|
|
540
|
+
return data.uploadAudio;
|
|
541
|
+
}
|
|
542
|
+
};
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
// src/graphql/mutations/transcripts.ts
|
|
546
|
+
function createTranscriptsMutationsAPI(client) {
|
|
547
|
+
return {
|
|
548
|
+
async delete(id) {
|
|
549
|
+
const mutation = `
|
|
550
|
+
mutation deleteTranscript($id: String!) {
|
|
551
|
+
deleteTranscript(id: $id) {
|
|
552
|
+
id
|
|
553
|
+
title
|
|
554
|
+
organizer_email
|
|
555
|
+
date
|
|
556
|
+
duration
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
`;
|
|
560
|
+
const data = await client.execute(mutation, { id });
|
|
561
|
+
return data.deleteTranscript;
|
|
562
|
+
}
|
|
563
|
+
};
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
// src/graphql/mutations/users.ts
|
|
567
|
+
function createUsersMutationsAPI(client) {
|
|
568
|
+
return {
|
|
569
|
+
async setRole(userId, role) {
|
|
570
|
+
const mutation = `
|
|
571
|
+
mutation setUserRole($userId: String!, $role: Role!) {
|
|
572
|
+
setUserRole(user_id: $userId, role: $role) {
|
|
573
|
+
id
|
|
574
|
+
name
|
|
575
|
+
email
|
|
576
|
+
role
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
`;
|
|
580
|
+
const data = await client.execute(mutation, {
|
|
581
|
+
userId,
|
|
582
|
+
role
|
|
583
|
+
});
|
|
584
|
+
return data.setUserRole;
|
|
585
|
+
}
|
|
586
|
+
};
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
// src/helpers/pagination.ts
|
|
590
|
+
async function* paginate(fetcher, pageSize = 50) {
|
|
591
|
+
let skip = 0;
|
|
592
|
+
let hasMore = true;
|
|
593
|
+
while (hasMore) {
|
|
594
|
+
const page = await fetcher(skip, pageSize);
|
|
595
|
+
for (const item of page) {
|
|
596
|
+
yield item;
|
|
597
|
+
}
|
|
598
|
+
if (page.length < pageSize) {
|
|
599
|
+
hasMore = false;
|
|
600
|
+
} else {
|
|
601
|
+
skip += pageSize;
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
// src/graphql/queries/ai-apps.ts
|
|
607
|
+
var AI_APP_OUTPUT_FIELDS = `
|
|
608
|
+
transcript_id
|
|
609
|
+
user_id
|
|
610
|
+
app_id
|
|
611
|
+
created_at
|
|
612
|
+
title
|
|
613
|
+
prompt
|
|
614
|
+
response
|
|
615
|
+
`;
|
|
616
|
+
function createAIAppsAPI(client) {
|
|
617
|
+
return {
|
|
618
|
+
async list(params) {
|
|
619
|
+
const query = `
|
|
620
|
+
query GetAIAppsOutputs(
|
|
621
|
+
$appId: String
|
|
622
|
+
$transcriptId: String
|
|
623
|
+
$skip: Float
|
|
624
|
+
$limit: Float
|
|
625
|
+
) {
|
|
626
|
+
apps(
|
|
627
|
+
app_id: $appId
|
|
628
|
+
transcript_id: $transcriptId
|
|
629
|
+
skip: $skip
|
|
630
|
+
limit: $limit
|
|
631
|
+
) {
|
|
632
|
+
outputs { ${AI_APP_OUTPUT_FIELDS} }
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
`;
|
|
636
|
+
const data = await client.execute(query, {
|
|
637
|
+
appId: params?.app_id,
|
|
638
|
+
transcriptId: params?.transcript_id,
|
|
639
|
+
skip: params?.skip,
|
|
640
|
+
limit: params?.limit ?? 10
|
|
641
|
+
});
|
|
642
|
+
return data.apps.outputs;
|
|
643
|
+
},
|
|
644
|
+
listAll(params) {
|
|
645
|
+
return paginate((skip, limit) => this.list({ ...params, skip, limit }), 10);
|
|
646
|
+
}
|
|
647
|
+
};
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
// src/graphql/queries/bites.ts
|
|
651
|
+
var BITE_FIELDS = `
|
|
652
|
+
id
|
|
653
|
+
transcript_id
|
|
654
|
+
user_id
|
|
655
|
+
name
|
|
656
|
+
status
|
|
657
|
+
summary
|
|
658
|
+
summary_status
|
|
659
|
+
media_type
|
|
660
|
+
start_time
|
|
661
|
+
end_time
|
|
662
|
+
created_at
|
|
663
|
+
thumbnail
|
|
664
|
+
preview
|
|
665
|
+
captions {
|
|
666
|
+
index
|
|
667
|
+
text
|
|
668
|
+
start_time
|
|
669
|
+
end_time
|
|
670
|
+
speaker_id
|
|
671
|
+
speaker_name
|
|
672
|
+
}
|
|
673
|
+
sources {
|
|
674
|
+
src
|
|
675
|
+
type
|
|
676
|
+
}
|
|
677
|
+
user {
|
|
678
|
+
id
|
|
679
|
+
name
|
|
680
|
+
first_name
|
|
681
|
+
last_name
|
|
682
|
+
picture
|
|
683
|
+
}
|
|
684
|
+
created_from {
|
|
685
|
+
id
|
|
686
|
+
name
|
|
687
|
+
type
|
|
688
|
+
description
|
|
689
|
+
duration
|
|
690
|
+
}
|
|
691
|
+
privacies
|
|
692
|
+
`;
|
|
693
|
+
function createBitesAPI(client) {
|
|
694
|
+
return {
|
|
695
|
+
async get(id) {
|
|
696
|
+
const query = `
|
|
697
|
+
query Bite($biteId: ID!) {
|
|
698
|
+
bite(id: $biteId) { ${BITE_FIELDS} }
|
|
699
|
+
}
|
|
700
|
+
`;
|
|
701
|
+
const data = await client.execute(query, { biteId: id });
|
|
702
|
+
return data.bite;
|
|
703
|
+
},
|
|
704
|
+
async list(params) {
|
|
705
|
+
const query = `
|
|
706
|
+
query Bites(
|
|
707
|
+
$transcriptId: ID
|
|
708
|
+
$mine: Boolean
|
|
709
|
+
$myTeam: Boolean
|
|
710
|
+
$limit: Int
|
|
711
|
+
$skip: Int
|
|
712
|
+
) {
|
|
713
|
+
bites(
|
|
714
|
+
transcript_id: $transcriptId
|
|
715
|
+
mine: $mine
|
|
716
|
+
my_team: $myTeam
|
|
717
|
+
limit: $limit
|
|
718
|
+
skip: $skip
|
|
719
|
+
) { ${BITE_FIELDS} }
|
|
720
|
+
}
|
|
721
|
+
`;
|
|
722
|
+
const data = await client.execute(query, {
|
|
723
|
+
transcriptId: params.transcript_id,
|
|
724
|
+
mine: params.mine,
|
|
725
|
+
myTeam: params.my_team,
|
|
726
|
+
limit: params.limit ?? 50,
|
|
727
|
+
skip: params.skip
|
|
728
|
+
});
|
|
729
|
+
return data.bites;
|
|
730
|
+
},
|
|
731
|
+
listAll(params) {
|
|
732
|
+
return paginate((skip, limit) => this.list({ ...params, skip, limit }), 50);
|
|
733
|
+
},
|
|
734
|
+
async create(params) {
|
|
735
|
+
const mutation = `
|
|
736
|
+
mutation CreateBite(
|
|
737
|
+
$transcriptId: ID!
|
|
738
|
+
$startTime: Float!
|
|
739
|
+
$endTime: Float!
|
|
740
|
+
$name: String
|
|
741
|
+
$mediaType: String
|
|
742
|
+
$summary: String
|
|
743
|
+
$privacies: [BitePrivacy!]
|
|
744
|
+
) {
|
|
745
|
+
createBite(
|
|
746
|
+
transcript_Id: $transcriptId
|
|
747
|
+
start_time: $startTime
|
|
748
|
+
end_time: $endTime
|
|
749
|
+
name: $name
|
|
750
|
+
media_type: $mediaType
|
|
751
|
+
summary: $summary
|
|
752
|
+
privacies: $privacies
|
|
753
|
+
) {
|
|
754
|
+
id
|
|
755
|
+
name
|
|
756
|
+
status
|
|
757
|
+
summary
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
`;
|
|
761
|
+
const data = await client.execute(mutation, {
|
|
762
|
+
transcriptId: params.transcript_id,
|
|
763
|
+
startTime: params.start_time,
|
|
764
|
+
endTime: params.end_time,
|
|
765
|
+
name: params.name,
|
|
766
|
+
mediaType: params.media_type,
|
|
767
|
+
summary: params.summary,
|
|
768
|
+
privacies: params.privacies
|
|
769
|
+
});
|
|
770
|
+
return data.createBite;
|
|
771
|
+
}
|
|
772
|
+
};
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
// src/graphql/queries/meetings.ts
|
|
776
|
+
var ACTIVE_MEETING_FIELDS = `
|
|
777
|
+
id
|
|
778
|
+
title
|
|
779
|
+
organizer_email
|
|
780
|
+
meeting_link
|
|
781
|
+
start_time
|
|
782
|
+
end_time
|
|
783
|
+
privacy
|
|
784
|
+
state
|
|
785
|
+
`;
|
|
786
|
+
function createMeetingsAPI(client) {
|
|
787
|
+
return {
|
|
788
|
+
async active(params) {
|
|
789
|
+
const query = `
|
|
790
|
+
query ActiveMeetings($email: String, $states: [MeetingState!]) {
|
|
791
|
+
active_meetings(input: { email: $email, states: $states }) {
|
|
792
|
+
${ACTIVE_MEETING_FIELDS}
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
`;
|
|
796
|
+
const data = await client.execute(query, {
|
|
797
|
+
email: params?.email,
|
|
798
|
+
states: params?.states
|
|
799
|
+
});
|
|
800
|
+
return data.active_meetings;
|
|
801
|
+
},
|
|
802
|
+
async addBot(params) {
|
|
803
|
+
const mutation = `
|
|
804
|
+
mutation AddToLiveMeeting(
|
|
805
|
+
$meetingLink: String!
|
|
806
|
+
$title: String
|
|
807
|
+
$meetingPassword: String
|
|
808
|
+
$duration: Int
|
|
809
|
+
$language: String
|
|
810
|
+
) {
|
|
811
|
+
addToLiveMeeting(
|
|
812
|
+
meeting_link: $meetingLink
|
|
813
|
+
title: $title
|
|
814
|
+
meeting_password: $meetingPassword
|
|
815
|
+
duration: $duration
|
|
816
|
+
language: $language
|
|
817
|
+
) {
|
|
818
|
+
success
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
`;
|
|
822
|
+
const data = await client.execute(mutation, {
|
|
823
|
+
meetingLink: params.meeting_link,
|
|
824
|
+
title: params.title,
|
|
825
|
+
meetingPassword: params.password,
|
|
826
|
+
duration: params.duration,
|
|
827
|
+
language: params.language
|
|
828
|
+
});
|
|
829
|
+
return data.addToLiveMeeting;
|
|
830
|
+
}
|
|
831
|
+
};
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
// src/helpers/action-items.ts
|
|
835
|
+
var ASSIGNEE_PATTERNS = [
|
|
836
|
+
{ pattern: /@(\w+)/i, group: 1 },
|
|
837
|
+
// @Alice
|
|
838
|
+
{ pattern: /^(\w+):/i, group: 1 },
|
|
839
|
+
// Alice: at start
|
|
840
|
+
{ pattern: /assigned to (\w+)/i, group: 1 },
|
|
841
|
+
// assigned to Alice
|
|
842
|
+
{ pattern: /(\w+) will\b/i, group: 1 },
|
|
843
|
+
// Alice will
|
|
844
|
+
{ pattern: /(\w+) to\b/i, group: 1 },
|
|
845
|
+
// Alice to (do something)
|
|
846
|
+
{ pattern: /\s-\s*(\w+)$/i, group: 1 }
|
|
847
|
+
// ... - Alice
|
|
848
|
+
];
|
|
849
|
+
var DUE_DATE_PATTERNS = [
|
|
850
|
+
{ pattern: /by (monday|tuesday|wednesday|thursday|friday|saturday|sunday)/i, group: 1 },
|
|
851
|
+
{ pattern: /by (tomorrow|today)/i, group: 1 },
|
|
852
|
+
{ pattern: /by (EOD|end of day)/i, group: 1 },
|
|
853
|
+
{ pattern: /by (EOW|end of week)/i, group: 1 },
|
|
854
|
+
{ pattern: /due (\d{4}-\d{2}-\d{2})/i, group: 1 },
|
|
855
|
+
{ pattern: /due (jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\s+\d+/i, group: 0 },
|
|
856
|
+
{ pattern: /by (\d{1,2}\/\d{1,2})/i, group: 1 }
|
|
857
|
+
];
|
|
858
|
+
var LIST_PREFIX_PATTERN = /^(?:[-•*]|\d+\.)\s*/;
|
|
859
|
+
var SECTION_HEADER_PATTERN = /^\*\*(.+)\*\*$/;
|
|
860
|
+
function extractActionItems(transcript, options = {}) {
|
|
861
|
+
const actionItemsText = transcript.summary?.action_items;
|
|
862
|
+
if (!actionItemsText || actionItemsText.trim().length === 0) {
|
|
863
|
+
return emptyResult();
|
|
864
|
+
}
|
|
865
|
+
const config = {
|
|
866
|
+
detectAssignees: options.detectAssignees ?? true,
|
|
867
|
+
detectDueDates: options.detectDueDates ?? true,
|
|
868
|
+
includeSourceSentences: options.includeSourceSentences ?? false,
|
|
869
|
+
participantNames: options.participantNames ?? []
|
|
870
|
+
};
|
|
871
|
+
const taskSentences = config.includeSourceSentences ? buildTaskSentenceLookup(transcript) : [];
|
|
872
|
+
const lines = actionItemsText.split(/\n/);
|
|
873
|
+
return parseAllLines(lines, config, taskSentences);
|
|
874
|
+
}
|
|
875
|
+
function parseAllLines(lines, config, taskSentences) {
|
|
876
|
+
const items = [];
|
|
877
|
+
const assigneeSet = /* @__PURE__ */ new Set();
|
|
878
|
+
let currentSectionAssignee;
|
|
879
|
+
for (let i = 0; i < lines.length; i++) {
|
|
880
|
+
const result = processLine(lines[i], i + 1, config, taskSentences, currentSectionAssignee);
|
|
881
|
+
if (result.type === "header") {
|
|
882
|
+
currentSectionAssignee = result.assignee;
|
|
883
|
+
} else if (result.type === "item" && result.item) {
|
|
884
|
+
items.push(result.item);
|
|
885
|
+
if (result.item.assignee) {
|
|
886
|
+
assigneeSet.add(result.item.assignee);
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
return buildResult(items, assigneeSet);
|
|
891
|
+
}
|
|
892
|
+
function processLine(line, lineNumber, config, taskSentences, sectionAssignee) {
|
|
893
|
+
if (!line) return { type: "skip" };
|
|
894
|
+
const trimmed = line.trim();
|
|
895
|
+
if (trimmed.length === 0) return { type: "skip" };
|
|
896
|
+
const headerMatch = trimmed.match(SECTION_HEADER_PATTERN);
|
|
897
|
+
if (headerMatch?.[1]) {
|
|
898
|
+
const headerName = headerMatch[1];
|
|
899
|
+
const assignee = headerName.toLowerCase() === "unassigned" ? void 0 : headerName;
|
|
900
|
+
return { type: "header", assignee };
|
|
901
|
+
}
|
|
902
|
+
const item = parseLine(line, lineNumber, config, taskSentences, sectionAssignee);
|
|
903
|
+
if (item) {
|
|
904
|
+
return { type: "item", item };
|
|
905
|
+
}
|
|
906
|
+
return { type: "skip" };
|
|
907
|
+
}
|
|
908
|
+
function parseLine(line, lineNumber, config, taskSentences, sectionAssignee) {
|
|
909
|
+
if (!line) return null;
|
|
910
|
+
const trimmed = line.trim();
|
|
911
|
+
if (trimmed.length === 0) return null;
|
|
912
|
+
const text = trimmed.replace(LIST_PREFIX_PATTERN, "");
|
|
913
|
+
if (text.length === 0) return null;
|
|
914
|
+
const inlineAssignee = config.detectAssignees ? detectAssignee(text, config.participantNames) : void 0;
|
|
915
|
+
const assignee = inlineAssignee ?? sectionAssignee;
|
|
916
|
+
const dueDate = config.detectDueDates ? detectDueDate(text) : void 0;
|
|
917
|
+
const sourceSentence = config.includeSourceSentences ? findSourceSentence(text, taskSentences) : void 0;
|
|
918
|
+
return { text, assignee, dueDate, lineNumber, sourceSentence };
|
|
919
|
+
}
|
|
920
|
+
function buildResult(items, assigneeSet) {
|
|
921
|
+
return {
|
|
922
|
+
items,
|
|
923
|
+
totalItems: items.length,
|
|
924
|
+
assignedItems: items.filter((i) => i.assignee !== void 0).length,
|
|
925
|
+
datedItems: items.filter((i) => i.dueDate !== void 0).length,
|
|
926
|
+
assignees: Array.from(assigneeSet)
|
|
927
|
+
};
|
|
928
|
+
}
|
|
929
|
+
function emptyResult() {
|
|
930
|
+
return {
|
|
931
|
+
items: [],
|
|
932
|
+
totalItems: 0,
|
|
933
|
+
assignedItems: 0,
|
|
934
|
+
datedItems: 0,
|
|
935
|
+
assignees: []
|
|
936
|
+
};
|
|
937
|
+
}
|
|
938
|
+
function detectAssignee(text, participantNames) {
|
|
939
|
+
const participantSet = new Set(participantNames.map((n) => n.toLowerCase()));
|
|
940
|
+
const filterByParticipants = participantSet.size > 0;
|
|
941
|
+
for (const { pattern, group } of ASSIGNEE_PATTERNS) {
|
|
942
|
+
const match = text.match(pattern);
|
|
943
|
+
if (match?.[group]) {
|
|
944
|
+
const name = match[group];
|
|
945
|
+
if (filterByParticipants) {
|
|
946
|
+
if (participantSet.has(name.toLowerCase())) {
|
|
947
|
+
return name;
|
|
948
|
+
}
|
|
949
|
+
continue;
|
|
950
|
+
}
|
|
951
|
+
return name;
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
return void 0;
|
|
955
|
+
}
|
|
956
|
+
function detectDueDate(text) {
|
|
957
|
+
for (const { pattern, group } of DUE_DATE_PATTERNS) {
|
|
958
|
+
const match = text.match(pattern);
|
|
959
|
+
if (match) {
|
|
960
|
+
if (group === 0 && match[0]) {
|
|
961
|
+
const fullMatch = match[0];
|
|
962
|
+
const dateMatch = fullMatch.match(
|
|
963
|
+
/(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\s+\d+/i
|
|
964
|
+
);
|
|
965
|
+
if (dateMatch?.[0]) {
|
|
966
|
+
return dateMatch[0];
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
if (match[group]) {
|
|
970
|
+
return match[group];
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
return void 0;
|
|
975
|
+
}
|
|
976
|
+
function buildTaskSentenceLookup(transcript) {
|
|
977
|
+
const sentences = transcript.sentences ?? [];
|
|
978
|
+
const result = [];
|
|
979
|
+
for (const sentence of sentences) {
|
|
980
|
+
const task = sentence.ai_filters?.task;
|
|
981
|
+
if (task) {
|
|
982
|
+
result.push({
|
|
983
|
+
text: sentence.text,
|
|
984
|
+
task: task.toLowerCase(),
|
|
985
|
+
speakerName: sentence.speaker_name,
|
|
986
|
+
startTime: Number.parseFloat(sentence.start_time)
|
|
987
|
+
});
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
return result;
|
|
991
|
+
}
|
|
992
|
+
function findSourceSentence(actionItemText, taskSentences) {
|
|
993
|
+
const normalizedItem = actionItemText.toLowerCase();
|
|
994
|
+
for (const sentence of taskSentences) {
|
|
995
|
+
if (normalizedItem.includes(sentence.task) || sentence.task.includes(normalizedItem)) {
|
|
996
|
+
return {
|
|
997
|
+
speakerName: sentence.speakerName,
|
|
998
|
+
text: sentence.text,
|
|
999
|
+
startTime: sentence.startTime
|
|
1000
|
+
};
|
|
1001
|
+
}
|
|
1002
|
+
const itemWords = new Set(normalizedItem.split(/\s+/).filter((w) => w.length > 3));
|
|
1003
|
+
const taskWords = sentence.task.split(/\s+/).filter((w) => w.length > 3);
|
|
1004
|
+
const matchingWords = taskWords.filter((w) => itemWords.has(w));
|
|
1005
|
+
if (taskWords.length > 0 && matchingWords.length / taskWords.length >= 0.5) {
|
|
1006
|
+
return {
|
|
1007
|
+
speakerName: sentence.speakerName,
|
|
1008
|
+
text: sentence.text,
|
|
1009
|
+
startTime: sentence.startTime
|
|
1010
|
+
};
|
|
1011
|
+
}
|
|
1012
|
+
}
|
|
1013
|
+
return void 0;
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
// src/helpers/action-items-format.ts
|
|
1017
|
+
function filterActionItems(items, options) {
|
|
1018
|
+
const { assignees, assignedOnly, datedOnly } = options;
|
|
1019
|
+
const normalizedAssignees = assignees?.map((a) => a.toLowerCase());
|
|
1020
|
+
return items.filter((item) => {
|
|
1021
|
+
if (normalizedAssignees && normalizedAssignees.length > 0) {
|
|
1022
|
+
if (!item.assignee) return false;
|
|
1023
|
+
if (!normalizedAssignees.includes(item.assignee.toLowerCase())) return false;
|
|
1024
|
+
}
|
|
1025
|
+
if (assignedOnly && !item.assignee) {
|
|
1026
|
+
return false;
|
|
1027
|
+
}
|
|
1028
|
+
if (datedOnly && !item.dueDate) {
|
|
1029
|
+
return false;
|
|
1030
|
+
}
|
|
1031
|
+
return true;
|
|
1032
|
+
});
|
|
1033
|
+
}
|
|
1034
|
+
function aggregateActionItems(transcripts, extractionOptions, filterOptions) {
|
|
1035
|
+
if (transcripts.length === 0) {
|
|
1036
|
+
return emptyAggregatedResult();
|
|
1037
|
+
}
|
|
1038
|
+
const allItems = [];
|
|
1039
|
+
let transcriptsWithItems = 0;
|
|
1040
|
+
for (const transcript of transcripts) {
|
|
1041
|
+
const extracted = extractActionItems(transcript, extractionOptions);
|
|
1042
|
+
if (extracted.items.length > 0) {
|
|
1043
|
+
transcriptsWithItems++;
|
|
1044
|
+
for (const item of extracted.items) {
|
|
1045
|
+
allItems.push({
|
|
1046
|
+
...item,
|
|
1047
|
+
transcriptId: transcript.id,
|
|
1048
|
+
transcriptTitle: transcript.title,
|
|
1049
|
+
transcriptDate: transcript.dateString
|
|
1050
|
+
});
|
|
1051
|
+
}
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1054
|
+
const filteredItems = filterOptions ? filterActionItems(allItems, filterOptions) : allItems;
|
|
1055
|
+
return buildAggregatedResult(filteredItems, transcripts.length, transcriptsWithItems);
|
|
1056
|
+
}
|
|
1057
|
+
function emptyAggregatedResult() {
|
|
1058
|
+
return {
|
|
1059
|
+
items: [],
|
|
1060
|
+
totalItems: 0,
|
|
1061
|
+
transcriptsProcessed: 0,
|
|
1062
|
+
transcriptsWithItems: 0,
|
|
1063
|
+
assignedItems: 0,
|
|
1064
|
+
datedItems: 0,
|
|
1065
|
+
assignees: [],
|
|
1066
|
+
dateRange: { earliest: "", latest: "" }
|
|
1067
|
+
};
|
|
1068
|
+
}
|
|
1069
|
+
function buildAggregatedResult(items, transcriptsProcessed, transcriptsWithItems) {
|
|
1070
|
+
const assigneeSet = /* @__PURE__ */ new Set();
|
|
1071
|
+
let assignedItems = 0;
|
|
1072
|
+
let datedItems = 0;
|
|
1073
|
+
for (const item of items) {
|
|
1074
|
+
if (item.assignee) {
|
|
1075
|
+
assigneeSet.add(item.assignee);
|
|
1076
|
+
assignedItems++;
|
|
1077
|
+
}
|
|
1078
|
+
if (item.dueDate) {
|
|
1079
|
+
datedItems++;
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
const dates = items.map((i) => i.transcriptDate).filter(Boolean).sort();
|
|
1083
|
+
return {
|
|
1084
|
+
items,
|
|
1085
|
+
totalItems: items.length,
|
|
1086
|
+
transcriptsProcessed,
|
|
1087
|
+
transcriptsWithItems,
|
|
1088
|
+
assignedItems,
|
|
1089
|
+
datedItems,
|
|
1090
|
+
assignees: Array.from(assigneeSet),
|
|
1091
|
+
dateRange: {
|
|
1092
|
+
earliest: dates[0] ?? "",
|
|
1093
|
+
latest: dates[dates.length - 1] ?? ""
|
|
1094
|
+
}
|
|
1095
|
+
};
|
|
1096
|
+
}
|
|
1097
|
+
|
|
1098
|
+
// src/helpers/domain-utils.ts
|
|
1099
|
+
function extractDomain(email) {
|
|
1100
|
+
const atIndex = email.indexOf("@");
|
|
1101
|
+
if (atIndex < 0) return "";
|
|
1102
|
+
const domain = email.slice(atIndex + 1).toLowerCase();
|
|
1103
|
+
return domain || "";
|
|
1104
|
+
}
|
|
1105
|
+
function hasExternalParticipants(participants, internalDomain) {
|
|
1106
|
+
const normalizedInternal = internalDomain.toLowerCase();
|
|
1107
|
+
return participants.some((email) => {
|
|
1108
|
+
const domain = extractDomain(email);
|
|
1109
|
+
return domain !== "" && domain !== normalizedInternal;
|
|
1110
|
+
});
|
|
1111
|
+
}
|
|
1112
|
+
|
|
1113
|
+
// src/helpers/meeting-insights.ts
|
|
1114
|
+
function analyzeMeetings(transcripts, options = {}) {
|
|
1115
|
+
const { speakers, groupBy, topSpeakersCount = 10, topParticipantsCount = 10 } = options;
|
|
1116
|
+
if (transcripts.length === 0) {
|
|
1117
|
+
return emptyInsights();
|
|
1118
|
+
}
|
|
1119
|
+
const totalDurationMinutes = sumDurations(transcripts);
|
|
1120
|
+
const averageDurationMinutes = totalDurationMinutes / transcripts.length;
|
|
1121
|
+
const byDayOfWeek = calculateDayOfWeekStats(transcripts);
|
|
1122
|
+
const byTimeGroup = groupBy ? calculateTimeGroupStats(transcripts, groupBy) : void 0;
|
|
1123
|
+
const participantData = aggregateParticipants(transcripts);
|
|
1124
|
+
const totalUniqueParticipants = participantData.uniqueEmails.size;
|
|
1125
|
+
const averageParticipantsPerMeeting = calculateAverageParticipants(transcripts);
|
|
1126
|
+
const topParticipants = buildTopParticipants(participantData.stats, topParticipantsCount);
|
|
1127
|
+
const speakerData = aggregateSpeakers(transcripts, speakers);
|
|
1128
|
+
const totalUniqueSpeakers = speakerData.uniqueNames.size;
|
|
1129
|
+
const topSpeakers = buildTopSpeakers(speakerData.stats, topSpeakersCount);
|
|
1130
|
+
const { earliestMeeting, latestMeeting } = findDateRange(transcripts);
|
|
1131
|
+
return {
|
|
1132
|
+
totalMeetings: transcripts.length,
|
|
1133
|
+
totalDurationMinutes,
|
|
1134
|
+
averageDurationMinutes,
|
|
1135
|
+
byDayOfWeek,
|
|
1136
|
+
byTimeGroup,
|
|
1137
|
+
totalUniqueParticipants,
|
|
1138
|
+
averageParticipantsPerMeeting,
|
|
1139
|
+
topParticipants,
|
|
1140
|
+
totalUniqueSpeakers,
|
|
1141
|
+
topSpeakers,
|
|
1142
|
+
earliestMeeting,
|
|
1143
|
+
latestMeeting
|
|
1144
|
+
};
|
|
1145
|
+
}
|
|
1146
|
+
function emptyInsights() {
|
|
1147
|
+
return {
|
|
1148
|
+
totalMeetings: 0,
|
|
1149
|
+
totalDurationMinutes: 0,
|
|
1150
|
+
averageDurationMinutes: 0,
|
|
1151
|
+
byDayOfWeek: emptyDayOfWeekStats(),
|
|
1152
|
+
byTimeGroup: void 0,
|
|
1153
|
+
totalUniqueParticipants: 0,
|
|
1154
|
+
averageParticipantsPerMeeting: 0,
|
|
1155
|
+
topParticipants: [],
|
|
1156
|
+
totalUniqueSpeakers: 0,
|
|
1157
|
+
topSpeakers: [],
|
|
1158
|
+
earliestMeeting: "",
|
|
1159
|
+
latestMeeting: ""
|
|
1160
|
+
};
|
|
1161
|
+
}
|
|
1162
|
+
function emptyDayOfWeekStats() {
|
|
1163
|
+
const emptyDay = () => ({ count: 0, totalMinutes: 0 });
|
|
1164
|
+
return {
|
|
1165
|
+
monday: emptyDay(),
|
|
1166
|
+
tuesday: emptyDay(),
|
|
1167
|
+
wednesday: emptyDay(),
|
|
1168
|
+
thursday: emptyDay(),
|
|
1169
|
+
friday: emptyDay(),
|
|
1170
|
+
saturday: emptyDay(),
|
|
1171
|
+
sunday: emptyDay()
|
|
1172
|
+
};
|
|
1173
|
+
}
|
|
1174
|
+
function sumDurations(transcripts) {
|
|
1175
|
+
return transcripts.reduce((sum, t) => sum + (t.duration ?? 0), 0);
|
|
1176
|
+
}
|
|
1177
|
+
function calculateDayOfWeekStats(transcripts) {
|
|
1178
|
+
const stats = emptyDayOfWeekStats();
|
|
1179
|
+
const dayNames = [
|
|
1180
|
+
"sunday",
|
|
1181
|
+
"monday",
|
|
1182
|
+
"tuesday",
|
|
1183
|
+
"wednesday",
|
|
1184
|
+
"thursday",
|
|
1185
|
+
"friday",
|
|
1186
|
+
"saturday"
|
|
1187
|
+
];
|
|
1188
|
+
for (const t of transcripts) {
|
|
1189
|
+
const date = parseDate(t.dateString);
|
|
1190
|
+
if (!date) continue;
|
|
1191
|
+
const dayIndex = date.getUTCDay();
|
|
1192
|
+
const dayName = dayNames[dayIndex];
|
|
1193
|
+
if (dayName) {
|
|
1194
|
+
stats[dayName].count++;
|
|
1195
|
+
stats[dayName].totalMinutes += t.duration ?? 0;
|
|
1196
|
+
}
|
|
1197
|
+
}
|
|
1198
|
+
return stats;
|
|
1199
|
+
}
|
|
1200
|
+
function calculateTimeGroupStats(transcripts, groupBy) {
|
|
1201
|
+
const groups = /* @__PURE__ */ new Map();
|
|
1202
|
+
for (const t of transcripts) {
|
|
1203
|
+
const date = parseDate(t.dateString);
|
|
1204
|
+
if (!date) continue;
|
|
1205
|
+
const period = formatPeriod(date, groupBy);
|
|
1206
|
+
const existing = groups.get(period) ?? { count: 0, totalMinutes: 0 };
|
|
1207
|
+
existing.count++;
|
|
1208
|
+
existing.totalMinutes += t.duration ?? 0;
|
|
1209
|
+
groups.set(period, existing);
|
|
1210
|
+
}
|
|
1211
|
+
const result = [];
|
|
1212
|
+
for (const [period, data] of groups) {
|
|
1213
|
+
result.push({
|
|
1214
|
+
period,
|
|
1215
|
+
count: data.count,
|
|
1216
|
+
totalMinutes: data.totalMinutes,
|
|
1217
|
+
averageMinutes: data.totalMinutes / data.count
|
|
1218
|
+
});
|
|
1219
|
+
}
|
|
1220
|
+
result.sort((a, b) => a.period.localeCompare(b.period));
|
|
1221
|
+
return result;
|
|
1222
|
+
}
|
|
1223
|
+
function formatPeriod(date, groupBy) {
|
|
1224
|
+
const year = date.getUTCFullYear();
|
|
1225
|
+
const month = String(date.getUTCMonth() + 1).padStart(2, "0");
|
|
1226
|
+
const day = String(date.getUTCDate()).padStart(2, "0");
|
|
1227
|
+
switch (groupBy) {
|
|
1228
|
+
case "day":
|
|
1229
|
+
return `${year}-${month}-${day}`;
|
|
1230
|
+
case "week":
|
|
1231
|
+
return getISOWeek(date);
|
|
1232
|
+
case "month":
|
|
1233
|
+
return `${year}-${month}`;
|
|
1234
|
+
}
|
|
1235
|
+
}
|
|
1236
|
+
function getISOWeek(date) {
|
|
1237
|
+
const d = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()));
|
|
1238
|
+
d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay() || 7));
|
|
1239
|
+
const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
|
|
1240
|
+
const weekNumber = Math.ceil(((d.getTime() - yearStart.getTime()) / 864e5 + 1) / 7);
|
|
1241
|
+
return `${d.getUTCFullYear()}-W${String(weekNumber).padStart(2, "0")}`;
|
|
1242
|
+
}
|
|
1243
|
+
function aggregateParticipants(transcripts) {
|
|
1244
|
+
const uniqueEmails = /* @__PURE__ */ new Set();
|
|
1245
|
+
const stats = /* @__PURE__ */ new Map();
|
|
1246
|
+
for (const t of transcripts) {
|
|
1247
|
+
const participants = t.participants ?? [];
|
|
1248
|
+
const seenInMeeting = /* @__PURE__ */ new Set();
|
|
1249
|
+
for (const email of participants) {
|
|
1250
|
+
const normalizedEmail = email.toLowerCase();
|
|
1251
|
+
uniqueEmails.add(normalizedEmail);
|
|
1252
|
+
if (seenInMeeting.has(normalizedEmail)) continue;
|
|
1253
|
+
seenInMeeting.add(normalizedEmail);
|
|
1254
|
+
const existing = stats.get(normalizedEmail) ?? { meetingCount: 0, totalMinutes: 0 };
|
|
1255
|
+
existing.meetingCount++;
|
|
1256
|
+
existing.totalMinutes += t.duration ?? 0;
|
|
1257
|
+
stats.set(normalizedEmail, existing);
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1260
|
+
return { uniqueEmails, stats };
|
|
1261
|
+
}
|
|
1262
|
+
function calculateAverageParticipants(transcripts) {
|
|
1263
|
+
if (transcripts.length === 0) return 0;
|
|
1264
|
+
let totalParticipants = 0;
|
|
1265
|
+
for (const t of transcripts) {
|
|
1266
|
+
const unique = new Set((t.participants ?? []).map((p) => p.toLowerCase()));
|
|
1267
|
+
totalParticipants += unique.size;
|
|
1268
|
+
}
|
|
1269
|
+
return totalParticipants / transcripts.length;
|
|
1270
|
+
}
|
|
1271
|
+
function buildTopParticipants(stats, limit) {
|
|
1272
|
+
const result = [];
|
|
1273
|
+
for (const [email, data] of stats) {
|
|
1274
|
+
result.push({
|
|
1275
|
+
email,
|
|
1276
|
+
meetingCount: data.meetingCount,
|
|
1277
|
+
totalMinutes: data.totalMinutes
|
|
1278
|
+
});
|
|
1279
|
+
}
|
|
1280
|
+
result.sort((a, b) => b.meetingCount - a.meetingCount);
|
|
1281
|
+
return result.slice(0, limit);
|
|
1282
|
+
}
|
|
1283
|
+
function aggregateSpeakers(transcripts, filterSpeakers) {
|
|
1284
|
+
const uniqueNames = /* @__PURE__ */ new Set();
|
|
1285
|
+
const stats = /* @__PURE__ */ new Map();
|
|
1286
|
+
const filterSet = filterSpeakers ? new Set(filterSpeakers) : null;
|
|
1287
|
+
for (const t of transcripts) {
|
|
1288
|
+
const sentences = t.sentences ?? [];
|
|
1289
|
+
for (const sentence of sentences) {
|
|
1290
|
+
const speakerName = sentence.speaker_name;
|
|
1291
|
+
if (filterSet && !filterSet.has(speakerName)) continue;
|
|
1292
|
+
uniqueNames.add(speakerName);
|
|
1293
|
+
const existing = stats.get(speakerName) ?? {
|
|
1294
|
+
meetingCount: 0,
|
|
1295
|
+
totalTalkTimeSeconds: 0,
|
|
1296
|
+
meetings: /* @__PURE__ */ new Set()
|
|
1297
|
+
};
|
|
1298
|
+
const duration = parseSentenceDuration(sentence);
|
|
1299
|
+
existing.totalTalkTimeSeconds += duration;
|
|
1300
|
+
if (!existing.meetings.has(t.id)) {
|
|
1301
|
+
existing.meetings.add(t.id);
|
|
1302
|
+
existing.meetingCount++;
|
|
1303
|
+
}
|
|
1304
|
+
stats.set(speakerName, existing);
|
|
1305
|
+
}
|
|
1306
|
+
}
|
|
1307
|
+
return { uniqueNames, stats };
|
|
1308
|
+
}
|
|
1309
|
+
function parseSentenceDuration(sentence) {
|
|
1310
|
+
const start = Number.parseFloat(sentence.start_time);
|
|
1311
|
+
const end = Number.parseFloat(sentence.end_time);
|
|
1312
|
+
return Math.max(0, end - start);
|
|
1313
|
+
}
|
|
1314
|
+
function buildTopSpeakers(stats, limit) {
|
|
1315
|
+
const result = [];
|
|
1316
|
+
for (const [name, data] of stats) {
|
|
1317
|
+
result.push({
|
|
1318
|
+
name,
|
|
1319
|
+
meetingCount: data.meetingCount,
|
|
1320
|
+
totalTalkTimeSeconds: data.totalTalkTimeSeconds,
|
|
1321
|
+
averageTalkTimeSeconds: data.meetingCount > 0 ? data.totalTalkTimeSeconds / data.meetingCount : 0
|
|
1322
|
+
});
|
|
1323
|
+
}
|
|
1324
|
+
result.sort((a, b) => b.totalTalkTimeSeconds - a.totalTalkTimeSeconds);
|
|
1325
|
+
return result.slice(0, limit);
|
|
1326
|
+
}
|
|
1327
|
+
function findDateRange(transcripts) {
|
|
1328
|
+
let earliest = null;
|
|
1329
|
+
let latest = null;
|
|
1330
|
+
for (const t of transcripts) {
|
|
1331
|
+
const date = parseDate(t.dateString);
|
|
1332
|
+
if (!date) continue;
|
|
1333
|
+
if (!earliest || date < earliest) {
|
|
1334
|
+
earliest = date;
|
|
1335
|
+
}
|
|
1336
|
+
if (!latest || date > latest) {
|
|
1337
|
+
latest = date;
|
|
1338
|
+
}
|
|
1339
|
+
}
|
|
1340
|
+
return {
|
|
1341
|
+
earliestMeeting: earliest ? formatDateOnly(earliest) : "",
|
|
1342
|
+
latestMeeting: latest ? formatDateOnly(latest) : ""
|
|
1343
|
+
};
|
|
1344
|
+
}
|
|
1345
|
+
function parseDate(dateString) {
|
|
1346
|
+
if (!dateString) return null;
|
|
1347
|
+
const date = new Date(dateString);
|
|
1348
|
+
return Number.isNaN(date.getTime()) ? null : date;
|
|
1349
|
+
}
|
|
1350
|
+
function formatDateOnly(date) {
|
|
1351
|
+
const year = date.getUTCFullYear();
|
|
1352
|
+
const month = String(date.getUTCMonth() + 1).padStart(2, "0");
|
|
1353
|
+
const day = String(date.getUTCDate()).padStart(2, "0");
|
|
1354
|
+
return `${year}-${month}-${day}`;
|
|
1355
|
+
}
|
|
1356
|
+
|
|
1357
|
+
// src/helpers/search.ts
|
|
1358
|
+
function escapeRegex(str) {
|
|
1359
|
+
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
1360
|
+
}
|
|
1361
|
+
function matchesSpeaker(sentence, speakerSet) {
|
|
1362
|
+
if (!speakerSet) return true;
|
|
1363
|
+
return speakerSet.has(sentence.speaker_name.toLowerCase());
|
|
1364
|
+
}
|
|
1365
|
+
function matchesAIFilters(sentence, filterQuestions, filterTasks) {
|
|
1366
|
+
if (!filterQuestions && !filterTasks) return true;
|
|
1367
|
+
const hasQuestion = Boolean(sentence.ai_filters?.question);
|
|
1368
|
+
const hasTask = Boolean(sentence.ai_filters?.task);
|
|
1369
|
+
if (filterQuestions && filterTasks) {
|
|
1370
|
+
return hasQuestion || hasTask;
|
|
1371
|
+
}
|
|
1372
|
+
if (filterQuestions) return hasQuestion;
|
|
1373
|
+
if (filterTasks) return hasTask;
|
|
1374
|
+
return true;
|
|
1375
|
+
}
|
|
1376
|
+
function extractContext(sentences, index, contextLines) {
|
|
1377
|
+
const beforeStart = Math.max(0, index - contextLines);
|
|
1378
|
+
const afterEnd = Math.min(sentences.length, index + contextLines + 1);
|
|
1379
|
+
return {
|
|
1380
|
+
before: sentences.slice(beforeStart, index).map((s) => ({
|
|
1381
|
+
speakerName: s.speaker_name,
|
|
1382
|
+
text: s.text
|
|
1383
|
+
})),
|
|
1384
|
+
after: sentences.slice(index + 1, afterEnd).map((s) => ({
|
|
1385
|
+
speakerName: s.speaker_name,
|
|
1386
|
+
text: s.text
|
|
1387
|
+
}))
|
|
1388
|
+
};
|
|
1389
|
+
}
|
|
1390
|
+
function sentenceToMatch(sentence, transcript, context) {
|
|
1391
|
+
return {
|
|
1392
|
+
transcriptId: transcript.id,
|
|
1393
|
+
transcriptTitle: transcript.title,
|
|
1394
|
+
transcriptDate: transcript.dateString,
|
|
1395
|
+
transcriptUrl: transcript.transcript_url,
|
|
1396
|
+
sentence: {
|
|
1397
|
+
index: sentence.index,
|
|
1398
|
+
text: sentence.text,
|
|
1399
|
+
speakerName: sentence.speaker_name,
|
|
1400
|
+
startTime: Number.parseFloat(sentence.start_time),
|
|
1401
|
+
endTime: Number.parseFloat(sentence.end_time),
|
|
1402
|
+
isQuestion: Boolean(sentence.ai_filters?.question),
|
|
1403
|
+
isTask: Boolean(sentence.ai_filters?.task)
|
|
1404
|
+
},
|
|
1405
|
+
context
|
|
1406
|
+
};
|
|
1407
|
+
}
|
|
1408
|
+
function searchTranscript(transcript, options) {
|
|
1409
|
+
const {
|
|
1410
|
+
query,
|
|
1411
|
+
caseSensitive = false,
|
|
1412
|
+
speakers,
|
|
1413
|
+
filterQuestions = false,
|
|
1414
|
+
filterTasks = false,
|
|
1415
|
+
contextLines = 1
|
|
1416
|
+
} = options;
|
|
1417
|
+
if (!query || query.trim() === "") {
|
|
1418
|
+
return [];
|
|
1419
|
+
}
|
|
1420
|
+
const sentences = transcript.sentences ?? [];
|
|
1421
|
+
if (sentences.length === 0) {
|
|
1422
|
+
return [];
|
|
1423
|
+
}
|
|
1424
|
+
const escapedQuery = escapeRegex(query);
|
|
1425
|
+
const regex = new RegExp(escapedQuery, caseSensitive ? "" : "i");
|
|
1426
|
+
const speakerSet = speakers ? new Set(speakers.map((s) => s.toLowerCase())) : null;
|
|
1427
|
+
const matches = [];
|
|
1428
|
+
for (let i = 0; i < sentences.length; i++) {
|
|
1429
|
+
const sentence = sentences[i];
|
|
1430
|
+
if (!sentence) continue;
|
|
1431
|
+
if (!regex.test(sentence.text)) continue;
|
|
1432
|
+
if (!matchesSpeaker(sentence, speakerSet)) continue;
|
|
1433
|
+
if (!matchesAIFilters(sentence, filterQuestions, filterTasks)) continue;
|
|
1434
|
+
const context = extractContext(sentences, i, contextLines);
|
|
1435
|
+
matches.push(sentenceToMatch(sentence, transcript, context));
|
|
1436
|
+
}
|
|
1437
|
+
return matches;
|
|
1438
|
+
}
|
|
1439
|
+
|
|
1440
|
+
// src/graphql/queries/transcripts.ts
|
|
1441
|
+
var TRANSCRIPT_BASE_FIELDS = `
|
|
1442
|
+
id
|
|
1443
|
+
title
|
|
1444
|
+
organizer_email
|
|
1445
|
+
host_email
|
|
1446
|
+
user {
|
|
1447
|
+
user_id
|
|
1448
|
+
email
|
|
1449
|
+
name
|
|
1450
|
+
}
|
|
1451
|
+
speakers {
|
|
1452
|
+
id
|
|
1453
|
+
name
|
|
1454
|
+
}
|
|
1455
|
+
transcript_url
|
|
1456
|
+
participants
|
|
1457
|
+
meeting_attendees {
|
|
1458
|
+
displayName
|
|
1459
|
+
email
|
|
1460
|
+
phoneNumber
|
|
1461
|
+
name
|
|
1462
|
+
location
|
|
1463
|
+
}
|
|
1464
|
+
meeting_attendance {
|
|
1465
|
+
name
|
|
1466
|
+
join_time
|
|
1467
|
+
leave_time
|
|
1468
|
+
}
|
|
1469
|
+
fireflies_users
|
|
1470
|
+
workspace_users
|
|
1471
|
+
duration
|
|
1472
|
+
dateString
|
|
1473
|
+
date
|
|
1474
|
+
audio_url
|
|
1475
|
+
video_url
|
|
1476
|
+
calendar_id
|
|
1477
|
+
meeting_info {
|
|
1478
|
+
fred_joined
|
|
1479
|
+
silent_meeting
|
|
1480
|
+
summary_status
|
|
1481
|
+
}
|
|
1482
|
+
cal_id
|
|
1483
|
+
calendar_type
|
|
1484
|
+
apps_preview {
|
|
1485
|
+
outputs {
|
|
1486
|
+
transcript_id
|
|
1487
|
+
user_id
|
|
1488
|
+
app_id
|
|
1489
|
+
created_at
|
|
1490
|
+
title
|
|
1491
|
+
prompt
|
|
1492
|
+
response
|
|
1493
|
+
}
|
|
1494
|
+
}
|
|
1495
|
+
meeting_link
|
|
1496
|
+
analytics {
|
|
1497
|
+
sentiments {
|
|
1498
|
+
negative_pct
|
|
1499
|
+
neutral_pct
|
|
1500
|
+
positive_pct
|
|
1501
|
+
}
|
|
1502
|
+
}
|
|
1503
|
+
channels {
|
|
1504
|
+
id
|
|
1505
|
+
title
|
|
1506
|
+
is_private
|
|
1507
|
+
created_at
|
|
1508
|
+
updated_at
|
|
1509
|
+
created_by
|
|
1510
|
+
members {
|
|
1511
|
+
user_id
|
|
1512
|
+
email
|
|
1513
|
+
name
|
|
1514
|
+
}
|
|
1515
|
+
}
|
|
1516
|
+
`;
|
|
1517
|
+
var SENTENCES_FIELDS = `
|
|
1518
|
+
sentences {
|
|
1519
|
+
index
|
|
1520
|
+
text
|
|
1521
|
+
raw_text
|
|
1522
|
+
start_time
|
|
1523
|
+
end_time
|
|
1524
|
+
speaker_id
|
|
1525
|
+
speaker_name
|
|
1526
|
+
ai_filters {
|
|
1527
|
+
task
|
|
1528
|
+
pricing
|
|
1529
|
+
metric
|
|
1530
|
+
question
|
|
1531
|
+
date_and_time
|
|
1532
|
+
text_cleanup
|
|
1533
|
+
sentiment
|
|
1534
|
+
}
|
|
1535
|
+
}
|
|
1536
|
+
`;
|
|
1537
|
+
var SUMMARY_FIELDS = `
|
|
1538
|
+
summary {
|
|
1539
|
+
action_items
|
|
1540
|
+
keywords
|
|
1541
|
+
outline
|
|
1542
|
+
overview
|
|
1543
|
+
shorthand_bullet
|
|
1544
|
+
notes
|
|
1545
|
+
gist
|
|
1546
|
+
bullet_gist
|
|
1547
|
+
short_summary
|
|
1548
|
+
short_overview
|
|
1549
|
+
meeting_type
|
|
1550
|
+
topics_discussed
|
|
1551
|
+
transcript_chapters
|
|
1552
|
+
extended_sections {
|
|
1553
|
+
title
|
|
1554
|
+
content
|
|
1555
|
+
}
|
|
1556
|
+
}
|
|
1557
|
+
`;
|
|
1558
|
+
function buildTranscriptFields(params) {
|
|
1559
|
+
const includeSentences = params?.includeSentences !== false;
|
|
1560
|
+
const includeSummary = params?.includeSummary !== false;
|
|
1561
|
+
let fields = TRANSCRIPT_BASE_FIELDS;
|
|
1562
|
+
if (includeSentences) {
|
|
1563
|
+
fields += SENTENCES_FIELDS;
|
|
1564
|
+
}
|
|
1565
|
+
if (includeSummary) {
|
|
1566
|
+
fields += SUMMARY_FIELDS;
|
|
1567
|
+
}
|
|
1568
|
+
return fields;
|
|
1569
|
+
}
|
|
1570
|
+
var TRANSCRIPT_LIST_FIELDS = `
|
|
1571
|
+
id
|
|
1572
|
+
title
|
|
1573
|
+
organizer_email
|
|
1574
|
+
transcript_url
|
|
1575
|
+
participants
|
|
1576
|
+
duration
|
|
1577
|
+
dateString
|
|
1578
|
+
date
|
|
1579
|
+
video_url
|
|
1580
|
+
meeting_info {
|
|
1581
|
+
fred_joined
|
|
1582
|
+
silent_meeting
|
|
1583
|
+
summary_status
|
|
1584
|
+
}
|
|
1585
|
+
`;
|
|
1586
|
+
function createTranscriptsAPI(client) {
|
|
1587
|
+
return {
|
|
1588
|
+
async get(id, params) {
|
|
1589
|
+
const fields = buildTranscriptFields(params);
|
|
1590
|
+
const query = `
|
|
1591
|
+
query GetTranscript($id: String!) {
|
|
1592
|
+
transcript(id: $id) {
|
|
1593
|
+
${fields}
|
|
1594
|
+
}
|
|
1595
|
+
}
|
|
1596
|
+
`;
|
|
1597
|
+
const data = await client.execute(query, { id });
|
|
1598
|
+
return normalizeTranscript(data.transcript);
|
|
1599
|
+
},
|
|
1600
|
+
async list(params) {
|
|
1601
|
+
const query = `
|
|
1602
|
+
query ListTranscripts(
|
|
1603
|
+
$keyword: String
|
|
1604
|
+
$scope: String
|
|
1605
|
+
$organizers: [String!]
|
|
1606
|
+
$participants: [String!]
|
|
1607
|
+
$user_id: String
|
|
1608
|
+
$mine: Boolean
|
|
1609
|
+
$channel_id: String
|
|
1610
|
+
$fromDate: DateTime
|
|
1611
|
+
$toDate: DateTime
|
|
1612
|
+
$limit: Int
|
|
1613
|
+
$skip: Int
|
|
1614
|
+
$title: String
|
|
1615
|
+
$host_email: String
|
|
1616
|
+
$organizer_email: String
|
|
1617
|
+
$participant_email: String
|
|
1618
|
+
$date: Float
|
|
1619
|
+
) {
|
|
1620
|
+
transcripts(
|
|
1621
|
+
keyword: $keyword
|
|
1622
|
+
scope: $scope
|
|
1623
|
+
organizers: $organizers
|
|
1624
|
+
participants: $participants
|
|
1625
|
+
user_id: $user_id
|
|
1626
|
+
mine: $mine
|
|
1627
|
+
channel_id: $channel_id
|
|
1628
|
+
fromDate: $fromDate
|
|
1629
|
+
toDate: $toDate
|
|
1630
|
+
limit: $limit
|
|
1631
|
+
skip: $skip
|
|
1632
|
+
title: $title
|
|
1633
|
+
host_email: $host_email
|
|
1634
|
+
organizer_email: $organizer_email
|
|
1635
|
+
participant_email: $participant_email
|
|
1636
|
+
date: $date
|
|
1637
|
+
) {
|
|
1638
|
+
${TRANSCRIPT_LIST_FIELDS}
|
|
1639
|
+
}
|
|
1640
|
+
}
|
|
1641
|
+
`;
|
|
1642
|
+
const variables = buildListVariables(params);
|
|
1643
|
+
const data = await client.execute(query, variables);
|
|
1644
|
+
return data.transcripts.map(normalizeTranscript);
|
|
1645
|
+
},
|
|
1646
|
+
async getSummary(id) {
|
|
1647
|
+
const query = `
|
|
1648
|
+
query GetTranscriptSummary($id: String!) {
|
|
1649
|
+
transcript(id: $id) {
|
|
1650
|
+
summary {
|
|
1651
|
+
action_items
|
|
1652
|
+
keywords
|
|
1653
|
+
outline
|
|
1654
|
+
overview
|
|
1655
|
+
shorthand_bullet
|
|
1656
|
+
notes
|
|
1657
|
+
gist
|
|
1658
|
+
bullet_gist
|
|
1659
|
+
short_summary
|
|
1660
|
+
short_overview
|
|
1661
|
+
meeting_type
|
|
1662
|
+
topics_discussed
|
|
1663
|
+
transcript_chapters
|
|
1664
|
+
extended_sections {
|
|
1665
|
+
title
|
|
1666
|
+
content
|
|
1667
|
+
}
|
|
1668
|
+
}
|
|
1669
|
+
}
|
|
1670
|
+
}
|
|
1671
|
+
`;
|
|
1672
|
+
const data = await client.execute(query, { id });
|
|
1673
|
+
return data.transcript.summary;
|
|
1674
|
+
},
|
|
1675
|
+
listAll(params) {
|
|
1676
|
+
return paginate((skip, limit) => this.list({ ...params, skip, limit }), 50);
|
|
1677
|
+
},
|
|
1678
|
+
async search(query, params = {}) {
|
|
1679
|
+
const {
|
|
1680
|
+
caseSensitive = false,
|
|
1681
|
+
scope = "sentences",
|
|
1682
|
+
speakers,
|
|
1683
|
+
filterQuestions,
|
|
1684
|
+
filterTasks,
|
|
1685
|
+
contextLines = 1,
|
|
1686
|
+
limit,
|
|
1687
|
+
...listParams
|
|
1688
|
+
} = params;
|
|
1689
|
+
const transcripts = [];
|
|
1690
|
+
for await (const t of this.listAll({
|
|
1691
|
+
keyword: query,
|
|
1692
|
+
scope,
|
|
1693
|
+
...listParams
|
|
1694
|
+
})) {
|
|
1695
|
+
transcripts.push(t);
|
|
1696
|
+
if (limit && transcripts.length >= limit) break;
|
|
1697
|
+
}
|
|
1698
|
+
const allMatches = [];
|
|
1699
|
+
let transcriptsWithMatches = 0;
|
|
1700
|
+
for (const t of transcripts) {
|
|
1701
|
+
const full = await this.get(t.id, { includeSentences: true });
|
|
1702
|
+
const matches = searchTranscript(full, {
|
|
1703
|
+
query,
|
|
1704
|
+
caseSensitive,
|
|
1705
|
+
speakers,
|
|
1706
|
+
filterQuestions,
|
|
1707
|
+
filterTasks,
|
|
1708
|
+
contextLines
|
|
1709
|
+
});
|
|
1710
|
+
if (matches.length > 0) {
|
|
1711
|
+
transcriptsWithMatches++;
|
|
1712
|
+
allMatches.push(...matches);
|
|
1713
|
+
}
|
|
1714
|
+
}
|
|
1715
|
+
return {
|
|
1716
|
+
query,
|
|
1717
|
+
options: params,
|
|
1718
|
+
totalMatches: allMatches.length,
|
|
1719
|
+
transcriptsSearched: transcripts.length,
|
|
1720
|
+
transcriptsWithMatches,
|
|
1721
|
+
matches: allMatches
|
|
1722
|
+
};
|
|
1723
|
+
},
|
|
1724
|
+
async insights(params = {}) {
|
|
1725
|
+
const {
|
|
1726
|
+
fromDate,
|
|
1727
|
+
toDate,
|
|
1728
|
+
mine,
|
|
1729
|
+
organizers,
|
|
1730
|
+
participants,
|
|
1731
|
+
user_id,
|
|
1732
|
+
channel_id,
|
|
1733
|
+
limit,
|
|
1734
|
+
external,
|
|
1735
|
+
speakers,
|
|
1736
|
+
groupBy,
|
|
1737
|
+
topSpeakersCount,
|
|
1738
|
+
topParticipantsCount
|
|
1739
|
+
} = params;
|
|
1740
|
+
let internalDomain;
|
|
1741
|
+
if (external) {
|
|
1742
|
+
const userQuery = "query { user { email } }";
|
|
1743
|
+
const userData = await client.execute(userQuery);
|
|
1744
|
+
internalDomain = extractDomain(userData.user.email);
|
|
1745
|
+
}
|
|
1746
|
+
const transcripts = [];
|
|
1747
|
+
for await (const t of this.listAll({
|
|
1748
|
+
fromDate,
|
|
1749
|
+
toDate,
|
|
1750
|
+
mine,
|
|
1751
|
+
organizers,
|
|
1752
|
+
participants,
|
|
1753
|
+
user_id,
|
|
1754
|
+
channel_id
|
|
1755
|
+
})) {
|
|
1756
|
+
if (internalDomain && !hasExternalParticipants(t.participants, internalDomain)) {
|
|
1757
|
+
continue;
|
|
1758
|
+
}
|
|
1759
|
+
const full = await this.get(t.id, { includeSentences: true, includeSummary: false });
|
|
1760
|
+
transcripts.push(full);
|
|
1761
|
+
if (limit && transcripts.length >= limit) break;
|
|
1762
|
+
}
|
|
1763
|
+
return analyzeMeetings(transcripts, {
|
|
1764
|
+
speakers,
|
|
1765
|
+
groupBy,
|
|
1766
|
+
topSpeakersCount,
|
|
1767
|
+
topParticipantsCount
|
|
1768
|
+
});
|
|
1769
|
+
},
|
|
1770
|
+
async exportActionItems(params = {}) {
|
|
1771
|
+
const { fromDate, toDate, mine, organizers, participants, limit, filterOptions } = params;
|
|
1772
|
+
const transcripts = [];
|
|
1773
|
+
for await (const t of this.listAll({
|
|
1774
|
+
fromDate,
|
|
1775
|
+
toDate,
|
|
1776
|
+
mine,
|
|
1777
|
+
organizers,
|
|
1778
|
+
participants
|
|
1779
|
+
})) {
|
|
1780
|
+
const full = await this.get(t.id, { includeSentences: false, includeSummary: true });
|
|
1781
|
+
transcripts.push(full);
|
|
1782
|
+
if (limit && transcripts.length >= limit) break;
|
|
1783
|
+
}
|
|
1784
|
+
return aggregateActionItems(transcripts, {}, filterOptions);
|
|
1785
|
+
}
|
|
1786
|
+
};
|
|
1787
|
+
}
|
|
1788
|
+
function orUndefined(value) {
|
|
1789
|
+
return value ?? void 0;
|
|
1790
|
+
}
|
|
1791
|
+
function orEmptyArray(value) {
|
|
1792
|
+
return value ?? [];
|
|
1793
|
+
}
|
|
1794
|
+
function normalizeRequiredFields(raw) {
|
|
1795
|
+
return {
|
|
1796
|
+
id: raw.id,
|
|
1797
|
+
title: raw.title ?? "",
|
|
1798
|
+
organizer_email: raw.organizer_email ?? "",
|
|
1799
|
+
transcript_url: raw.transcript_url ?? "",
|
|
1800
|
+
duration: raw.duration ?? 0,
|
|
1801
|
+
dateString: raw.dateString ?? "",
|
|
1802
|
+
date: raw.date ?? 0
|
|
1803
|
+
};
|
|
1804
|
+
}
|
|
1805
|
+
function normalizeArrayFields(raw) {
|
|
1806
|
+
return {
|
|
1807
|
+
speakers: orEmptyArray(raw.speakers),
|
|
1808
|
+
participants: orEmptyArray(raw.participants),
|
|
1809
|
+
meeting_attendees: orEmptyArray(raw.meeting_attendees),
|
|
1810
|
+
meeting_attendance: orEmptyArray(raw.meeting_attendance),
|
|
1811
|
+
fireflies_users: orEmptyArray(raw.fireflies_users),
|
|
1812
|
+
workspace_users: orEmptyArray(raw.workspace_users),
|
|
1813
|
+
sentences: orEmptyArray(raw.sentences),
|
|
1814
|
+
channels: orEmptyArray(raw.channels)
|
|
1815
|
+
};
|
|
1816
|
+
}
|
|
1817
|
+
function normalizeOptionalFields(raw) {
|
|
1818
|
+
return {
|
|
1819
|
+
host_email: orUndefined(raw.host_email),
|
|
1820
|
+
user: orUndefined(raw.user),
|
|
1821
|
+
audio_url: orUndefined(raw.audio_url),
|
|
1822
|
+
video_url: orUndefined(raw.video_url),
|
|
1823
|
+
calendar_id: orUndefined(raw.calendar_id),
|
|
1824
|
+
summary: orUndefined(raw.summary),
|
|
1825
|
+
meeting_info: orUndefined(raw.meeting_info),
|
|
1826
|
+
cal_id: orUndefined(raw.cal_id),
|
|
1827
|
+
calendar_type: orUndefined(raw.calendar_type),
|
|
1828
|
+
apps_preview: orUndefined(raw.apps_preview),
|
|
1829
|
+
meeting_link: orUndefined(raw.meeting_link),
|
|
1830
|
+
analytics: orUndefined(raw.analytics)
|
|
1831
|
+
};
|
|
1832
|
+
}
|
|
1833
|
+
function normalizeTranscript(raw) {
|
|
1834
|
+
return {
|
|
1835
|
+
...normalizeRequiredFields(raw),
|
|
1836
|
+
...normalizeArrayFields(raw),
|
|
1837
|
+
...normalizeOptionalFields(raw)
|
|
1838
|
+
};
|
|
1839
|
+
}
|
|
1840
|
+
function buildListVariables(params) {
|
|
1841
|
+
if (!params) {
|
|
1842
|
+
return { limit: 50 };
|
|
1843
|
+
}
|
|
1844
|
+
return {
|
|
1845
|
+
keyword: params.keyword,
|
|
1846
|
+
scope: params.scope,
|
|
1847
|
+
organizers: params.organizers,
|
|
1848
|
+
participants: params.participants,
|
|
1849
|
+
user_id: params.user_id,
|
|
1850
|
+
mine: params.mine,
|
|
1851
|
+
channel_id: params.channel_id,
|
|
1852
|
+
fromDate: params.fromDate,
|
|
1853
|
+
toDate: params.toDate,
|
|
1854
|
+
limit: params.limit ?? 50,
|
|
1855
|
+
skip: params.skip,
|
|
1856
|
+
title: params.title,
|
|
1857
|
+
host_email: params.host_email,
|
|
1858
|
+
organizer_email: params.organizer_email,
|
|
1859
|
+
participant_email: params.participant_email,
|
|
1860
|
+
date: params.date
|
|
1861
|
+
};
|
|
1862
|
+
}
|
|
1863
|
+
|
|
1864
|
+
// src/graphql/queries/users.ts
|
|
1865
|
+
var USER_FIELDS = `
|
|
1866
|
+
user_id
|
|
1867
|
+
email
|
|
1868
|
+
name
|
|
1869
|
+
num_transcripts
|
|
1870
|
+
recent_meeting
|
|
1871
|
+
recent_transcript
|
|
1872
|
+
minutes_consumed
|
|
1873
|
+
is_admin
|
|
1874
|
+
integrations
|
|
1875
|
+
user_groups {
|
|
1876
|
+
id
|
|
1877
|
+
name
|
|
1878
|
+
handle
|
|
1879
|
+
members {
|
|
1880
|
+
user_id
|
|
1881
|
+
email
|
|
1882
|
+
}
|
|
1883
|
+
}
|
|
1884
|
+
`;
|
|
1885
|
+
function createUsersAPI(client) {
|
|
1886
|
+
return {
|
|
1887
|
+
async me() {
|
|
1888
|
+
const query = `query { user { ${USER_FIELDS} } }`;
|
|
1889
|
+
const data = await client.execute(query);
|
|
1890
|
+
return data.user;
|
|
1891
|
+
},
|
|
1892
|
+
async get(id) {
|
|
1893
|
+
const query = `
|
|
1894
|
+
query User($userId: String!) {
|
|
1895
|
+
user(id: $userId) { ${USER_FIELDS} }
|
|
1896
|
+
}
|
|
1897
|
+
`;
|
|
1898
|
+
const data = await client.execute(query, { userId: id });
|
|
1899
|
+
return data.user;
|
|
1900
|
+
},
|
|
1901
|
+
async list() {
|
|
1902
|
+
const query = `query Users { users { ${USER_FIELDS} } }`;
|
|
1903
|
+
const data = await client.execute(query);
|
|
1904
|
+
return data.users;
|
|
1905
|
+
}
|
|
1906
|
+
};
|
|
1907
|
+
}
|
|
1908
|
+
var DEFAULT_WS_URL = "wss://api.fireflies.ai";
|
|
1909
|
+
var DEFAULT_WS_PATH = "/ws/realtime";
|
|
1910
|
+
var DEFAULT_TIMEOUT2 = 2e4;
|
|
1911
|
+
var DEFAULT_CHUNK_TIMEOUT = 2e4;
|
|
1912
|
+
var DEFAULT_RECONNECT_DELAY = 5e3;
|
|
1913
|
+
var DEFAULT_MAX_RECONNECT_DELAY = 6e4;
|
|
1914
|
+
var DEFAULT_MAX_RECONNECT_ATTEMPTS = 10;
|
|
1915
|
+
var RealtimeConnection = class {
|
|
1916
|
+
socket = null;
|
|
1917
|
+
config;
|
|
1918
|
+
constructor(config) {
|
|
1919
|
+
this.config = {
|
|
1920
|
+
wsUrl: DEFAULT_WS_URL,
|
|
1921
|
+
wsPath: DEFAULT_WS_PATH,
|
|
1922
|
+
timeout: DEFAULT_TIMEOUT2,
|
|
1923
|
+
chunkTimeout: DEFAULT_CHUNK_TIMEOUT,
|
|
1924
|
+
reconnect: true,
|
|
1925
|
+
maxReconnectAttempts: DEFAULT_MAX_RECONNECT_ATTEMPTS,
|
|
1926
|
+
reconnectDelay: DEFAULT_RECONNECT_DELAY,
|
|
1927
|
+
maxReconnectDelay: DEFAULT_MAX_RECONNECT_DELAY,
|
|
1928
|
+
...config
|
|
1929
|
+
};
|
|
1930
|
+
}
|
|
1931
|
+
/**
|
|
1932
|
+
* Establish connection and wait for auth success.
|
|
1933
|
+
*/
|
|
1934
|
+
async connect() {
|
|
1935
|
+
if (this.socket?.connected) {
|
|
1936
|
+
return;
|
|
1937
|
+
}
|
|
1938
|
+
const socket = io(this.config.wsUrl, {
|
|
1939
|
+
path: this.config.wsPath,
|
|
1940
|
+
auth: {
|
|
1941
|
+
token: `Bearer ${this.config.apiKey}`,
|
|
1942
|
+
transcriptId: this.config.transcriptId
|
|
1943
|
+
},
|
|
1944
|
+
// Force WebSocket transport (proven more reliable than polling)
|
|
1945
|
+
transports: ["websocket"],
|
|
1946
|
+
reconnection: this.config.reconnect,
|
|
1947
|
+
reconnectionDelay: this.config.reconnectDelay,
|
|
1948
|
+
reconnectionDelayMax: this.config.maxReconnectDelay,
|
|
1949
|
+
reconnectionAttempts: this.config.maxReconnectAttempts,
|
|
1950
|
+
// Exponential backoff factor (default 2x matches our fireflies-whiteboard pattern)
|
|
1951
|
+
randomizationFactor: 0.5,
|
|
1952
|
+
timeout: this.config.timeout,
|
|
1953
|
+
autoConnect: false
|
|
1954
|
+
});
|
|
1955
|
+
this.socket = socket;
|
|
1956
|
+
return new Promise((resolve, reject) => {
|
|
1957
|
+
const timeoutId = setTimeout(() => {
|
|
1958
|
+
socket.disconnect();
|
|
1959
|
+
reject(new TimeoutError(`Realtime connection timed out after ${this.config.timeout}ms`));
|
|
1960
|
+
}, this.config.timeout);
|
|
1961
|
+
const cleanup = () => clearTimeout(timeoutId);
|
|
1962
|
+
socket.once("auth.success", () => {
|
|
1963
|
+
cleanup();
|
|
1964
|
+
resolve();
|
|
1965
|
+
});
|
|
1966
|
+
socket.once("auth.failed", (data) => {
|
|
1967
|
+
cleanup();
|
|
1968
|
+
socket.disconnect();
|
|
1969
|
+
reject(new AuthenticationError(`Realtime auth failed: ${formatData(data)}`));
|
|
1970
|
+
});
|
|
1971
|
+
socket.once("connection.error", (data) => {
|
|
1972
|
+
cleanup();
|
|
1973
|
+
socket.disconnect();
|
|
1974
|
+
reject(new ConnectionError(`Realtime connection error: ${formatData(data)}`));
|
|
1975
|
+
});
|
|
1976
|
+
socket.once("connect_error", (error) => {
|
|
1977
|
+
cleanup();
|
|
1978
|
+
socket.disconnect();
|
|
1979
|
+
const message = error.message || "Connection failed";
|
|
1980
|
+
if (message.includes("auth") || message.includes("401") || message.includes("unauthorized")) {
|
|
1981
|
+
reject(new AuthenticationError(`Realtime auth failed: ${message}`));
|
|
1982
|
+
} else {
|
|
1983
|
+
reject(
|
|
1984
|
+
new ConnectionError(`Realtime connection failed: ${message}`, {
|
|
1985
|
+
cause: error
|
|
1986
|
+
})
|
|
1987
|
+
);
|
|
1988
|
+
}
|
|
1989
|
+
});
|
|
1990
|
+
socket.connect();
|
|
1991
|
+
});
|
|
1992
|
+
}
|
|
1993
|
+
/**
|
|
1994
|
+
* Register a chunk handler.
|
|
1995
|
+
* Handles both { payload: {...} } and direct payload shapes.
|
|
1996
|
+
*/
|
|
1997
|
+
onChunk(handler) {
|
|
1998
|
+
this.socket?.on("transcription.broadcast", (data) => {
|
|
1999
|
+
const chunk = "payload" in data ? data.payload : data;
|
|
2000
|
+
handler(chunk);
|
|
2001
|
+
});
|
|
2002
|
+
}
|
|
2003
|
+
/**
|
|
2004
|
+
* Register a disconnect handler.
|
|
2005
|
+
*/
|
|
2006
|
+
onDisconnect(handler) {
|
|
2007
|
+
this.socket?.on("disconnect", handler);
|
|
2008
|
+
}
|
|
2009
|
+
/**
|
|
2010
|
+
* Register a reconnect handler.
|
|
2011
|
+
*/
|
|
2012
|
+
onReconnect(handler) {
|
|
2013
|
+
this.socket?.io.on("reconnect", handler);
|
|
2014
|
+
}
|
|
2015
|
+
/**
|
|
2016
|
+
* Register a reconnect attempt handler.
|
|
2017
|
+
*/
|
|
2018
|
+
onReconnectAttempt(handler) {
|
|
2019
|
+
this.socket?.io.on("reconnect_attempt", handler);
|
|
2020
|
+
}
|
|
2021
|
+
/**
|
|
2022
|
+
* Register an error handler.
|
|
2023
|
+
*/
|
|
2024
|
+
onError(handler) {
|
|
2025
|
+
this.socket?.on("connect_error", handler);
|
|
2026
|
+
}
|
|
2027
|
+
/**
|
|
2028
|
+
* Disconnect and cleanup.
|
|
2029
|
+
*/
|
|
2030
|
+
disconnect() {
|
|
2031
|
+
if (this.socket) {
|
|
2032
|
+
this.socket.disconnect();
|
|
2033
|
+
this.socket = null;
|
|
2034
|
+
}
|
|
2035
|
+
}
|
|
2036
|
+
get connected() {
|
|
2037
|
+
return this.socket?.connected ?? false;
|
|
2038
|
+
}
|
|
2039
|
+
};
|
|
2040
|
+
function formatData(data) {
|
|
2041
|
+
if (data === void 0 || data === null) {
|
|
2042
|
+
return String(data);
|
|
2043
|
+
}
|
|
2044
|
+
try {
|
|
2045
|
+
return JSON.stringify(data);
|
|
2046
|
+
} catch {
|
|
2047
|
+
return String(data);
|
|
2048
|
+
}
|
|
2049
|
+
}
|
|
2050
|
+
|
|
2051
|
+
// src/realtime/stream.ts
|
|
2052
|
+
var RealtimeStream = class {
|
|
2053
|
+
connection;
|
|
2054
|
+
listeners = /* @__PURE__ */ new Map();
|
|
2055
|
+
buffer = [];
|
|
2056
|
+
waiters = [];
|
|
2057
|
+
closed = false;
|
|
2058
|
+
lastChunkId = null;
|
|
2059
|
+
lastChunk = null;
|
|
2060
|
+
constructor(config) {
|
|
2061
|
+
this.connection = new RealtimeConnection(config);
|
|
2062
|
+
}
|
|
2063
|
+
/**
|
|
2064
|
+
* Connect to the realtime stream.
|
|
2065
|
+
* @throws AuthenticationError if authentication fails
|
|
2066
|
+
* @throws ConnectionError if connection fails
|
|
2067
|
+
* @throws TimeoutError if connection times out
|
|
2068
|
+
*/
|
|
2069
|
+
async connect() {
|
|
2070
|
+
await this.connection.connect();
|
|
2071
|
+
this.setupHandlers();
|
|
2072
|
+
this.emit("connected");
|
|
2073
|
+
}
|
|
2074
|
+
setupHandlers() {
|
|
2075
|
+
this.connection.onChunk((rawChunk) => {
|
|
2076
|
+
const isNewChunk = this.lastChunkId !== null && rawChunk.chunk_id !== this.lastChunkId;
|
|
2077
|
+
if (isNewChunk && this.lastChunk) {
|
|
2078
|
+
const finalChunk = { ...this.lastChunk, isFinal: true };
|
|
2079
|
+
this.emitChunk(finalChunk);
|
|
2080
|
+
}
|
|
2081
|
+
const chunk = { ...rawChunk, isFinal: false };
|
|
2082
|
+
this.lastChunkId = chunk.chunk_id;
|
|
2083
|
+
this.lastChunk = chunk;
|
|
2084
|
+
this.emit("chunk", chunk);
|
|
2085
|
+
});
|
|
2086
|
+
this.connection.onDisconnect((reason) => {
|
|
2087
|
+
if (this.lastChunk) {
|
|
2088
|
+
const finalChunk = { ...this.lastChunk, isFinal: true };
|
|
2089
|
+
this.emitChunk(finalChunk);
|
|
2090
|
+
this.lastChunk = null;
|
|
2091
|
+
}
|
|
2092
|
+
this.emit("disconnected", reason);
|
|
2093
|
+
if (!this.connection.connected) {
|
|
2094
|
+
this.closed = true;
|
|
2095
|
+
for (const waiter of this.waiters) {
|
|
2096
|
+
waiter(null);
|
|
2097
|
+
}
|
|
2098
|
+
this.waiters = [];
|
|
2099
|
+
}
|
|
2100
|
+
});
|
|
2101
|
+
this.connection.onReconnectAttempt((attempt) => {
|
|
2102
|
+
this.emit("reconnecting", attempt);
|
|
2103
|
+
});
|
|
2104
|
+
this.connection.onReconnect(() => {
|
|
2105
|
+
this.emit("connected");
|
|
2106
|
+
});
|
|
2107
|
+
this.connection.onError((error) => {
|
|
2108
|
+
this.emit("error", error);
|
|
2109
|
+
});
|
|
2110
|
+
}
|
|
2111
|
+
/**
|
|
2112
|
+
* Register an event listener.
|
|
2113
|
+
* @param event - Event name
|
|
2114
|
+
* @param handler - Event handler
|
|
2115
|
+
*/
|
|
2116
|
+
on(event, handler) {
|
|
2117
|
+
let handlers = this.listeners.get(event);
|
|
2118
|
+
if (!handlers) {
|
|
2119
|
+
handlers = /* @__PURE__ */ new Set();
|
|
2120
|
+
this.listeners.set(event, handlers);
|
|
2121
|
+
}
|
|
2122
|
+
handlers.add(handler);
|
|
2123
|
+
return this;
|
|
2124
|
+
}
|
|
2125
|
+
/**
|
|
2126
|
+
* Remove an event listener.
|
|
2127
|
+
* @param event - Event name
|
|
2128
|
+
* @param handler - Event handler to remove
|
|
2129
|
+
*/
|
|
2130
|
+
off(event, handler) {
|
|
2131
|
+
this.listeners.get(event)?.delete(handler);
|
|
2132
|
+
return this;
|
|
2133
|
+
}
|
|
2134
|
+
/**
|
|
2135
|
+
* Emit a chunk to both event listeners and async iterator buffer.
|
|
2136
|
+
* Used for final chunks that should be yielded by the iterator.
|
|
2137
|
+
*/
|
|
2138
|
+
emitChunk(chunk) {
|
|
2139
|
+
this.emit("chunk", chunk);
|
|
2140
|
+
if (chunk.isFinal) {
|
|
2141
|
+
if (this.waiters.length > 0) {
|
|
2142
|
+
const waiter = this.waiters.shift();
|
|
2143
|
+
waiter?.(chunk);
|
|
2144
|
+
} else {
|
|
2145
|
+
this.buffer.push(chunk);
|
|
2146
|
+
}
|
|
2147
|
+
}
|
|
2148
|
+
}
|
|
2149
|
+
emit(event, ...args) {
|
|
2150
|
+
const handlers = this.listeners.get(event);
|
|
2151
|
+
handlers?.forEach((handler) => {
|
|
2152
|
+
try {
|
|
2153
|
+
handler(...args);
|
|
2154
|
+
} catch {
|
|
2155
|
+
}
|
|
2156
|
+
});
|
|
2157
|
+
}
|
|
2158
|
+
/**
|
|
2159
|
+
* AsyncIterable implementation for `for await` loops.
|
|
2160
|
+
*/
|
|
2161
|
+
async *[Symbol.asyncIterator]() {
|
|
2162
|
+
if (this.closed) {
|
|
2163
|
+
throw new StreamClosedError();
|
|
2164
|
+
}
|
|
2165
|
+
while (!this.closed) {
|
|
2166
|
+
const buffered = this.buffer.shift();
|
|
2167
|
+
if (buffered) {
|
|
2168
|
+
yield buffered;
|
|
2169
|
+
continue;
|
|
2170
|
+
}
|
|
2171
|
+
const chunk = await new Promise((resolve) => {
|
|
2172
|
+
if (this.closed) {
|
|
2173
|
+
resolve(null);
|
|
2174
|
+
return;
|
|
2175
|
+
}
|
|
2176
|
+
this.waiters.push(resolve);
|
|
2177
|
+
});
|
|
2178
|
+
if (chunk === null) {
|
|
2179
|
+
break;
|
|
2180
|
+
}
|
|
2181
|
+
yield chunk;
|
|
2182
|
+
}
|
|
2183
|
+
}
|
|
2184
|
+
/**
|
|
2185
|
+
* Close the stream and disconnect.
|
|
2186
|
+
*/
|
|
2187
|
+
close() {
|
|
2188
|
+
if (this.lastChunk) {
|
|
2189
|
+
const finalChunk = { ...this.lastChunk, isFinal: true };
|
|
2190
|
+
this.emitChunk(finalChunk);
|
|
2191
|
+
this.lastChunk = null;
|
|
2192
|
+
}
|
|
2193
|
+
this.closed = true;
|
|
2194
|
+
this.connection.disconnect();
|
|
2195
|
+
this.buffer = [];
|
|
2196
|
+
this.lastChunkId = null;
|
|
2197
|
+
for (const waiter of this.waiters) {
|
|
2198
|
+
waiter(null);
|
|
2199
|
+
}
|
|
2200
|
+
this.waiters = [];
|
|
2201
|
+
}
|
|
2202
|
+
/**
|
|
2203
|
+
* Whether the stream is currently connected.
|
|
2204
|
+
*/
|
|
2205
|
+
get connected() {
|
|
2206
|
+
return this.connection.connected;
|
|
2207
|
+
}
|
|
2208
|
+
};
|
|
2209
|
+
|
|
2210
|
+
// src/realtime/api.ts
|
|
2211
|
+
function createRealtimeAPI(apiKey, baseConfig) {
|
|
2212
|
+
return {
|
|
2213
|
+
async connect(transcriptId) {
|
|
2214
|
+
const stream = new RealtimeStream({
|
|
2215
|
+
apiKey,
|
|
2216
|
+
transcriptId,
|
|
2217
|
+
...baseConfig
|
|
2218
|
+
});
|
|
2219
|
+
await stream.connect();
|
|
2220
|
+
return stream;
|
|
2221
|
+
},
|
|
2222
|
+
async *stream(transcriptId) {
|
|
2223
|
+
const stream = new RealtimeStream({
|
|
2224
|
+
apiKey,
|
|
2225
|
+
transcriptId,
|
|
2226
|
+
...baseConfig
|
|
2227
|
+
});
|
|
2228
|
+
try {
|
|
2229
|
+
await stream.connect();
|
|
2230
|
+
yield* stream;
|
|
2231
|
+
} finally {
|
|
2232
|
+
stream.close();
|
|
2233
|
+
}
|
|
2234
|
+
}
|
|
2235
|
+
};
|
|
2236
|
+
}
|
|
2237
|
+
|
|
2238
|
+
// src/client.ts
|
|
2239
|
+
var FirefliesClient = class {
|
|
2240
|
+
graphql;
|
|
2241
|
+
/**
|
|
2242
|
+
* Transcript operations: list, get, search, delete.
|
|
2243
|
+
*/
|
|
2244
|
+
transcripts;
|
|
2245
|
+
/**
|
|
2246
|
+
* User operations: me, get, list, setRole.
|
|
2247
|
+
*/
|
|
2248
|
+
users;
|
|
2249
|
+
/**
|
|
2250
|
+
* Bite operations: get, list, create.
|
|
2251
|
+
*/
|
|
2252
|
+
bites;
|
|
2253
|
+
/**
|
|
2254
|
+
* Meeting operations: active meetings, add bot.
|
|
2255
|
+
*/
|
|
2256
|
+
meetings;
|
|
2257
|
+
/**
|
|
2258
|
+
* Audio operations: upload audio for transcription.
|
|
2259
|
+
*/
|
|
2260
|
+
audio;
|
|
2261
|
+
/**
|
|
2262
|
+
* AI Apps operations: list outputs.
|
|
2263
|
+
*/
|
|
2264
|
+
aiApps;
|
|
2265
|
+
/**
|
|
2266
|
+
* Realtime transcription streaming.
|
|
2267
|
+
*/
|
|
2268
|
+
realtime;
|
|
2269
|
+
/**
|
|
2270
|
+
* Create a new Fireflies client.
|
|
2271
|
+
*
|
|
2272
|
+
* @param config - Client configuration
|
|
2273
|
+
* @throws FirefliesError if API key is missing
|
|
2274
|
+
*/
|
|
2275
|
+
constructor(config) {
|
|
2276
|
+
this.graphql = new GraphQLClient(config);
|
|
2277
|
+
const transcriptsQueries = createTranscriptsAPI(this.graphql);
|
|
2278
|
+
const transcriptsMutations = createTranscriptsMutationsAPI(this.graphql);
|
|
2279
|
+
this.transcripts = { ...transcriptsQueries, ...transcriptsMutations };
|
|
2280
|
+
const usersQueries = createUsersAPI(this.graphql);
|
|
2281
|
+
const usersMutations = createUsersMutationsAPI(this.graphql);
|
|
2282
|
+
this.users = { ...usersQueries, ...usersMutations };
|
|
2283
|
+
this.bites = createBitesAPI(this.graphql);
|
|
2284
|
+
this.meetings = createMeetingsAPI(this.graphql);
|
|
2285
|
+
this.audio = createAudioAPI(this.graphql);
|
|
2286
|
+
this.aiApps = createAIAppsAPI(this.graphql);
|
|
2287
|
+
this.realtime = createRealtimeAPI(config.apiKey);
|
|
2288
|
+
}
|
|
2289
|
+
/**
|
|
2290
|
+
* Get the current rate limit state.
|
|
2291
|
+
* Returns undefined if rate limit tracking is not configured.
|
|
2292
|
+
*
|
|
2293
|
+
* @example
|
|
2294
|
+
* ```typescript
|
|
2295
|
+
* const client = new FirefliesClient({
|
|
2296
|
+
* apiKey: '...',
|
|
2297
|
+
* rateLimit: { warningThreshold: 10 }
|
|
2298
|
+
* });
|
|
2299
|
+
*
|
|
2300
|
+
* await client.users.me();
|
|
2301
|
+
* console.log(client.rateLimits);
|
|
2302
|
+
* // { remaining: 59, limit: 60, resetInSeconds: 60, updatedAt: 1706299500000 }
|
|
2303
|
+
* ```
|
|
2304
|
+
*/
|
|
2305
|
+
get rateLimits() {
|
|
2306
|
+
return this.graphql.rateLimitState;
|
|
2307
|
+
}
|
|
2308
|
+
};
|
|
2309
|
+
function verifyWebhookSignature(options) {
|
|
2310
|
+
const { payload, signature, secret } = options;
|
|
2311
|
+
if (!signature || !secret) {
|
|
2312
|
+
return false;
|
|
2313
|
+
}
|
|
2314
|
+
const payloadString = typeof payload === "string" ? payload : JSON.stringify(payload);
|
|
2315
|
+
const computed = createHmac("sha256", secret).update(payloadString).digest("hex");
|
|
2316
|
+
try {
|
|
2317
|
+
return timingSafeEqual(Buffer.from(signature), Buffer.from(computed));
|
|
2318
|
+
} catch {
|
|
2319
|
+
return false;
|
|
2320
|
+
}
|
|
2321
|
+
}
|
|
2322
|
+
|
|
2323
|
+
// src/webhooks/parse.ts
|
|
2324
|
+
var VALID_EVENT_TYPES = ["Transcription completed"];
|
|
2325
|
+
function isValidEventType(value) {
|
|
2326
|
+
return VALID_EVENT_TYPES.includes(value);
|
|
2327
|
+
}
|
|
2328
|
+
function isValidWebhookPayload(payload) {
|
|
2329
|
+
if (!payload || typeof payload !== "object") {
|
|
2330
|
+
return false;
|
|
2331
|
+
}
|
|
2332
|
+
const meetingId = payload["meetingId"];
|
|
2333
|
+
const eventType = payload["eventType"];
|
|
2334
|
+
const clientReferenceId = payload["clientReferenceId"];
|
|
2335
|
+
return typeof meetingId === "string" && typeof eventType === "string" && isValidEventType(eventType) && (clientReferenceId === void 0 || typeof clientReferenceId === "string");
|
|
2336
|
+
}
|
|
2337
|
+
function parseWebhookPayload(payload, options) {
|
|
2338
|
+
if (options?.signature && options?.secret) {
|
|
2339
|
+
const isValid = verifyWebhookSignature({
|
|
2340
|
+
payload,
|
|
2341
|
+
signature: options.signature,
|
|
2342
|
+
secret: options.secret
|
|
2343
|
+
});
|
|
2344
|
+
if (!isValid) {
|
|
2345
|
+
throw new WebhookVerificationError("Invalid webhook signature");
|
|
2346
|
+
}
|
|
2347
|
+
}
|
|
2348
|
+
if (!isValidWebhookPayload(payload)) {
|
|
2349
|
+
throw new WebhookParseError(
|
|
2350
|
+
"Invalid webhook payload: expected meetingId (string), eventType (valid event type), and optional clientReferenceId (string)"
|
|
2351
|
+
);
|
|
2352
|
+
}
|
|
2353
|
+
return payload;
|
|
2354
|
+
}
|
|
2355
|
+
|
|
2356
|
+
// src/middleware/core.ts
|
|
2357
|
+
function validateOptions(options) {
|
|
2358
|
+
if (!options.secret || !options.secret.trim()) {
|
|
2359
|
+
throw new Error("Webhook middleware: secret is required");
|
|
2360
|
+
}
|
|
2361
|
+
}
|
|
2362
|
+
function buildHandlerContext(params) {
|
|
2363
|
+
const { payload, apiKey, transcript } = params;
|
|
2364
|
+
const context = {
|
|
2365
|
+
payload
|
|
2366
|
+
};
|
|
2367
|
+
if (apiKey) {
|
|
2368
|
+
context.client = new FirefliesClient({ apiKey });
|
|
2369
|
+
}
|
|
2370
|
+
if (transcript) {
|
|
2371
|
+
context.transcript = transcript;
|
|
2372
|
+
}
|
|
2373
|
+
return context;
|
|
2374
|
+
}
|
|
2375
|
+
function parseRawBody(rawBody) {
|
|
2376
|
+
return Buffer.isBuffer(rawBody) ? rawBody.toString("utf-8") : rawBody;
|
|
2377
|
+
}
|
|
2378
|
+
function parseAndValidatePayload(rawBody, signature, secret) {
|
|
2379
|
+
if (!signature) {
|
|
2380
|
+
throw new WebhookVerificationError("Missing webhook signature");
|
|
2381
|
+
}
|
|
2382
|
+
const bodyString = parseRawBody(rawBody);
|
|
2383
|
+
let jsonPayload;
|
|
2384
|
+
try {
|
|
2385
|
+
jsonPayload = JSON.parse(bodyString);
|
|
2386
|
+
} catch {
|
|
2387
|
+
throw new WebhookParseError("Invalid JSON in webhook body");
|
|
2388
|
+
}
|
|
2389
|
+
return parseWebhookPayload(jsonPayload, { signature, secret });
|
|
2390
|
+
}
|
|
2391
|
+
async function fetchTranscriptIfEnabled(payload, apiKey, autoFetch) {
|
|
2392
|
+
if (!apiKey || autoFetch === false) {
|
|
2393
|
+
return void 0;
|
|
2394
|
+
}
|
|
2395
|
+
try {
|
|
2396
|
+
const client = new FirefliesClient({ apiKey });
|
|
2397
|
+
return await client.transcripts.get(payload.meetingId);
|
|
2398
|
+
} catch {
|
|
2399
|
+
return void 0;
|
|
2400
|
+
}
|
|
2401
|
+
}
|
|
2402
|
+
async function executeHandlers(context, options) {
|
|
2403
|
+
const { onEvent, onTranscriptionCompleted } = options;
|
|
2404
|
+
if (onEvent) {
|
|
2405
|
+
await onEvent(context);
|
|
2406
|
+
}
|
|
2407
|
+
if (context.payload.eventType === "Transcription completed" && onTranscriptionCompleted) {
|
|
2408
|
+
await onTranscriptionCompleted(context);
|
|
2409
|
+
}
|
|
2410
|
+
}
|
|
2411
|
+
function mapErrorToResponse(error) {
|
|
2412
|
+
if (error instanceof WebhookVerificationError) {
|
|
2413
|
+
return {
|
|
2414
|
+
success: false,
|
|
2415
|
+
statusCode: 401,
|
|
2416
|
+
body: "Invalid webhook signature",
|
|
2417
|
+
error
|
|
2418
|
+
};
|
|
2419
|
+
}
|
|
2420
|
+
if (error instanceof WebhookParseError) {
|
|
2421
|
+
return {
|
|
2422
|
+
success: false,
|
|
2423
|
+
statusCode: 400,
|
|
2424
|
+
body: "Invalid webhook payload",
|
|
2425
|
+
error
|
|
2426
|
+
};
|
|
2427
|
+
}
|
|
2428
|
+
if (error instanceof SyntaxError) {
|
|
2429
|
+
return {
|
|
2430
|
+
success: false,
|
|
2431
|
+
statusCode: 400,
|
|
2432
|
+
body: "Invalid JSON in webhook body",
|
|
2433
|
+
error
|
|
2434
|
+
};
|
|
2435
|
+
}
|
|
2436
|
+
return {
|
|
2437
|
+
success: false,
|
|
2438
|
+
statusCode: 500,
|
|
2439
|
+
body: "Internal server error",
|
|
2440
|
+
error: error instanceof Error ? error : new Error(String(error))
|
|
2441
|
+
};
|
|
2442
|
+
}
|
|
2443
|
+
async function processWebhook(input, options) {
|
|
2444
|
+
const { rawBody, signature } = input;
|
|
2445
|
+
const { secret, apiKey, autoFetch, onError } = options;
|
|
2446
|
+
let parsedPayload;
|
|
2447
|
+
try {
|
|
2448
|
+
parsedPayload = parseAndValidatePayload(rawBody, signature, secret);
|
|
2449
|
+
const transcript = await fetchTranscriptIfEnabled(parsedPayload, apiKey, autoFetch);
|
|
2450
|
+
const context = buildHandlerContext({
|
|
2451
|
+
payload: parsedPayload,
|
|
2452
|
+
apiKey,
|
|
2453
|
+
transcript
|
|
2454
|
+
});
|
|
2455
|
+
await executeHandlers(context, options);
|
|
2456
|
+
return {
|
|
2457
|
+
success: true,
|
|
2458
|
+
statusCode: 200,
|
|
2459
|
+
body: "ok",
|
|
2460
|
+
payload: parsedPayload
|
|
2461
|
+
};
|
|
2462
|
+
} catch (error) {
|
|
2463
|
+
if (onError && error instanceof Error) {
|
|
2464
|
+
await onError(error, parsedPayload);
|
|
2465
|
+
}
|
|
2466
|
+
return mapErrorToResponse(error);
|
|
2467
|
+
}
|
|
2468
|
+
}
|
|
2469
|
+
|
|
2470
|
+
// src/middleware/hono.ts
|
|
2471
|
+
function webhookHandler(options) {
|
|
2472
|
+
validateOptions(options);
|
|
2473
|
+
return async (c) => {
|
|
2474
|
+
const rawBody = await c.req.text();
|
|
2475
|
+
const signature = c.req.header("x-hub-signature");
|
|
2476
|
+
const result = await processWebhook(
|
|
2477
|
+
{
|
|
2478
|
+
rawBody,
|
|
2479
|
+
signature
|
|
2480
|
+
},
|
|
2481
|
+
options
|
|
2482
|
+
);
|
|
2483
|
+
return c.text(result.body, result.statusCode);
|
|
2484
|
+
};
|
|
2485
|
+
}
|
|
2486
|
+
var createWebhookHandler = webhookHandler;
|
|
2487
|
+
|
|
2488
|
+
export { createWebhookHandler, webhookHandler };
|
|
2489
|
+
//# sourceMappingURL=hono.js.map
|
|
2490
|
+
//# sourceMappingURL=hono.js.map
|