@dereekb/calcom 13.38.0 → 13.39.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.
@@ -1,2422 +0,0 @@
1
- 'use strict';
2
-
3
- var common = require('@nestjs/common');
4
- var calcom = require('@dereekb/calcom');
5
- var util = require('@dereekb/util');
6
- var nestjs = require('@dereekb/nestjs');
7
- var node_crypto = require('node:crypto');
8
- var node_path = require('node:path');
9
- var config = require('@nestjs/config');
10
-
11
- function _type_of$1(obj) {
12
- "@swc/helpers - typeof";
13
- return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
14
- }
15
- function __decorate(decorators, target, key, desc) {
16
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
17
- if ((typeof Reflect === "undefined" ? "undefined" : _type_of$1(Reflect)) === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
18
- else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
19
- return c > 3 && r && Object.defineProperty(target, key, r), r;
20
- }
21
- function __param(paramIndex, decorator) {
22
- return function(target, key) {
23
- decorator(target, key, paramIndex);
24
- };
25
- }
26
- typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
27
- var e = new Error(message);
28
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
29
- };
30
-
31
- function _class_call_check$8(instance, Constructor) {
32
- if (!(instance instanceof Constructor)) {
33
- throw new TypeError("Cannot call a class as a function");
34
- }
35
- }
36
- function _defineProperties$6(target, props) {
37
- for(var i = 0; i < props.length; i++){
38
- var descriptor = props[i];
39
- descriptor.enumerable = descriptor.enumerable || false;
40
- descriptor.configurable = true;
41
- if ("value" in descriptor) descriptor.writable = true;
42
- Object.defineProperty(target, descriptor.key, descriptor);
43
- }
44
- }
45
- function _create_class$6(Constructor, protoProps, staticProps) {
46
- if (staticProps) _defineProperties$6(Constructor, staticProps);
47
- return Constructor;
48
- }
49
- function _define_property$8(obj, key, value) {
50
- if (key in obj) {
51
- Object.defineProperty(obj, key, {
52
- value: value,
53
- enumerable: true,
54
- configurable: true,
55
- writable: true
56
- });
57
- } else {
58
- obj[key] = value;
59
- }
60
- return obj;
61
- }
62
- var CALCOM_SERVICE_NAME = 'calcom';
63
- var CALCOM_CLIENT_ID_CONFIG_KEY = 'CALCOM_CLIENT_ID';
64
- var CALCOM_CLIENT_SECRET_CONFIG_KEY = 'CALCOM_CLIENT_SECRET';
65
- var CALCOM_REFRESH_TOKEN_CONFIG_KEY = 'CALCOM_REFRESH_TOKEN';
66
- var CALCOM_API_KEY_CONFIG_KEY = 'CALCOM_API_KEY';
67
- /**
68
- * Configuration for CalcomOAuthService
69
- */ var CalcomOAuthServiceConfig = /*#__PURE__*/ function() {
70
- function CalcomOAuthServiceConfig() {
71
- _class_call_check$8(this, CalcomOAuthServiceConfig);
72
- _define_property$8(this, "calcomOAuth", void 0);
73
- _define_property$8(this, "factoryConfig", void 0);
74
- }
75
- _create_class$6(CalcomOAuthServiceConfig, null, [
76
- {
77
- key: "assertValidConfig",
78
- value: function assertValidConfig(config) {
79
- var calcomOAuth = config.calcomOAuth;
80
- if (!calcomOAuth) {
81
- throw new Error('CalcomOAuthServiceConfig.calcomOAuth is required');
82
- }
83
- // mirrors the guard in calcomOAuthFactory(): an api key IS a token, anything else is an exchange
84
- // the token endpoint authenticates with the client pair. The two must not drift
85
- var hasApiKey = !!calcomOAuth.apiKey;
86
- var hasOAuth = !!calcomOAuth.clientId && !!calcomOAuth.clientSecret;
87
- if (!hasApiKey && !hasOAuth) {
88
- throw new Error('CalcomOAuthServiceConfig requires either apiKey or clientId+clientSecret');
89
- }
90
- }
91
- }
92
- ]);
93
- return CalcomOAuthServiceConfig;
94
- }();
95
- /**
96
- * Factory function that creates a {@link CalcomOAuthServiceConfig} from NestJS ConfigService environment variables.
97
- *
98
- * @param configService - The NestJS ConfigService instance.
99
- * @returns A validated CalcomOAuthServiceConfig.
100
- */ function calcomOAuthServiceConfigFactory(configService) {
101
- var clientId = configService.get(CALCOM_CLIENT_ID_CONFIG_KEY);
102
- var clientSecret = configService.get(CALCOM_CLIENT_SECRET_CONFIG_KEY);
103
- var refreshToken = configService.get(CALCOM_REFRESH_TOKEN_CONFIG_KEY);
104
- var apiKey = configService.get(CALCOM_API_KEY_CONFIG_KEY);
105
- var config = {
106
- calcomOAuth: {
107
- clientId: clientId || undefined,
108
- clientSecret: clientSecret || undefined,
109
- refreshToken: refreshToken || undefined,
110
- apiKey: apiKey || undefined
111
- }
112
- };
113
- // the api key wins for ambient calls because it does not expire, so a configured refresh token is
114
- // silently unused. Warned here rather than in assertValidConfig, which tests call directly and
115
- // which stays side-effect-free
116
- if (apiKey && refreshToken) {
117
- new common.Logger('CalcomOAuthServiceConfig').warn("Both ".concat(CALCOM_API_KEY_CONFIG_KEY, " and ").concat(CALCOM_REFRESH_TOKEN_CONFIG_KEY, " are set. The api key takes precedence for ambient calls and the refresh token is ignored — unset one to make the intent explicit."));
118
- }
119
- CalcomOAuthServiceConfig.assertValidConfig(config);
120
- return config;
121
- }
122
-
123
- function _array_like_to_array$3(arr, len) {
124
- if (len == null || len > arr.length) len = arr.length;
125
- for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
126
- return arr2;
127
- }
128
- function _array_with_holes(arr) {
129
- if (Array.isArray(arr)) return arr;
130
- }
131
- function _array_without_holes$3(arr) {
132
- if (Array.isArray(arr)) return _array_like_to_array$3(arr);
133
- }
134
- function asyncGeneratorStep$3(gen, resolve, reject, _next, _throw, key, arg) {
135
- try {
136
- var info = gen[key](arg);
137
- var value = info.value;
138
- } catch (error) {
139
- reject(error);
140
- return;
141
- }
142
- if (info.done) {
143
- resolve(value);
144
- } else {
145
- Promise.resolve(value).then(_next, _throw);
146
- }
147
- }
148
- function _async_to_generator$3(fn) {
149
- return function() {
150
- var self = this, args = arguments;
151
- return new Promise(function(resolve, reject) {
152
- var gen = fn.apply(self, args);
153
- function _next(value) {
154
- asyncGeneratorStep$3(gen, resolve, reject, _next, _throw, "next", value);
155
- }
156
- function _throw(err) {
157
- asyncGeneratorStep$3(gen, resolve, reject, _next, _throw, "throw", err);
158
- }
159
- _next(undefined);
160
- });
161
- };
162
- }
163
- function _class_call_check$7(instance, Constructor) {
164
- if (!(instance instanceof Constructor)) {
165
- throw new TypeError("Cannot call a class as a function");
166
- }
167
- }
168
- function _define_property$7(obj, key, value) {
169
- if (key in obj) {
170
- Object.defineProperty(obj, key, {
171
- value: value,
172
- enumerable: true,
173
- configurable: true,
174
- writable: true
175
- });
176
- } else {
177
- obj[key] = value;
178
- }
179
- return obj;
180
- }
181
- function _instanceof(left, right) {
182
- "@swc/helpers - instanceof";
183
- if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
184
- return !!right[Symbol.hasInstance](left);
185
- } else {
186
- return left instanceof right;
187
- }
188
- }
189
- function _iterable_to_array$3(iter) {
190
- if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
191
- }
192
- function _iterable_to_array_limit(arr, i) {
193
- var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
194
- if (_i == null) return;
195
- var _arr = [];
196
- var _n = true;
197
- var _d = false;
198
- var _s, _e;
199
- try {
200
- for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
201
- _arr.push(_s.value);
202
- if (i && _arr.length === i) break;
203
- }
204
- } catch (err) {
205
- _d = true;
206
- _e = err;
207
- } finally{
208
- try {
209
- if (!_n && _i["return"] != null) _i["return"]();
210
- } finally{
211
- if (_d) throw _e;
212
- }
213
- }
214
- return _arr;
215
- }
216
- function _non_iterable_rest() {
217
- throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
218
- }
219
- function _non_iterable_spread$3() {
220
- throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
221
- }
222
- function _object_spread$2(target) {
223
- for(var i = 1; i < arguments.length; i++){
224
- var source = arguments[i] != null ? arguments[i] : {};
225
- var ownKeys = Object.keys(source);
226
- if (typeof Object.getOwnPropertySymbols === "function") {
227
- ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
228
- return Object.getOwnPropertyDescriptor(source, sym).enumerable;
229
- }));
230
- }
231
- ownKeys.forEach(function(key) {
232
- _define_property$7(target, key, source[key]);
233
- });
234
- }
235
- return target;
236
- }
237
- function ownKeys$2(object, enumerableOnly) {
238
- var keys = Object.keys(object);
239
- if (Object.getOwnPropertySymbols) {
240
- var symbols = Object.getOwnPropertySymbols(object);
241
- keys.push.apply(keys, symbols);
242
- }
243
- return keys;
244
- }
245
- function _object_spread_props$2(target, source) {
246
- source = source != null ? source : {};
247
- if (Object.getOwnPropertyDescriptors) {
248
- Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
249
- } else {
250
- ownKeys$2(Object(source)).forEach(function(key) {
251
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
252
- });
253
- }
254
- return target;
255
- }
256
- function _sliced_to_array(arr, i) {
257
- return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array$3(arr, i) || _non_iterable_rest();
258
- }
259
- function _to_consumable_array$3(arr) {
260
- return _array_without_holes$3(arr) || _iterable_to_array$3(arr) || _unsupported_iterable_to_array$3(arr) || _non_iterable_spread$3();
261
- }
262
- function _type_of(obj) {
263
- "@swc/helpers - typeof";
264
- return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
265
- }
266
- function _unsupported_iterable_to_array$3(o, minLen) {
267
- if (!o) return;
268
- if (typeof o === "string") return _array_like_to_array$3(o, minLen);
269
- var n = Object.prototype.toString.call(o).slice(8, -1);
270
- if (n === "Object" && o.constructor) n = o.constructor.name;
271
- if (n === "Map" || n === "Set") return Array.from(n);
272
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array$3(o, minLen);
273
- }
274
- function _ts_generator$3(thisArg, body) {
275
- var f, y, t, _ = {
276
- label: 0,
277
- sent: function() {
278
- if (t[0] & 1) throw t[1];
279
- return t[1];
280
- },
281
- trys: [],
282
- ops: []
283
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
284
- return d(g, "next", {
285
- value: verb(0)
286
- }), d(g, "throw", {
287
- value: verb(1)
288
- }), d(g, "return", {
289
- value: verb(2)
290
- }), typeof Symbol === "function" && d(g, Symbol.iterator, {
291
- value: function() {
292
- return this;
293
- }
294
- }), g;
295
- function verb(n) {
296
- return function(v) {
297
- return step([
298
- n,
299
- v
300
- ]);
301
- };
302
- }
303
- function step(op) {
304
- if (f) throw new TypeError("Generator is already executing.");
305
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
306
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
307
- if (y = 0, t) op = [
308
- op[0] & 2,
309
- t.value
310
- ];
311
- switch(op[0]){
312
- case 0:
313
- case 1:
314
- t = op;
315
- break;
316
- case 4:
317
- _.label++;
318
- return {
319
- value: op[1],
320
- done: false
321
- };
322
- case 5:
323
- _.label++;
324
- y = op[1];
325
- op = [
326
- 0
327
- ];
328
- continue;
329
- case 7:
330
- op = _.ops.pop();
331
- _.trys.pop();
332
- continue;
333
- default:
334
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
335
- _ = 0;
336
- continue;
337
- }
338
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
339
- _.label = op[1];
340
- break;
341
- }
342
- if (op[0] === 6 && _.label < t[1]) {
343
- _.label = t[1];
344
- t = op;
345
- break;
346
- }
347
- if (t && _.label < t[2]) {
348
- _.label = t[2];
349
- _.ops.push(op);
350
- break;
351
- }
352
- if (t[2]) _.ops.pop();
353
- _.trys.pop();
354
- continue;
355
- }
356
- op = body.call(thisArg, _);
357
- } catch (e) {
358
- op = [
359
- 6,
360
- e
361
- ];
362
- y = 0;
363
- } finally{
364
- f = t = 0;
365
- }
366
- if (op[0] & 5) throw op[1];
367
- return {
368
- value: op[0] ? op[1] : void 0,
369
- done: true
370
- };
371
- }
372
- }
373
- /**
374
- * Service used for retrieving CalcomAccessTokenCache for Cal.com services.
375
- *
376
- * Implementations store and retrieve OAuth access tokens (and the rotated refresh tokens
377
- * embedded in them). The service supports both a server-level cache and per-user caches
378
- * keyed either by a caller-owned key ({@link cacheForKey}) or by the user's refresh token
379
- * ({@link cacheForRefreshToken}).
380
- */ exports.CalcomOAuthAccessTokenCacheService = function CalcomOAuthAccessTokenCacheService() {
381
- _class_call_check$7(this, CalcomOAuthAccessTokenCacheService);
382
- };
383
- exports.CalcomOAuthAccessTokenCacheService = __decorate([
384
- common.Injectable()
385
- ], exports.CalcomOAuthAccessTokenCacheService);
386
- /**
387
- * Derives a short, filesystem-safe cache key from a refresh token.
388
- *
389
- * Uses SHA-256 truncated to 16 hex chars; the goal is fingerprinting, not security.
390
- *
391
- * @param refreshToken - The OAuth refresh token to hash.
392
- * @returns A 16-character hex string suitable for use as a cache key.
393
- */ function calcomRefreshTokenCacheKey(refreshToken) {
394
- return node_crypto.createHash('sha256').update(refreshToken).digest('hex').substring(0, 16);
395
- }
396
- /**
397
- * Matches any character that is unsafe in a filesystem path segment.
398
- */ var UNSAFE_CALCOM_CACHE_FILE_KEY_CHARACTERS_REGEX = /[^a-zA-Z0-9_-]/g;
399
- /**
400
- * Converts a cache key into a filesystem-safe path segment.
401
- *
402
- * A key that is already safe (such as the hex output of {@link calcomRefreshTokenCacheKey}) is
403
- * returned unchanged. Otherwise the unsafe characters are replaced and a hash of the original key
404
- * is appended, so two different keys can never collapse onto the same file.
405
- *
406
- * @param key - The cache key to convert.
407
- * @returns A filesystem-safe path segment for the key.
408
- */ function calcomAccessTokenCacheFileKey(key) {
409
- var safeKey = key.replaceAll(UNSAFE_CALCOM_CACHE_FILE_KEY_CHARACTERS_REGEX, '_');
410
- return safeKey === key ? key : "".concat(safeKey, "-").concat(node_crypto.createHash('sha256').update(key).digest('hex').substring(0, 8));
411
- }
412
- // MARK: Merge
413
- function buildCalcomReadAdapter(cache) {
414
- return {
415
- load: function load() {
416
- return _async_to_generator$3(function() {
417
- var value;
418
- return _ts_generator$3(this, function(_state) {
419
- switch(_state.label){
420
- case 0:
421
- return [
422
- 4,
423
- cache.loadCachedToken().catch(function() {
424
- return undefined;
425
- })
426
- ];
427
- case 1:
428
- value = _state.sent();
429
- return [
430
- 2,
431
- value != null && !util.isExpired(value) ? value : undefined
432
- ];
433
- }
434
- });
435
- })();
436
- },
437
- update: function update(token) {
438
- return cache.updateCachedToken(token);
439
- },
440
- clear: function clear() {
441
- return _async_to_generator$3(function() {
442
- return _ts_generator$3(this, function(_state) {
443
- return [
444
- 2
445
- ];
446
- });
447
- // CalcomAccessTokenCache does not expose a clear method.
448
- })();
449
- }
450
- };
451
- }
452
- function updateCalcomCacheCapturingError(cache, accessToken) {
453
- return cache.updateCachedToken(accessToken).then(function() {
454
- return null;
455
- }).catch(function(e) {
456
- return [
457
- cache,
458
- e
459
- ];
460
- });
461
- }
462
- /**
463
- * Default error logging function for {@link mergeCalcomOAuthAccessTokenCacheServices}.
464
- * Logs a warning for each cache that failed to update.
465
- *
466
- * @param failedUpdates - Array of tuples containing the failed cache and its error.
467
- */ function logMergeCalcomOAuthAccessTokenCacheServiceErrorFunction(failedUpdates) {
468
- console.warn("mergeCalcomOAuthAccessTokenCacheServices(): failed updating ".concat(failedUpdates.length, " caches."));
469
- failedUpdates.forEach(function(param, i) {
470
- var _param = _sliced_to_array(param, 2); _param[0]; var e = _param[1];
471
- console.warn("Cache update failure ".concat(i + 1, ": - ").concat(e));
472
- });
473
- }
474
- /**
475
- * Merges the input services in order to use some as a backup source.
476
- *
477
- * If one source fails retrieval, the next will be tried.
478
- * When updating a cached token, it will update the token across all services.
479
- *
480
- * Read fall-through is delegated to {@link mergeAsyncValueCaches} after wrapping each
481
- * underlying cache with an {@link isExpired}-aware filter, so an expired cached token
482
- * never short-circuits the lookup. Updates run across all services in parallel via
483
- * `Promise.allSettled`, mirroring the previous behavior, with optional error logging.
484
- *
485
- * @param inputServicesToMerge - Must include at least one service. Empty arrays will throw an error.
486
- * @param logError - Optional error logging configuration; pass a function, true for default logging, or false to disable.
487
- * @returns A merged CalcomOAuthAccessTokenCacheService that delegates across all input services.
488
- * @throws {Error} When `inputServicesToMerge` is empty.
489
- */ function mergeCalcomOAuthAccessTokenCacheServices(inputServicesToMerge, logError) {
490
- var allServices = _to_consumable_array$3(inputServicesToMerge);
491
- var logErrorFunction = typeof logError === 'function' ? logError : logError === false ? undefined : logMergeCalcomOAuthAccessTokenCacheServiceErrorFunction;
492
- if (allServices.length === 0) {
493
- throw new Error('mergeCalcomOAuthAccessTokenCacheServices() input cannot be empty.');
494
- }
495
- function mergeCachesForService(accessCachesForServices) {
496
- var readAdapters = accessCachesForServices.map(buildCalcomReadAdapter);
497
- var merged = util.mergeAsyncValueCaches(readAdapters);
498
- return {
499
- loadCachedToken: function loadCachedToken() {
500
- return merged.load();
501
- },
502
- updateCachedToken: function updateCachedToken(accessToken) {
503
- return _async_to_generator$3(function() {
504
- var settled, failedUpdates;
505
- return _ts_generator$3(this, function(_state) {
506
- switch(_state.label){
507
- case 0:
508
- return [
509
- 4,
510
- Promise.allSettled(accessCachesForServices.map(function(cache) {
511
- return updateCalcomCacheCapturingError(cache, accessToken);
512
- }))
513
- ];
514
- case 1:
515
- settled = _state.sent();
516
- if (logErrorFunction != null) {
517
- failedUpdates = util.filterMaybeArrayValues(settled.map(function(y) {
518
- return y.value;
519
- }));
520
- if (failedUpdates.length) {
521
- logErrorFunction(failedUpdates);
522
- }
523
- }
524
- return [
525
- 2
526
- ];
527
- }
528
- });
529
- })();
530
- }
531
- };
532
- }
533
- var allServiceAccessTokenCaches = allServices.map(function(x) {
534
- return x.loadCalcomAccessTokenCache();
535
- });
536
- var allServicesWithCacheForRefreshToken = allServices.filter(function(x) {
537
- return x.cacheForRefreshToken != null;
538
- });
539
- var allServicesWithCacheForKey = allServices.filter(function(x) {
540
- return x.cacheForKey != null;
541
- });
542
- var cacheForRefreshToken = allServicesWithCacheForRefreshToken.length > 0 ? function(refreshToken) {
543
- var allCaches = allServicesWithCacheForRefreshToken.map(function(x) {
544
- return x.cacheForRefreshToken(refreshToken);
545
- });
546
- return mergeCachesForService(allCaches);
547
- } : undefined;
548
- var cacheForKey = allServicesWithCacheForKey.length > 0 ? function(key) {
549
- var allCaches = allServicesWithCacheForKey.map(function(x) {
550
- return x.cacheForKey(key);
551
- });
552
- return mergeCachesForService(allCaches);
553
- } : undefined;
554
- var service = {
555
- loadCalcomAccessTokenCache: function loadCalcomAccessTokenCache() {
556
- return mergeCachesForService(allServiceAccessTokenCaches);
557
- },
558
- cacheForKey: cacheForKey,
559
- cacheForRefreshToken: cacheForRefreshToken
560
- };
561
- return service;
562
- }
563
- // MARK: Memory Access Token Cache
564
- /**
565
- * Adapts an {@link AsyncValueCache} to a {@link CalcomAccessTokenCache}, optionally logging cache reads/writes to the console.
566
- *
567
- * @param cache - Underlying single-value cache for the access token.
568
- * @param logAccessToConsole - When true, logs reads and writes to the console.
569
- * @returns The CalcomAccessTokenCache backed by the given async cache.
570
- */ function calcomAccessTokenCacheFromAsyncValueCache(cache, logAccessToConsole) {
571
- return {
572
- loadCachedToken: function loadCachedToken() {
573
- return _async_to_generator$3(function() {
574
- var token;
575
- return _ts_generator$3(this, function(_state) {
576
- switch(_state.label){
577
- case 0:
578
- return [
579
- 4,
580
- cache.load()
581
- ];
582
- case 1:
583
- token = _state.sent();
584
- if (logAccessToConsole) {
585
- console.log('retrieving access token from memory: ', {
586
- hit: token != null,
587
- expiresAt: token === null || token === void 0 ? void 0 : token.expiresAt
588
- });
589
- }
590
- return [
591
- 2,
592
- token
593
- ];
594
- }
595
- });
596
- })();
597
- },
598
- updateCachedToken: function updateCachedToken(accessToken) {
599
- return _async_to_generator$3(function() {
600
- return _ts_generator$3(this, function(_state) {
601
- switch(_state.label){
602
- case 0:
603
- return [
604
- 4,
605
- cache.update(accessToken)
606
- ];
607
- case 1:
608
- _state.sent();
609
- if (logAccessToConsole) {
610
- console.log('updating access token in memory: ', {
611
- expiresAt: accessToken === null || accessToken === void 0 ? void 0 : accessToken.expiresAt
612
- });
613
- }
614
- return [
615
- 2
616
- ];
617
- }
618
- });
619
- })();
620
- }
621
- };
622
- }
623
- /**
624
- * Creates a CalcomOAuthAccessTokenCacheService that uses in-memory storage.
625
- *
626
- * The server-level token is held in a single-slot {@link inMemoryAsyncValueCache};
627
- * per-user tokens are held in an {@link inMemoryAsyncKeyedValueCache} keyed by the
628
- * sha256-truncated refresh token hash.
629
- *
630
- * @param existingToken - Optional pre-existing server-level access token to seed the cache.
631
- * @param logAccessToConsole - When true, logs all cache reads and writes to console.
632
- * @returns A CalcomOAuthAccessTokenCacheService backed by in-memory caches.
633
- */ function memoryCalcomOAuthAccessTokenCacheService(existingToken, logAccessToConsole) {
634
- var serverCache = util.inMemoryAsyncValueCache(existingToken);
635
- var userCache = util.inMemoryAsyncKeyedValueCache();
636
- function userCacheView(key) {
637
- return {
638
- load: function load() {
639
- return userCache.get(key);
640
- },
641
- update: function update(token) {
642
- return userCache.set(key, token);
643
- },
644
- clear: function clear() {
645
- return userCache.remove(key);
646
- }
647
- };
648
- }
649
- function cacheForKey(key) {
650
- return calcomAccessTokenCacheFromAsyncValueCache(userCacheView(key), logAccessToConsole);
651
- }
652
- return {
653
- loadCalcomAccessTokenCache: function loadCalcomAccessTokenCache() {
654
- return calcomAccessTokenCacheFromAsyncValueCache(serverCache, logAccessToConsole);
655
- },
656
- cacheForKey: cacheForKey,
657
- cacheForRefreshToken: function cacheForRefreshToken(refreshToken) {
658
- return cacheForKey(calcomRefreshTokenCacheKey(refreshToken));
659
- }
660
- };
661
- }
662
- // MARK: File System Access Token Cache
663
- var DEFAULT_FILE_CALCOM_ACCESS_TOKEN_CACHE_DIR = '.tmp/calcom-tokens';
664
- var CALCOM_SERVER_TOKEN_FILE_KEY = 'server';
665
- /**
666
- * Reviver applied to the cached file payload on load so `expiresAt` is always a `Date`
667
- * regardless of how it was serialized.
668
- *
669
- * @param raw - The raw JSON-parsed file payload.
670
- * @returns The revived CalcomAccessToken, or undefined when the payload is empty/invalid.
671
- */ function reviveCalcomAccessTokenFile(raw) {
672
- var result;
673
- if (raw == null || (typeof raw === "undefined" ? "undefined" : _type_of(raw)) !== 'object') {
674
- result = undefined;
675
- } else {
676
- var wrapper = raw;
677
- var token = wrapper.token;
678
- if (token == null) {
679
- result = undefined;
680
- } else {
681
- var rawExpiresAt = token.expiresAt;
682
- var expiresAt = rawExpiresAt != null && !_instanceof(rawExpiresAt, Date) ? new Date(rawExpiresAt) : rawExpiresAt;
683
- result = _object_spread_props$2(_object_spread$2({}, token), {
684
- expiresAt: expiresAt
685
- });
686
- }
687
- }
688
- return result;
689
- }
690
- /**
691
- * Creates a CalcomOAuthAccessTokenCacheService that reads and writes access tokens
692
- * to the file system. Each user gets their own file, keyed by an sha256 hash of their refresh token.
693
- *
694
- * Backed by {@link createMemoizedJsonFileAsyncValueCache} for each key, so reads after
695
- * the first hit memory.
696
- *
697
- * File structure:
698
- * ```
699
- * <cacheDir>/
700
- * server.json — server-level token
701
- * user-<sha256hash>.json — per-user tokens (hash of initial refresh token)
702
- * ```
703
- *
704
- * @param cacheDir - Directory to store token files. Defaults to `.tmp/calcom-tokens`.
705
- * @returns A CalcomOAuthAccessTokenCacheService backed by the file system.
706
- */ function fileCalcomOAuthAccessTokenCacheService() {
707
- var cacheDir = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : DEFAULT_FILE_CALCOM_ACCESS_TOKEN_CACHE_DIR;
708
- var cachesByKey = new Map();
709
- function cacheForKey(fileKey) {
710
- var cache = cachesByKey.get(fileKey);
711
- if (cache == null) {
712
- cache = nestjs.createMemoizedJsonFileAsyncValueCache({
713
- filePath: node_path.join(cacheDir, "".concat(fileKey, ".json")),
714
- reviver: reviveCalcomAccessTokenFile,
715
- replacer: function replacer(token) {
716
- return {
717
- token: token
718
- };
719
- }
720
- });
721
- cachesByKey.set(fileKey, cache);
722
- }
723
- return cache;
724
- }
725
- function makeCacheForKey(fileKey) {
726
- var cache = cacheForKey(fileKey);
727
- return {
728
- loadCachedToken: function loadCachedToken() {
729
- return cache.load();
730
- },
731
- updateCachedToken: function updateCachedToken(accessToken) {
732
- return _async_to_generator$3(function() {
733
- var e;
734
- return _ts_generator$3(this, function(_state) {
735
- switch(_state.label){
736
- case 0:
737
- _state.trys.push([
738
- 0,
739
- 2,
740
- ,
741
- 3
742
- ]);
743
- return [
744
- 4,
745
- cache.update(accessToken)
746
- ];
747
- case 1:
748
- _state.sent();
749
- return [
750
- 3,
751
- 3
752
- ];
753
- case 2:
754
- e = _state.sent();
755
- console.error("Failed updating token file for ".concat(fileKey, ": "), e);
756
- throw e;
757
- case 3:
758
- return [
759
- 2
760
- ];
761
- }
762
- });
763
- })();
764
- }
765
- };
766
- }
767
- function cacheForCallerKey(key) {
768
- return makeCacheForKey("user-".concat(calcomAccessTokenCacheFileKey(key)));
769
- }
770
- return {
771
- cacheDir: cacheDir,
772
- loadCalcomAccessTokenCache: function loadCalcomAccessTokenCache() {
773
- return makeCacheForKey(CALCOM_SERVER_TOKEN_FILE_KEY);
774
- },
775
- cacheForKey: cacheForCallerKey,
776
- cacheForRefreshToken: function cacheForRefreshToken(refreshToken) {
777
- return cacheForCallerKey(calcomRefreshTokenCacheKey(refreshToken));
778
- }
779
- };
780
- }
781
-
782
- function asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, key, arg) {
783
- try {
784
- var info = gen[key](arg);
785
- var value = info.value;
786
- } catch (error) {
787
- reject(error);
788
- return;
789
- }
790
- if (info.done) {
791
- resolve(value);
792
- } else {
793
- Promise.resolve(value).then(_next, _throw);
794
- }
795
- }
796
- function _async_to_generator$2(fn) {
797
- return function() {
798
- var self = this, args = arguments;
799
- return new Promise(function(resolve, reject) {
800
- var gen = fn.apply(self, args);
801
- function _next(value) {
802
- asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, "next", value);
803
- }
804
- function _throw(err) {
805
- asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, "throw", err);
806
- }
807
- _next(undefined);
808
- });
809
- };
810
- }
811
- function _class_call_check$6(instance, Constructor) {
812
- if (!(instance instanceof Constructor)) {
813
- throw new TypeError("Cannot call a class as a function");
814
- }
815
- }
816
- function _defineProperties$5(target, props) {
817
- for(var i = 0; i < props.length; i++){
818
- var descriptor = props[i];
819
- descriptor.enumerable = descriptor.enumerable || false;
820
- descriptor.configurable = true;
821
- if ("value" in descriptor) descriptor.writable = true;
822
- Object.defineProperty(target, descriptor.key, descriptor);
823
- }
824
- }
825
- function _create_class$5(Constructor, protoProps, staticProps) {
826
- if (protoProps) _defineProperties$5(Constructor.prototype, protoProps);
827
- return Constructor;
828
- }
829
- function _define_property$6(obj, key, value) {
830
- if (key in obj) {
831
- Object.defineProperty(obj, key, {
832
- value: value,
833
- enumerable: true,
834
- configurable: true,
835
- writable: true
836
- });
837
- } else {
838
- obj[key] = value;
839
- }
840
- return obj;
841
- }
842
- function _ts_generator$2(thisArg, body) {
843
- var f, y, t, _ = {
844
- label: 0,
845
- sent: function() {
846
- if (t[0] & 1) throw t[1];
847
- return t[1];
848
- },
849
- trys: [],
850
- ops: []
851
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
852
- return d(g, "next", {
853
- value: verb(0)
854
- }), d(g, "throw", {
855
- value: verb(1)
856
- }), d(g, "return", {
857
- value: verb(2)
858
- }), typeof Symbol === "function" && d(g, Symbol.iterator, {
859
- value: function() {
860
- return this;
861
- }
862
- }), g;
863
- function verb(n) {
864
- return function(v) {
865
- return step([
866
- n,
867
- v
868
- ]);
869
- };
870
- }
871
- function step(op) {
872
- if (f) throw new TypeError("Generator is already executing.");
873
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
874
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
875
- if (y = 0, t) op = [
876
- op[0] & 2,
877
- t.value
878
- ];
879
- switch(op[0]){
880
- case 0:
881
- case 1:
882
- t = op;
883
- break;
884
- case 4:
885
- _.label++;
886
- return {
887
- value: op[1],
888
- done: false
889
- };
890
- case 5:
891
- _.label++;
892
- y = op[1];
893
- op = [
894
- 0
895
- ];
896
- continue;
897
- case 7:
898
- op = _.ops.pop();
899
- _.trys.pop();
900
- continue;
901
- default:
902
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
903
- _ = 0;
904
- continue;
905
- }
906
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
907
- _.label = op[1];
908
- break;
909
- }
910
- if (op[0] === 6 && _.label < t[1]) {
911
- _.label = t[1];
912
- t = op;
913
- break;
914
- }
915
- if (t && _.label < t[2]) {
916
- _.label = t[2];
917
- _.ops.push(op);
918
- break;
919
- }
920
- if (t[2]) _.ops.pop();
921
- _.trys.pop();
922
- continue;
923
- }
924
- op = body.call(thisArg, _);
925
- } catch (e) {
926
- op = [
927
- 6,
928
- e
929
- ];
930
- y = 0;
931
- } finally{
932
- f = t = 0;
933
- }
934
- if (op[0] & 5) throw op[1];
935
- return {
936
- value: op[0] ? op[1] : void 0,
937
- done: true
938
- };
939
- }
940
- }
941
- exports.CalcomOAuthApi = /*#__PURE__*/ function() {
942
- function CalcomOAuthApi(config, cacheService) {
943
- _class_call_check$6(this, CalcomOAuthApi);
944
- var _config_factoryConfig;
945
- _define_property$6(this, "config", void 0);
946
- _define_property$6(this, "cacheService", void 0);
947
- _define_property$6(this, "calcomOAuth", void 0);
948
- this.config = config;
949
- this.cacheService = cacheService;
950
- var accessTokenCache = cacheService.loadCalcomAccessTokenCache();
951
- var _config_calcomOAuth = config.calcomOAuth, clientId = _config_calcomOAuth.clientId, clientSecret = _config_calcomOAuth.clientSecret, refreshToken = _config_calcomOAuth.refreshToken, apiKey = _config_calcomOAuth.apiKey;
952
- // the environment-facing config stays flat, mirroring the CALCOM_* variables it is read from.
953
- // `client` is the app's OAuth registration, sent on every exchange; `defaultAuth` is the one
954
- // credential the ambient loadAccessToken() resolves. The client is taken as a pair or not at all,
955
- // which replaces the empty-string sentinels this used to pass for a config with no OAuth client
956
- this.calcomOAuth = calcom.calcomOAuthFactory((_config_factoryConfig = config.factoryConfig) !== null && _config_factoryConfig !== void 0 ? _config_factoryConfig : {})({
957
- client: clientId && clientSecret ? {
958
- clientId: clientId,
959
- clientSecret: clientSecret
960
- } : undefined,
961
- defaultAuth: calcom.calcomAuthCredentialFromValues({
962
- apiKey: apiKey,
963
- refreshToken: refreshToken,
964
- accessTokenCache: accessTokenCache
965
- })
966
- });
967
- }
968
- _create_class$5(CalcomOAuthApi, [
969
- {
970
- key: "oauthContext",
971
- get: function get() {
972
- return this.calcomOAuth.oauthContext;
973
- }
974
- },
975
- {
976
- key: "exchangeAuthorizationCode",
977
- get: // MARK: Accessors
978
- /**
979
- * Configured pass-through for {@link exchangeAuthorizationCode}.
980
- *
981
- * @returns Function to exchange an OAuth authorization code for tokens.
982
- */ function get() {
983
- return calcom.exchangeAuthorizationCode(this.oauthContext);
984
- }
985
- },
986
- {
987
- key: "exchangeAuthorizationCodeToAccessToken",
988
- value: /**
989
- * Exchanges an OAuth authorization code and maps the response to a {@link CalcomAccessToken}.
990
- *
991
- * The returned `refreshToken` is the one to persist: Cal.com rotates refresh tokens on every use.
992
- *
993
- * @param input - The authorization code and the exact redirect URI it was issued for.
994
- * @returns The exchanged access token.
995
- */ function exchangeAuthorizationCodeToAccessToken(input) {
996
- return _async_to_generator$2(function() {
997
- var response;
998
- return _ts_generator$2(this, function(_state) {
999
- switch(_state.label){
1000
- case 0:
1001
- return [
1002
- 4,
1003
- this.exchangeAuthorizationCode(input)
1004
- ];
1005
- case 1:
1006
- response = _state.sent();
1007
- return [
1008
- 2,
1009
- calcom.calcomAccessTokenFromTokenResponse(response)
1010
- ];
1011
- }
1012
- });
1013
- }).call(this);
1014
- }
1015
- },
1016
- {
1017
- /**
1018
- * Retrieves an access token for a specific user using their refresh token.
1019
- *
1020
- * @param credential - The user's refresh token credential, with the cache scoped to that grant.
1021
- * @returns Promise resolving to the user's CalcomAccessToken.
1022
- */ key: "userAccessToken",
1023
- value: function userAccessToken(credential) {
1024
- return this.userAccessTokenFactory(credential)();
1025
- }
1026
- },
1027
- {
1028
- /**
1029
- * Returns the CalcomAccessTokenFactory for a user's credential.
1030
- *
1031
- * A fresh factory on every call: its in-memory tier lives only as long as the returned factory, so
1032
- * one caller's tokens are never visible to the next. Durable sharing is the access token cache's
1033
- * job — see {@link cacheForKey}.
1034
- *
1035
- * @param credential - The user's refresh token credential.
1036
- * @returns The CalcomAccessTokenFactory for that credential.
1037
- */ key: "userAccessTokenFactory",
1038
- value: function userAccessTokenFactory(credential) {
1039
- return this.oauthContext.makeAccessTokenFactory(credential);
1040
- }
1041
- },
1042
- {
1043
- /**
1044
- * Returns a per-user CalcomAccessTokenCache for a stable, caller-owned key.
1045
- * Returns undefined if the cache service does not support keyed caching.
1046
- *
1047
- * Preferred over {@link cacheForRefreshToken}, whose key changes as Cal.com rotates the token.
1048
- *
1049
- * @param key - A stable key identifying the user, such as their user or profile id.
1050
- * @returns A per-user access token cache, or undefined if not supported.
1051
- */ key: "cacheForKey",
1052
- value: function cacheForKey(key) {
1053
- var _this_cacheService_cacheForKey, _this_cacheService;
1054
- return (_this_cacheService_cacheForKey = (_this_cacheService = this.cacheService).cacheForKey) === null || _this_cacheService_cacheForKey === void 0 ? void 0 : _this_cacheService_cacheForKey.call(_this_cacheService, key);
1055
- }
1056
- },
1057
- {
1058
- /**
1059
- * Returns a per-user CalcomAccessTokenCache derived from a hash of the refresh token.
1060
- * Returns undefined if the cache service does not support per-user caching.
1061
- *
1062
- * @param refreshToken - The user's OAuth refresh token used to derive the cache key.
1063
- * @returns A per-user access token cache, or undefined if not supported.
1064
- */ key: "cacheForRefreshToken",
1065
- value: function cacheForRefreshToken(refreshToken) {
1066
- var _this_cacheService_cacheForRefreshToken, _this_cacheService;
1067
- return (_this_cacheService_cacheForRefreshToken = (_this_cacheService = this.cacheService).cacheForRefreshToken) === null || _this_cacheService_cacheForRefreshToken === void 0 ? void 0 : _this_cacheService_cacheForRefreshToken.call(_this_cacheService, refreshToken);
1068
- }
1069
- }
1070
- ]);
1071
- return CalcomOAuthApi;
1072
- }();
1073
- exports.CalcomOAuthApi = __decorate([
1074
- common.Injectable(),
1075
- __param(0, common.Inject(CalcomOAuthServiceConfig)),
1076
- __param(1, common.Inject(exports.CalcomOAuthAccessTokenCacheService))
1077
- ], exports.CalcomOAuthApi);
1078
-
1079
- function _array_like_to_array$2(arr, len) {
1080
- if (len == null || len > arr.length) len = arr.length;
1081
- for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
1082
- return arr2;
1083
- }
1084
- function _array_without_holes$2(arr) {
1085
- if (Array.isArray(arr)) return _array_like_to_array$2(arr);
1086
- }
1087
- function _iterable_to_array$2(iter) {
1088
- if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
1089
- }
1090
- function _non_iterable_spread$2() {
1091
- throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
1092
- }
1093
- function _to_consumable_array$2(arr) {
1094
- return _array_without_holes$2(arr) || _iterable_to_array$2(arr) || _unsupported_iterable_to_array$2(arr) || _non_iterable_spread$2();
1095
- }
1096
- function _unsupported_iterable_to_array$2(o, minLen) {
1097
- if (!o) return;
1098
- if (typeof o === "string") return _array_like_to_array$2(o, minLen);
1099
- var n = Object.prototype.toString.call(o).slice(8, -1);
1100
- if (n === "Object" && o.constructor) n = o.constructor.name;
1101
- if (n === "Map" || n === "Set") return Array.from(n);
1102
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array$2(o, minLen);
1103
- }
1104
- /**
1105
- * Convenience function used to generate ModuleMetadata for an app's CalcomOAuthModule.
1106
- *
1107
- * @param config - The module metadata configuration including optional dependency module and config factory.
1108
- * @returns NestJS ModuleMetadata for registering the CalcomOAuthModule.
1109
- */ function appCalcomOAuthModuleMetadata(config$1) {
1110
- var _config_calcomOAuthServiceConfigFactory;
1111
- var dependencyModule = config$1.dependencyModule, imports = config$1.imports, exports$1 = config$1.exports, providers = config$1.providers;
1112
- var dependencyModuleImport = dependencyModule ? [
1113
- dependencyModule
1114
- ] : [];
1115
- return {
1116
- imports: [
1117
- config.ConfigModule
1118
- ].concat(_to_consumable_array$2(dependencyModuleImport), _to_consumable_array$2(imports !== null && imports !== void 0 ? imports : [])),
1119
- exports: [
1120
- exports.CalcomOAuthApi
1121
- ].concat(_to_consumable_array$2(exports$1 !== null && exports$1 !== void 0 ? exports$1 : [])),
1122
- providers: [
1123
- {
1124
- provide: CalcomOAuthServiceConfig,
1125
- inject: [
1126
- config.ConfigService
1127
- ],
1128
- useFactory: (_config_calcomOAuthServiceConfigFactory = config$1.calcomOAuthServiceConfigFactory) !== null && _config_calcomOAuthServiceConfigFactory !== void 0 ? _config_calcomOAuthServiceConfigFactory : calcomOAuthServiceConfigFactory
1129
- },
1130
- exports.CalcomOAuthApi
1131
- ].concat(_to_consumable_array$2(providers !== null && providers !== void 0 ? providers : []))
1132
- };
1133
- }
1134
-
1135
- function _class_call_check$5(instance, Constructor) {
1136
- if (!(instance instanceof Constructor)) {
1137
- throw new TypeError("Cannot call a class as a function");
1138
- }
1139
- }
1140
- function _defineProperties$4(target, props) {
1141
- for(var i = 0; i < props.length; i++){
1142
- var descriptor = props[i];
1143
- descriptor.enumerable = descriptor.enumerable || false;
1144
- descriptor.configurable = true;
1145
- if ("value" in descriptor) descriptor.writable = true;
1146
- Object.defineProperty(target, descriptor.key, descriptor);
1147
- }
1148
- }
1149
- function _create_class$4(Constructor, protoProps, staticProps) {
1150
- if (staticProps) _defineProperties$4(Constructor, staticProps);
1151
- return Constructor;
1152
- }
1153
- function _define_property$5(obj, key, value) {
1154
- if (key in obj) {
1155
- Object.defineProperty(obj, key, {
1156
- value: value,
1157
- enumerable: true,
1158
- configurable: true,
1159
- writable: true
1160
- });
1161
- } else {
1162
- obj[key] = value;
1163
- }
1164
- return obj;
1165
- }
1166
- /**
1167
- * Configuration for CalcomService
1168
- */ var CalcomServiceConfig = /*#__PURE__*/ function() {
1169
- function CalcomServiceConfig() {
1170
- _class_call_check$5(this, CalcomServiceConfig);
1171
- _define_property$5(this, "calcom", void 0);
1172
- _define_property$5(this, "factoryConfig", void 0);
1173
- }
1174
- _create_class$4(CalcomServiceConfig, null, [
1175
- {
1176
- key: "assertValidConfig",
1177
- value: function assertValidConfig(_config) {
1178
- // no required env-specific config currently
1179
- }
1180
- }
1181
- ]);
1182
- return CalcomServiceConfig;
1183
- }
1184
- ();
1185
-
1186
- function _class_call_check$4(instance, Constructor) {
1187
- if (!(instance instanceof Constructor)) {
1188
- throw new TypeError("Cannot call a class as a function");
1189
- }
1190
- }
1191
- function _defineProperties$3(target, props) {
1192
- for(var i = 0; i < props.length; i++){
1193
- var descriptor = props[i];
1194
- descriptor.enumerable = descriptor.enumerable || false;
1195
- descriptor.configurable = true;
1196
- if ("value" in descriptor) descriptor.writable = true;
1197
- Object.defineProperty(target, descriptor.key, descriptor);
1198
- }
1199
- }
1200
- function _create_class$3(Constructor, protoProps, staticProps) {
1201
- if (protoProps) _defineProperties$3(Constructor.prototype, protoProps);
1202
- return Constructor;
1203
- }
1204
- function _define_property$4(obj, key, value) {
1205
- if (key in obj) {
1206
- Object.defineProperty(obj, key, {
1207
- value: value,
1208
- enumerable: true,
1209
- configurable: true,
1210
- writable: true
1211
- });
1212
- } else {
1213
- obj[key] = value;
1214
- }
1215
- return obj;
1216
- }
1217
- function _object_spread$1(target) {
1218
- for(var i = 1; i < arguments.length; i++){
1219
- var source = arguments[i] != null ? arguments[i] : {};
1220
- var ownKeys = Object.keys(source);
1221
- if (typeof Object.getOwnPropertySymbols === "function") {
1222
- ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
1223
- return Object.getOwnPropertyDescriptor(source, sym).enumerable;
1224
- }));
1225
- }
1226
- ownKeys.forEach(function(key) {
1227
- _define_property$4(target, key, source[key]);
1228
- });
1229
- }
1230
- return target;
1231
- }
1232
- function ownKeys$1(object, enumerableOnly) {
1233
- var keys = Object.keys(object);
1234
- if (Object.getOwnPropertySymbols) {
1235
- var symbols = Object.getOwnPropertySymbols(object);
1236
- keys.push.apply(keys, symbols);
1237
- }
1238
- return keys;
1239
- }
1240
- function _object_spread_props$1(target, source) {
1241
- source = source != null ? source : {};
1242
- if (Object.getOwnPropertyDescriptors) {
1243
- Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
1244
- } else {
1245
- ownKeys$1(Object(source)).forEach(function(key) {
1246
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
1247
- });
1248
- }
1249
- return target;
1250
- }
1251
- /**
1252
- * Injectable NestJS service that provides access to the Cal.com API.
1253
- *
1254
- * Use {@link serverContextInstance} to access API functions via the server context,
1255
- * or {@link makeUserContextInstance} to create per-mentor API instances.
1256
- *
1257
- * @example
1258
- * ```ts
1259
- * // Server context (API key or server OAuth)
1260
- * const instance = calcomApi.serverContextInstance;
1261
- * const me = await instance.getMe();
1262
- *
1263
- * // Per-mentor context
1264
- * const mentorInstance = calcomApi.makeUserContextInstance({ refreshToken: mentor.calcomRefreshToken });
1265
- * const eventTypes = await mentorInstance.getEventTypes();
1266
- *
1267
- * // Public slot query (no auth)
1268
- * const slots = await calcomApi.getAvailableSlots({ start: '...', end: '...', eventTypeId: 123 });
1269
- * ```
1270
- */ exports.CalcomApi = /*#__PURE__*/ function() {
1271
- function CalcomApi(config, calcomOAuthApi) {
1272
- var _this = this;
1273
- _class_call_check$4(this, CalcomApi);
1274
- _define_property$4(this, "config", void 0);
1275
- _define_property$4(this, "calcomOAuthApi", void 0);
1276
- _define_property$4(this, "calcom", void 0);
1277
- _define_property$4(this, "_serverInstance", util.cachedGetter(function() {
1278
- return new CalcomApiContextInstance(_this, _this.calcomServerContext);
1279
- }));
1280
- _define_property$4(this, "_publicContext", util.cachedGetter(function() {
1281
- return _this.calcom.calcomServerContext.makePublicContext();
1282
- }));
1283
- this.config = config;
1284
- this.calcomOAuthApi = calcomOAuthApi;
1285
- this.calcom = calcom.calcomFactory(_object_spread_props$1(_object_spread$1({}, config.factoryConfig), {
1286
- oauthContext: calcomOAuthApi.oauthContext
1287
- }))(config.calcom);
1288
- }
1289
- _create_class$3(CalcomApi, [
1290
- {
1291
- key: "calcomServerContext",
1292
- get: function get() {
1293
- return this.calcom.calcomServerContext;
1294
- }
1295
- },
1296
- {
1297
- key: "serverContextInstance",
1298
- get: /**
1299
- * Returns the cached {@link CalcomApiContextInstance} for the server context.
1300
- * All API functions are available through this instance.
1301
- *
1302
- * @returns The server context instance.
1303
- */ function get() {
1304
- return this._serverInstance();
1305
- }
1306
- },
1307
- {
1308
- key: "getAvailableSlots",
1309
- get: // MARK: Public Context
1310
- /**
1311
- * Configured pass-through for {@link getAvailableSlots} using the public (unauthenticated) context.
1312
- *
1313
- * @returns Function to query available slots without authentication.
1314
- */ function get() {
1315
- return calcom.getAvailableSlots(this._publicContext());
1316
- }
1317
- },
1318
- {
1319
- // MARK: Context Creation
1320
- /**
1321
- * Creates a {@link CalcomApiContextInstance} for a specific user using their OAuth refresh token.
1322
- * The returned instance has all API functions scoped to that user's account.
1323
- *
1324
- * When no explicit `accessTokenCache` is provided, a per-user cache is automatically
1325
- * resolved from the cache service using an md5 hash of the refresh token as the key.
1326
- * This ensures tokens persist across requests and server restarts without collisions.
1327
- *
1328
- * @param credential - The user's refresh token credential, with an optional cache scoped to that grant.
1329
- * @returns A new CalcomApiContextInstance scoped to the user.
1330
- *
1331
- * @example
1332
- * ```ts
1333
- * // Automatic per-user caching (recommended):
1334
- * const userInstance = calcomApi.makeUserContextInstance({
1335
- * refreshToken: user.calcomRefreshToken
1336
- * });
1337
- *
1338
- * // With explicit cache override:
1339
- * const userInstance = calcomApi.makeUserContextInstance({
1340
- * refreshToken: user.calcomRefreshToken,
1341
- * accessTokenCache: customCache
1342
- * });
1343
- * ```
1344
- */ key: "makeUserContextInstance",
1345
- value: function makeUserContextInstance(credential) {
1346
- var _credential_accessTokenCache;
1347
- // auto-resolve a per-user cache from the refresh token when none was given
1348
- var accessTokenCache = (_credential_accessTokenCache = credential.accessTokenCache) !== null && _credential_accessTokenCache !== void 0 ? _credential_accessTokenCache : this.calcomOAuthApi.cacheForRefreshToken(credential.refreshToken);
1349
- var userContext = this.calcom.calcomServerContext.makeUserContext(_object_spread_props$1(_object_spread$1({}, credential), {
1350
- accessTokenCache: accessTokenCache
1351
- }));
1352
- return this.makeContextInstance(userContext);
1353
- }
1354
- },
1355
- {
1356
- /**
1357
- * Creates a {@link CalcomApiContextInstance} from any {@link CalcomContext}.
1358
- *
1359
- * @param context - The CalcomContext (server or user) to wrap.
1360
- * @returns A new CalcomApiContextInstance bound to the given context.
1361
- */ key: "makeContextInstance",
1362
- value: function makeContextInstance(context) {
1363
- return new CalcomApiContextInstance(this, context);
1364
- }
1365
- },
1366
- {
1367
- /**
1368
- * Creates a raw {@link CalcomUserContext} from a refresh token, without wrapping in a {@link CalcomApiContextInstance}.
1369
- * Prefer {@link makeUserContextInstance} unless you need direct context access.
1370
- *
1371
- * @param credential - The user's refresh token credential, with the cache scoped to that grant.
1372
- * @returns A CalcomUserContext for the given user.
1373
- */ key: "makeUserContext",
1374
- value: function makeUserContext(credential) {
1375
- return this.calcom.calcomServerContext.makeUserContext(credential);
1376
- }
1377
- }
1378
- ]);
1379
- return CalcomApi;
1380
- }();
1381
- exports.CalcomApi = __decorate([
1382
- common.Injectable(),
1383
- __param(0, common.Inject(CalcomServiceConfig)),
1384
- __param(1, common.Inject(exports.CalcomOAuthApi))
1385
- ], exports.CalcomApi);
1386
- /**
1387
- * Wraps a {@link CalcomContext} (server or user) and exposes all authenticated Cal.com API
1388
- * functions bound to that context. Each getter delegates to the corresponding function
1389
- * from `@dereekb/calcom`.
1390
- *
1391
- * Access the parent {@link CalcomApi} via {@link calcomApi} for public endpoints
1392
- * (e.g., `calcomApi.getAvailableSlots`) or to create additional context instances.
1393
- *
1394
- * @example
1395
- * ```ts
1396
- * const instance = calcomApi.serverContextInstance;
1397
- *
1398
- * // Authenticated API calls
1399
- * const me = await instance.getMe();
1400
- * const schedules = await instance.getSchedules();
1401
- *
1402
- * // Access public endpoints via parent
1403
- * const slots = await instance.calcomApi.getAvailableSlots({ start: '...', end: '...', eventTypeId: 123 });
1404
- * ```
1405
- */ var CalcomApiContextInstance = /*#__PURE__*/ function() {
1406
- function CalcomApiContextInstance(calcomApi, context) {
1407
- _class_call_check$4(this, CalcomApiContextInstance);
1408
- _define_property$4(this, "calcomApi", void 0);
1409
- _define_property$4(this, "context", void 0);
1410
- this.calcomApi = calcomApi;
1411
- this.context = context;
1412
- }
1413
- _create_class$3(CalcomApiContextInstance, [
1414
- {
1415
- key: "getMe",
1416
- get: // MARK: User
1417
- /**
1418
- * Configured pass-through for {@link getMe}.
1419
- *
1420
- * @returns Function to retrieve the authenticated user's profile.
1421
- */ function get() {
1422
- return calcom.getMe(this.context);
1423
- }
1424
- },
1425
- {
1426
- key: "getSchedules",
1427
- get: // MARK: Schedules
1428
- /**
1429
- * Configured pass-through for {@link getSchedules}.
1430
- *
1431
- * @returns Function to retrieve all schedules for the authenticated user.
1432
- */ function get() {
1433
- return calcom.getSchedules(this.context);
1434
- }
1435
- },
1436
- {
1437
- key: "createBooking",
1438
- get: // MARK: Bookings
1439
- /**
1440
- * Configured pass-through for {@link createBooking}.
1441
- *
1442
- * @returns Function to create a new booking.
1443
- */ function get() {
1444
- return calcom.createBooking(this.context);
1445
- }
1446
- },
1447
- {
1448
- key: "getBooking",
1449
- get: /**
1450
- * Configured pass-through for {@link getBooking}.
1451
- *
1452
- * @returns Function to retrieve a booking by UID.
1453
- */ function get() {
1454
- return calcom.getBooking(this.context);
1455
- }
1456
- },
1457
- {
1458
- key: "getBookings",
1459
- get: /**
1460
- * Configured pass-through for {@link getBookings}.
1461
- *
1462
- * @returns Function to retrieve a page of bookings.
1463
- */ function get() {
1464
- return calcom.getBookings(this.context);
1465
- }
1466
- },
1467
- {
1468
- key: "cancelBooking",
1469
- get: /**
1470
- * Configured pass-through for {@link cancelBooking}.
1471
- *
1472
- * @returns Function to cancel a booking by UID.
1473
- */ function get() {
1474
- return calcom.cancelBooking(this.context);
1475
- }
1476
- },
1477
- {
1478
- key: "getEventTypes",
1479
- get: // MARK: Event Types
1480
- /**
1481
- * Configured pass-through for {@link getEventTypes}.
1482
- *
1483
- * @returns Function to retrieve all event types for the authenticated user.
1484
- */ function get() {
1485
- return calcom.getEventTypes(this.context);
1486
- }
1487
- },
1488
- {
1489
- key: "createEventType",
1490
- get: /**
1491
- * Configured pass-through for {@link createEventType}.
1492
- *
1493
- * @returns Function to create a new event type.
1494
- */ function get() {
1495
- return calcom.createEventType(this.context);
1496
- }
1497
- },
1498
- {
1499
- key: "updateEventType",
1500
- get: /**
1501
- * Configured pass-through for {@link updateEventType}.
1502
- *
1503
- * @returns Function to update an existing event type by ID.
1504
- */ function get() {
1505
- return calcom.updateEventType(this.context);
1506
- }
1507
- },
1508
- {
1509
- key: "deleteEventType",
1510
- get: /**
1511
- * Configured pass-through for {@link deleteEventType}.
1512
- *
1513
- * @returns Function to delete an event type by ID.
1514
- */ function get() {
1515
- return calcom.deleteEventType(this.context);
1516
- }
1517
- },
1518
- {
1519
- key: "getCalendars",
1520
- get: // MARK: Calendars
1521
- /**
1522
- * Configured pass-through for {@link getCalendars}.
1523
- *
1524
- * @returns Function to retrieve all connected calendars.
1525
- */ function get() {
1526
- return calcom.getCalendars(this.context);
1527
- }
1528
- },
1529
- {
1530
- key: "getBusyTimes",
1531
- get: /**
1532
- * Configured pass-through for {@link getBusyTimes}.
1533
- *
1534
- * @returns Function to retrieve busy time ranges across connected calendars.
1535
- */ function get() {
1536
- return calcom.getBusyTimes(this.context);
1537
- }
1538
- },
1539
- {
1540
- key: "getBusyTimesForConnectedCalendars",
1541
- get: /**
1542
- * Configured pass-through for {@link getBusyTimesForConnectedCalendars}.
1543
- *
1544
- * @returns Function to retrieve busy times without having to resolve `calendarsToLoad` first.
1545
- */ function get() {
1546
- return calcom.getBusyTimesForConnectedCalendars(this.context);
1547
- }
1548
- },
1549
- {
1550
- key: "createWebhook",
1551
- get: // MARK: Webhooks
1552
- /**
1553
- * Configured pass-through for {@link createWebhook}.
1554
- *
1555
- * @returns Function to create a webhook subscription.
1556
- */ function get() {
1557
- return calcom.createWebhook(this.context);
1558
- }
1559
- },
1560
- {
1561
- key: "getWebhooks",
1562
- get: /**
1563
- * Configured pass-through for {@link getWebhooks}.
1564
- *
1565
- * @returns Function to retrieve all webhooks.
1566
- */ function get() {
1567
- return calcom.getWebhooks(this.context);
1568
- }
1569
- },
1570
- {
1571
- key: "getWebhook",
1572
- get: /**
1573
- * Configured pass-through for {@link getWebhook}.
1574
- *
1575
- * @returns Function to retrieve a specific webhook by ID.
1576
- */ function get() {
1577
- return calcom.getWebhook(this.context);
1578
- }
1579
- },
1580
- {
1581
- key: "updateWebhook",
1582
- get: /**
1583
- * Configured pass-through for {@link updateWebhook}.
1584
- *
1585
- * @returns Function to update an existing webhook by ID.
1586
- */ function get() {
1587
- return calcom.updateWebhook(this.context);
1588
- }
1589
- },
1590
- {
1591
- key: "deleteWebhook",
1592
- get: /**
1593
- * Configured pass-through for {@link deleteWebhook}.
1594
- *
1595
- * @returns Function to delete a webhook by ID.
1596
- */ function get() {
1597
- return calcom.deleteWebhook(this.context);
1598
- }
1599
- }
1600
- ]);
1601
- return CalcomApiContextInstance;
1602
- }
1603
- ();
1604
-
1605
- function _array_like_to_array$1(arr, len) {
1606
- if (len == null || len > arr.length) len = arr.length;
1607
- for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
1608
- return arr2;
1609
- }
1610
- function _array_without_holes$1(arr) {
1611
- if (Array.isArray(arr)) return _array_like_to_array$1(arr);
1612
- }
1613
- function _iterable_to_array$1(iter) {
1614
- if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
1615
- }
1616
- function _non_iterable_spread$1() {
1617
- throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
1618
- }
1619
- function _to_consumable_array$1(arr) {
1620
- return _array_without_holes$1(arr) || _iterable_to_array$1(arr) || _unsupported_iterable_to_array$1(arr) || _non_iterable_spread$1();
1621
- }
1622
- function _unsupported_iterable_to_array$1(o, minLen) {
1623
- if (!o) return;
1624
- if (typeof o === "string") return _array_like_to_array$1(o, minLen);
1625
- var n = Object.prototype.toString.call(o).slice(8, -1);
1626
- if (n === "Object" && o.constructor) n = o.constructor.name;
1627
- if (n === "Map" || n === "Set") return Array.from(n);
1628
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array$1(o, minLen);
1629
- }
1630
- // MARK: Provider Factories
1631
- /**
1632
- * Factory function that creates a {@link CalcomServiceConfig} from NestJS ConfigService values.
1633
- *
1634
- * @param _configService - The NestJS ConfigService instance.
1635
- * @returns A validated CalcomServiceConfig.
1636
- */ function calcomServiceConfigFactory(_configService) {
1637
- var config = {
1638
- calcom: {}
1639
- };
1640
- CalcomServiceConfig.assertValidConfig(config);
1641
- return config;
1642
- }
1643
- /**
1644
- * Convenience function used to generate ModuleMetadata for an app's CalcomModule.
1645
- *
1646
- * @param config - The module metadata configuration including optional dependency module.
1647
- * @returns NestJS ModuleMetadata for registering the CalcomModule.
1648
- */ function appCalcomModuleMetadata(config$1) {
1649
- var dependencyModule = config$1.dependencyModule, imports = config$1.imports, exports$1 = config$1.exports, providers = config$1.providers;
1650
- var dependencyModuleImport = dependencyModule ? [
1651
- dependencyModule
1652
- ] : [];
1653
- return {
1654
- imports: [
1655
- config.ConfigModule
1656
- ].concat(_to_consumable_array$1(dependencyModuleImport), _to_consumable_array$1(imports !== null && imports !== void 0 ? imports : [])),
1657
- exports: [
1658
- exports.CalcomApi
1659
- ].concat(_to_consumable_array$1(exports$1 !== null && exports$1 !== void 0 ? exports$1 : [])),
1660
- providers: [
1661
- {
1662
- provide: CalcomServiceConfig,
1663
- inject: [
1664
- config.ConfigService
1665
- ],
1666
- useFactory: calcomServiceConfigFactory
1667
- },
1668
- exports.CalcomApi
1669
- ].concat(_to_consumable_array$1(providers !== null && providers !== void 0 ? providers : []))
1670
- };
1671
- }
1672
-
1673
- // MARK: Event Types
1674
- var CALCOM_WEBHOOK_BOOKING_CREATED = 'BOOKING_CREATED';
1675
- var CALCOM_WEBHOOK_BOOKING_CANCELLED = 'BOOKING_CANCELLED';
1676
- var CALCOM_WEBHOOK_BOOKING_RESCHEDULED = 'BOOKING_RESCHEDULED';
1677
-
1678
- function _define_property$3(obj, key, value) {
1679
- if (key in obj) {
1680
- Object.defineProperty(obj, key, {
1681
- value: value,
1682
- enumerable: true,
1683
- configurable: true,
1684
- writable: true
1685
- });
1686
- } else {
1687
- obj[key] = value;
1688
- }
1689
- return obj;
1690
- }
1691
- function _object_spread(target) {
1692
- for(var i = 1; i < arguments.length; i++){
1693
- var source = arguments[i] != null ? arguments[i] : {};
1694
- var ownKeys = Object.keys(source);
1695
- if (typeof Object.getOwnPropertySymbols === "function") {
1696
- ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
1697
- return Object.getOwnPropertyDescriptor(source, sym).enumerable;
1698
- }));
1699
- }
1700
- ownKeys.forEach(function(key) {
1701
- _define_property$3(target, key, source[key]);
1702
- });
1703
- }
1704
- return target;
1705
- }
1706
- function ownKeys(object, enumerableOnly) {
1707
- var keys = Object.keys(object);
1708
- if (Object.getOwnPropertySymbols) {
1709
- var symbols = Object.getOwnPropertySymbols(object);
1710
- keys.push.apply(keys, symbols);
1711
- }
1712
- return keys;
1713
- }
1714
- function _object_spread_props(target, source) {
1715
- source = source != null ? source : {};
1716
- if (Object.getOwnPropertyDescriptors) {
1717
- Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
1718
- } else {
1719
- ownKeys(Object(source)).forEach(function(key) {
1720
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
1721
- });
1722
- }
1723
- return target;
1724
- }
1725
- /**
1726
- * Creates a CalcomWebhookEvent and treats the data as the input type.
1727
- *
1728
- * @param event - The untyped webhook event to convert.
1729
- * @returns A typed CalcomWebhookEvent with the payload cast to type T.
1730
- */ function calcomWebhookEvent(event) {
1731
- return {
1732
- triggerEvent: event.triggerEvent,
1733
- createdAt: event.createdAt,
1734
- payload: event.payload
1735
- };
1736
- }
1737
- var calcomEventHandlerFactory = util.handlerFactory(function(x) {
1738
- return x.triggerEvent;
1739
- });
1740
- var calcomEventHandlerConfigurerFactory = util.handlerConfigurerFactory({
1741
- configurerForAccessor: function configurerForAccessor(accessor) {
1742
- var fnWithKey = util.handlerMappedSetFunctionFactory(accessor, calcomWebhookEvent);
1743
- var configurer = _object_spread_props(_object_spread({}, accessor), {
1744
- handleBookingCreated: fnWithKey(CALCOM_WEBHOOK_BOOKING_CREATED),
1745
- handleBookingCancelled: fnWithKey(CALCOM_WEBHOOK_BOOKING_CANCELLED),
1746
- handleBookingRescheduled: fnWithKey(CALCOM_WEBHOOK_BOOKING_RESCHEDULED)
1747
- });
1748
- return configurer;
1749
- }
1750
- });
1751
-
1752
- function _class_call_check$3(instance, Constructor) {
1753
- if (!(instance instanceof Constructor)) {
1754
- throw new TypeError("Cannot call a class as a function");
1755
- }
1756
- }
1757
- function _defineProperties$2(target, props) {
1758
- for(var i = 0; i < props.length; i++){
1759
- var descriptor = props[i];
1760
- descriptor.enumerable = descriptor.enumerable || false;
1761
- descriptor.configurable = true;
1762
- if ("value" in descriptor) descriptor.writable = true;
1763
- Object.defineProperty(target, descriptor.key, descriptor);
1764
- }
1765
- }
1766
- function _create_class$2(Constructor, protoProps, staticProps) {
1767
- if (staticProps) _defineProperties$2(Constructor, staticProps);
1768
- return Constructor;
1769
- }
1770
- function _define_property$2(obj, key, value) {
1771
- if (key in obj) {
1772
- Object.defineProperty(obj, key, {
1773
- value: value,
1774
- enumerable: true,
1775
- configurable: true,
1776
- writable: true
1777
- });
1778
- } else {
1779
- obj[key] = value;
1780
- }
1781
- return obj;
1782
- }
1783
- var CALCOM_WEBHOOK_SECRET_CONFIG_KEY = 'CALCOM_WEBHOOK_SECRET';
1784
- /**
1785
- * Configuration for CalcomWebhookService
1786
- */ var CalcomWebhookServiceConfig = /*#__PURE__*/ function() {
1787
- function CalcomWebhookServiceConfig() {
1788
- _class_call_check$3(this, CalcomWebhookServiceConfig);
1789
- _define_property$2(this, "webhookConfig", void 0);
1790
- }
1791
- _create_class$2(CalcomWebhookServiceConfig, null, [
1792
- {
1793
- key: "assertValidConfig",
1794
- value: function assertValidConfig(config) {
1795
- if (!config.webhookConfig.webhookSecret) {
1796
- throw new Error('No Cal.com webhook secret specified.');
1797
- }
1798
- }
1799
- }
1800
- ]);
1801
- return CalcomWebhookServiceConfig;
1802
- }
1803
- ();
1804
-
1805
- /**
1806
- * Verifies a Cal.com webhook event using HMAC-SHA256 signature.
1807
- *
1808
- * @param secret - The webhook signing secret.
1809
- * @returns Verifies a Cal.com webhook event.
1810
- */ function calcomWebhookEventVerifier(secret) {
1811
- return function(rawBody, headers) {
1812
- var _headers_xcalsignature256;
1813
- var rawBodyString = rawBody.toString('utf8');
1814
- var signature = (_headers_xcalsignature256 = headers['x-cal-signature-256']) !== null && _headers_xcalsignature256 !== void 0 ? _headers_xcalsignature256 : '';
1815
- var expectedSignature = node_crypto.createHmac('sha256', secret).update(rawBodyString).digest('hex');
1816
- var valid = signature === expectedSignature;
1817
- var event;
1818
- try {
1819
- event = JSON.parse(rawBodyString);
1820
- } catch (unused) {
1821
- event = {
1822
- triggerEvent: '',
1823
- createdAt: '',
1824
- payload: {}
1825
- };
1826
- }
1827
- var result = {
1828
- valid: valid,
1829
- event: event
1830
- };
1831
- return result;
1832
- };
1833
- }
1834
-
1835
- function asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, key, arg) {
1836
- try {
1837
- var info = gen[key](arg);
1838
- var value = info.value;
1839
- } catch (error) {
1840
- reject(error);
1841
- return;
1842
- }
1843
- if (info.done) {
1844
- resolve(value);
1845
- } else {
1846
- Promise.resolve(value).then(_next, _throw);
1847
- }
1848
- }
1849
- function _async_to_generator$1(fn) {
1850
- return function() {
1851
- var self = this, args = arguments;
1852
- return new Promise(function(resolve, reject) {
1853
- var gen = fn.apply(self, args);
1854
- function _next(value) {
1855
- asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, "next", value);
1856
- }
1857
- function _throw(err) {
1858
- asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, "throw", err);
1859
- }
1860
- _next(undefined);
1861
- });
1862
- };
1863
- }
1864
- function _class_call_check$2(instance, Constructor) {
1865
- if (!(instance instanceof Constructor)) {
1866
- throw new TypeError("Cannot call a class as a function");
1867
- }
1868
- }
1869
- function _defineProperties$1(target, props) {
1870
- for(var i = 0; i < props.length; i++){
1871
- var descriptor = props[i];
1872
- descriptor.enumerable = descriptor.enumerable || false;
1873
- descriptor.configurable = true;
1874
- if ("value" in descriptor) descriptor.writable = true;
1875
- Object.defineProperty(target, descriptor.key, descriptor);
1876
- }
1877
- }
1878
- function _create_class$1(Constructor, protoProps, staticProps) {
1879
- if (protoProps) _defineProperties$1(Constructor.prototype, protoProps);
1880
- return Constructor;
1881
- }
1882
- function _define_property$1(obj, key, value) {
1883
- if (key in obj) {
1884
- Object.defineProperty(obj, key, {
1885
- value: value,
1886
- enumerable: true,
1887
- configurable: true,
1888
- writable: true
1889
- });
1890
- } else {
1891
- obj[key] = value;
1892
- }
1893
- return obj;
1894
- }
1895
- function _ts_generator$1(thisArg, body) {
1896
- var f, y, t, _ = {
1897
- label: 0,
1898
- sent: function() {
1899
- if (t[0] & 1) throw t[1];
1900
- return t[1];
1901
- },
1902
- trys: [],
1903
- ops: []
1904
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
1905
- return d(g, "next", {
1906
- value: verb(0)
1907
- }), d(g, "throw", {
1908
- value: verb(1)
1909
- }), d(g, "return", {
1910
- value: verb(2)
1911
- }), typeof Symbol === "function" && d(g, Symbol.iterator, {
1912
- value: function() {
1913
- return this;
1914
- }
1915
- }), g;
1916
- function verb(n) {
1917
- return function(v) {
1918
- return step([
1919
- n,
1920
- v
1921
- ]);
1922
- };
1923
- }
1924
- function step(op) {
1925
- if (f) throw new TypeError("Generator is already executing.");
1926
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
1927
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
1928
- if (y = 0, t) op = [
1929
- op[0] & 2,
1930
- t.value
1931
- ];
1932
- switch(op[0]){
1933
- case 0:
1934
- case 1:
1935
- t = op;
1936
- break;
1937
- case 4:
1938
- _.label++;
1939
- return {
1940
- value: op[1],
1941
- done: false
1942
- };
1943
- case 5:
1944
- _.label++;
1945
- y = op[1];
1946
- op = [
1947
- 0
1948
- ];
1949
- continue;
1950
- case 7:
1951
- op = _.ops.pop();
1952
- _.trys.pop();
1953
- continue;
1954
- default:
1955
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
1956
- _ = 0;
1957
- continue;
1958
- }
1959
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
1960
- _.label = op[1];
1961
- break;
1962
- }
1963
- if (op[0] === 6 && _.label < t[1]) {
1964
- _.label = t[1];
1965
- t = op;
1966
- break;
1967
- }
1968
- if (t && _.label < t[2]) {
1969
- _.label = t[2];
1970
- _.ops.push(op);
1971
- break;
1972
- }
1973
- if (t[2]) _.ops.pop();
1974
- _.trys.pop();
1975
- continue;
1976
- }
1977
- op = body.call(thisArg, _);
1978
- } catch (e) {
1979
- op = [
1980
- 6,
1981
- e
1982
- ];
1983
- y = 0;
1984
- } finally{
1985
- f = t = 0;
1986
- }
1987
- if (op[0] & 5) throw op[1];
1988
- return {
1989
- value: op[0] ? op[1] : void 0,
1990
- done: true
1991
- };
1992
- }
1993
- }
1994
- /**
1995
- * Service that makes system changes based on Cal.com webhook events.
1996
- */ exports.CalcomWebhookService = /*#__PURE__*/ function() {
1997
- function CalcomWebhookService(config) {
1998
- _class_call_check$2(this, CalcomWebhookService);
1999
- _define_property$1(this, "logger", new common.Logger('CalcomWebhookService'));
2000
- _define_property$1(this, "_verifier", void 0);
2001
- _define_property$1(this, "handler", calcomEventHandlerFactory());
2002
- _define_property$1(this, "configure", calcomEventHandlerConfigurerFactory(this.handler));
2003
- this._verifier = calcomWebhookEventVerifier(config.webhookConfig.webhookSecret);
2004
- }
2005
- _create_class$1(CalcomWebhookService, [
2006
- {
2007
- key: "updateForWebhook",
2008
- value: function updateForWebhook(req, rawBody) {
2009
- return _async_to_generator$1(function() {
2010
- var headers, _this__verifier, valid, event, handled, result;
2011
- return _ts_generator$1(this, function(_state) {
2012
- switch(_state.label){
2013
- case 0:
2014
- headers = req.headers;
2015
- _this__verifier = this._verifier(rawBody, headers), valid = _this__verifier.valid, event = _this__verifier.event;
2016
- handled = false;
2017
- if (!valid) return [
2018
- 3,
2019
- 2
2020
- ];
2021
- return [
2022
- 4,
2023
- this.updateForCalcomEvent(event)
2024
- ];
2025
- case 1:
2026
- handled = _state.sent();
2027
- return [
2028
- 3,
2029
- 3
2030
- ];
2031
- case 2:
2032
- this.logger.warn('Received invalid calcom event: ', event);
2033
- _state.label = 3;
2034
- case 3:
2035
- result = {
2036
- valid: valid,
2037
- handled: handled,
2038
- event: event
2039
- };
2040
- return [
2041
- 2,
2042
- result
2043
- ];
2044
- }
2045
- });
2046
- }).call(this);
2047
- }
2048
- },
2049
- {
2050
- key: "updateForCalcomEvent",
2051
- value: function updateForCalcomEvent(event) {
2052
- return _async_to_generator$1(function() {
2053
- var handled;
2054
- return _ts_generator$1(this, function(_state) {
2055
- switch(_state.label){
2056
- case 0:
2057
- return [
2058
- 4,
2059
- this.handler(event)
2060
- ];
2061
- case 1:
2062
- handled = _state.sent();
2063
- if (!handled) {
2064
- this.logger.warn('Received unexpected/unhandled calcom event: ', event);
2065
- }
2066
- return [
2067
- 2,
2068
- handled
2069
- ];
2070
- }
2071
- });
2072
- }).call(this);
2073
- }
2074
- }
2075
- ]);
2076
- return CalcomWebhookService;
2077
- }();
2078
- exports.CalcomWebhookService = __decorate([
2079
- common.Injectable(),
2080
- __param(0, common.Inject(CalcomWebhookServiceConfig))
2081
- ], exports.CalcomWebhookService);
2082
-
2083
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
2084
- try {
2085
- var info = gen[key](arg);
2086
- var value = info.value;
2087
- } catch (error) {
2088
- reject(error);
2089
- return;
2090
- }
2091
- if (info.done) {
2092
- resolve(value);
2093
- } else {
2094
- Promise.resolve(value).then(_next, _throw);
2095
- }
2096
- }
2097
- function _async_to_generator(fn) {
2098
- return function() {
2099
- var self = this, args = arguments;
2100
- return new Promise(function(resolve, reject) {
2101
- var gen = fn.apply(self, args);
2102
- function _next(value) {
2103
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
2104
- }
2105
- function _throw(err) {
2106
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
2107
- }
2108
- _next(undefined);
2109
- });
2110
- };
2111
- }
2112
- function _class_call_check$1(instance, Constructor) {
2113
- if (!(instance instanceof Constructor)) {
2114
- throw new TypeError("Cannot call a class as a function");
2115
- }
2116
- }
2117
- function _defineProperties(target, props) {
2118
- for(var i = 0; i < props.length; i++){
2119
- var descriptor = props[i];
2120
- descriptor.enumerable = descriptor.enumerable || false;
2121
- descriptor.configurable = true;
2122
- if ("value" in descriptor) descriptor.writable = true;
2123
- Object.defineProperty(target, descriptor.key, descriptor);
2124
- }
2125
- }
2126
- function _create_class(Constructor, protoProps, staticProps) {
2127
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
2128
- return Constructor;
2129
- }
2130
- function _define_property(obj, key, value) {
2131
- if (key in obj) {
2132
- Object.defineProperty(obj, key, {
2133
- value: value,
2134
- enumerable: true,
2135
- configurable: true,
2136
- writable: true
2137
- });
2138
- } else {
2139
- obj[key] = value;
2140
- }
2141
- return obj;
2142
- }
2143
- function _ts_generator(thisArg, body) {
2144
- var f, y, t, _ = {
2145
- label: 0,
2146
- sent: function() {
2147
- if (t[0] & 1) throw t[1];
2148
- return t[1];
2149
- },
2150
- trys: [],
2151
- ops: []
2152
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
2153
- return d(g, "next", {
2154
- value: verb(0)
2155
- }), d(g, "throw", {
2156
- value: verb(1)
2157
- }), d(g, "return", {
2158
- value: verb(2)
2159
- }), typeof Symbol === "function" && d(g, Symbol.iterator, {
2160
- value: function() {
2161
- return this;
2162
- }
2163
- }), g;
2164
- function verb(n) {
2165
- return function(v) {
2166
- return step([
2167
- n,
2168
- v
2169
- ]);
2170
- };
2171
- }
2172
- function step(op) {
2173
- if (f) throw new TypeError("Generator is already executing.");
2174
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
2175
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
2176
- if (y = 0, t) op = [
2177
- op[0] & 2,
2178
- t.value
2179
- ];
2180
- switch(op[0]){
2181
- case 0:
2182
- case 1:
2183
- t = op;
2184
- break;
2185
- case 4:
2186
- _.label++;
2187
- return {
2188
- value: op[1],
2189
- done: false
2190
- };
2191
- case 5:
2192
- _.label++;
2193
- y = op[1];
2194
- op = [
2195
- 0
2196
- ];
2197
- continue;
2198
- case 7:
2199
- op = _.ops.pop();
2200
- _.trys.pop();
2201
- continue;
2202
- default:
2203
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
2204
- _ = 0;
2205
- continue;
2206
- }
2207
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
2208
- _.label = op[1];
2209
- break;
2210
- }
2211
- if (op[0] === 6 && _.label < t[1]) {
2212
- _.label = t[1];
2213
- t = op;
2214
- break;
2215
- }
2216
- if (t && _.label < t[2]) {
2217
- _.label = t[2];
2218
- _.ops.push(op);
2219
- break;
2220
- }
2221
- if (t[2]) _.ops.pop();
2222
- _.trys.pop();
2223
- continue;
2224
- }
2225
- op = body.call(thisArg, _);
2226
- } catch (e) {
2227
- op = [
2228
- 6,
2229
- e
2230
- ];
2231
- y = 0;
2232
- } finally{
2233
- f = t = 0;
2234
- }
2235
- if (op[0] & 5) throw op[1];
2236
- return {
2237
- value: op[0] ? op[1] : void 0,
2238
- done: true
2239
- };
2240
- }
2241
- }
2242
- exports.CalcomWebhookController = /*#__PURE__*/ function() {
2243
- function CalcomWebhookController(calcomWebhookService) {
2244
- _class_call_check$1(this, CalcomWebhookController);
2245
- _define_property(this, "calcomWebhookService", void 0);
2246
- this.calcomWebhookService = calcomWebhookService;
2247
- }
2248
- _create_class(CalcomWebhookController, [
2249
- {
2250
- key: "handleCalcomWebhook",
2251
- value: function handleCalcomWebhook(res, req, rawBody) {
2252
- return _async_to_generator(function() {
2253
- var _ref, response;
2254
- return _ts_generator(this, function(_state) {
2255
- switch(_state.label){
2256
- case 0:
2257
- return [
2258
- 4,
2259
- this.calcomWebhookService.updateForWebhook(req, rawBody)
2260
- ];
2261
- case 1:
2262
- _ref = _state.sent(), _ref.valid;
2263
- response = res.status(200); // always return a 200 status code
2264
- response.json({});
2265
- return [
2266
- 2
2267
- ];
2268
- }
2269
- });
2270
- }).call(this);
2271
- }
2272
- }
2273
- ]);
2274
- return CalcomWebhookController;
2275
- }();
2276
- __decorate([
2277
- common.Post(),
2278
- __param(0, common.Res()),
2279
- __param(1, common.Req()),
2280
- __param(2, nestjs.RawBody())
2281
- ], exports.CalcomWebhookController.prototype, "handleCalcomWebhook", null);
2282
- exports.CalcomWebhookController = __decorate([
2283
- common.Controller('/webhook/calcom'),
2284
- __param(0, common.Inject(exports.CalcomWebhookService))
2285
- ], exports.CalcomWebhookController);
2286
-
2287
- function _array_like_to_array(arr, len) {
2288
- if (len == null || len > arr.length) len = arr.length;
2289
- for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
2290
- return arr2;
2291
- }
2292
- function _array_without_holes(arr) {
2293
- if (Array.isArray(arr)) return _array_like_to_array(arr);
2294
- }
2295
- function _class_call_check(instance, Constructor) {
2296
- if (!(instance instanceof Constructor)) {
2297
- throw new TypeError("Cannot call a class as a function");
2298
- }
2299
- }
2300
- function _iterable_to_array(iter) {
2301
- if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
2302
- }
2303
- function _non_iterable_spread() {
2304
- throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
2305
- }
2306
- function _to_consumable_array(arr) {
2307
- return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
2308
- }
2309
- function _unsupported_iterable_to_array(o, minLen) {
2310
- if (!o) return;
2311
- if (typeof o === "string") return _array_like_to_array(o, minLen);
2312
- var n = Object.prototype.toString.call(o).slice(8, -1);
2313
- if (n === "Object" && o.constructor) n = o.constructor.name;
2314
- if (n === "Map" || n === "Set") return Array.from(n);
2315
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
2316
- }
2317
- /**
2318
- * Factory function that creates a {@link CalcomWebhookServiceConfig} from NestJS ConfigService environment variables.
2319
- *
2320
- * @param configService - The NestJS ConfigService instance.
2321
- * @returns A validated CalcomWebhookServiceConfig.
2322
- */ function calcomWebhookServiceConfigFactory(configService) {
2323
- var config = {
2324
- webhookConfig: {
2325
- webhookSecret: configService.get(CALCOM_WEBHOOK_SECRET_CONFIG_KEY)
2326
- }
2327
- };
2328
- CalcomWebhookServiceConfig.assertValidConfig(config);
2329
- return config;
2330
- }
2331
- /**
2332
- * Configures webhooks for the service.
2333
- */ exports.CalcomWebhookModule = function CalcomWebhookModule() {
2334
- _class_call_check(this, CalcomWebhookModule);
2335
- };
2336
- exports.CalcomWebhookModule = __decorate([
2337
- common.Module({
2338
- imports: [
2339
- config.ConfigModule
2340
- ],
2341
- controllers: [
2342
- exports.CalcomWebhookController
2343
- ],
2344
- exports: [
2345
- exports.CalcomWebhookService
2346
- ],
2347
- providers: [
2348
- {
2349
- provide: CalcomWebhookServiceConfig,
2350
- inject: [
2351
- config.ConfigService
2352
- ],
2353
- useFactory: calcomWebhookServiceConfigFactory
2354
- },
2355
- exports.CalcomWebhookService
2356
- ]
2357
- })
2358
- ], exports.CalcomWebhookModule);
2359
- /**
2360
- * Convenience function used to generate ModuleMetadata for an app's CalcomWebhookModule.
2361
- *
2362
- * @param config - The module metadata configuration including optional dependency module.
2363
- * @returns NestJS ModuleMetadata for registering the CalcomWebhookModule.
2364
- */ function appCalcomWebhookModuleMetadata(config$1) {
2365
- var dependencyModule = config$1.dependencyModule, imports = config$1.imports, exports$1 = config$1.exports, providers = config$1.providers;
2366
- var dependencyModuleImport = dependencyModule ? [
2367
- dependencyModule
2368
- ] : [];
2369
- return {
2370
- imports: [
2371
- config.ConfigModule
2372
- ].concat(_to_consumable_array(dependencyModuleImport), _to_consumable_array(imports !== null && imports !== void 0 ? imports : [])),
2373
- controllers: [
2374
- exports.CalcomWebhookController
2375
- ],
2376
- exports: [
2377
- exports.CalcomWebhookService
2378
- ].concat(_to_consumable_array(exports$1 !== null && exports$1 !== void 0 ? exports$1 : [])),
2379
- providers: [
2380
- {
2381
- provide: CalcomWebhookServiceConfig,
2382
- inject: [
2383
- config.ConfigService
2384
- ],
2385
- useFactory: calcomWebhookServiceConfigFactory
2386
- },
2387
- exports.CalcomWebhookService
2388
- ].concat(_to_consumable_array(providers !== null && providers !== void 0 ? providers : []))
2389
- };
2390
- }
2391
-
2392
- exports.CALCOM_API_KEY_CONFIG_KEY = CALCOM_API_KEY_CONFIG_KEY;
2393
- exports.CALCOM_CLIENT_ID_CONFIG_KEY = CALCOM_CLIENT_ID_CONFIG_KEY;
2394
- exports.CALCOM_CLIENT_SECRET_CONFIG_KEY = CALCOM_CLIENT_SECRET_CONFIG_KEY;
2395
- exports.CALCOM_REFRESH_TOKEN_CONFIG_KEY = CALCOM_REFRESH_TOKEN_CONFIG_KEY;
2396
- exports.CALCOM_SERVER_TOKEN_FILE_KEY = CALCOM_SERVER_TOKEN_FILE_KEY;
2397
- exports.CALCOM_SERVICE_NAME = CALCOM_SERVICE_NAME;
2398
- exports.CALCOM_WEBHOOK_BOOKING_CANCELLED = CALCOM_WEBHOOK_BOOKING_CANCELLED;
2399
- exports.CALCOM_WEBHOOK_BOOKING_CREATED = CALCOM_WEBHOOK_BOOKING_CREATED;
2400
- exports.CALCOM_WEBHOOK_BOOKING_RESCHEDULED = CALCOM_WEBHOOK_BOOKING_RESCHEDULED;
2401
- exports.CALCOM_WEBHOOK_SECRET_CONFIG_KEY = CALCOM_WEBHOOK_SECRET_CONFIG_KEY;
2402
- exports.CalcomApiContextInstance = CalcomApiContextInstance;
2403
- exports.CalcomOAuthServiceConfig = CalcomOAuthServiceConfig;
2404
- exports.CalcomServiceConfig = CalcomServiceConfig;
2405
- exports.CalcomWebhookServiceConfig = CalcomWebhookServiceConfig;
2406
- exports.DEFAULT_FILE_CALCOM_ACCESS_TOKEN_CACHE_DIR = DEFAULT_FILE_CALCOM_ACCESS_TOKEN_CACHE_DIR;
2407
- exports.appCalcomModuleMetadata = appCalcomModuleMetadata;
2408
- exports.appCalcomOAuthModuleMetadata = appCalcomOAuthModuleMetadata;
2409
- exports.appCalcomWebhookModuleMetadata = appCalcomWebhookModuleMetadata;
2410
- exports.calcomAccessTokenCacheFileKey = calcomAccessTokenCacheFileKey;
2411
- exports.calcomEventHandlerConfigurerFactory = calcomEventHandlerConfigurerFactory;
2412
- exports.calcomEventHandlerFactory = calcomEventHandlerFactory;
2413
- exports.calcomOAuthServiceConfigFactory = calcomOAuthServiceConfigFactory;
2414
- exports.calcomRefreshTokenCacheKey = calcomRefreshTokenCacheKey;
2415
- exports.calcomServiceConfigFactory = calcomServiceConfigFactory;
2416
- exports.calcomWebhookEvent = calcomWebhookEvent;
2417
- exports.calcomWebhookEventVerifier = calcomWebhookEventVerifier;
2418
- exports.calcomWebhookServiceConfigFactory = calcomWebhookServiceConfigFactory;
2419
- exports.fileCalcomOAuthAccessTokenCacheService = fileCalcomOAuthAccessTokenCacheService;
2420
- exports.logMergeCalcomOAuthAccessTokenCacheServiceErrorFunction = logMergeCalcomOAuthAccessTokenCacheServiceErrorFunction;
2421
- exports.memoryCalcomOAuthAccessTokenCacheService = memoryCalcomOAuthAccessTokenCacheService;
2422
- exports.mergeCalcomOAuthAccessTokenCacheServices = mergeCalcomOAuthAccessTokenCacheServices;