@dereekb/calcom 13.37.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.
package/index.cjs.js DELETED
@@ -1,2870 +0,0 @@
1
- 'use strict';
2
-
3
- var fetch = require('@dereekb/util/fetch');
4
- var util = require('@dereekb/util');
5
- var makeError = require('make-error');
6
-
7
- function _assert_this_initialized$1(self) {
8
- if (self === void 0) {
9
- throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
10
- }
11
- return self;
12
- }
13
- function asyncGeneratorStep$6(gen, resolve, reject, _next, _throw, key, arg) {
14
- try {
15
- var info = gen[key](arg);
16
- var value = info.value;
17
- } catch (error) {
18
- reject(error);
19
- return;
20
- }
21
- if (info.done) {
22
- resolve(value);
23
- } else {
24
- Promise.resolve(value).then(_next, _throw);
25
- }
26
- }
27
- function _async_to_generator$6(fn) {
28
- return function() {
29
- var self = this, args = arguments;
30
- return new Promise(function(resolve, reject) {
31
- var gen = fn.apply(self, args);
32
- function _next(value) {
33
- asyncGeneratorStep$6(gen, resolve, reject, _next, _throw, "next", value);
34
- }
35
- function _throw(err) {
36
- asyncGeneratorStep$6(gen, resolve, reject, _next, _throw, "throw", err);
37
- }
38
- _next(undefined);
39
- });
40
- };
41
- }
42
- function _call_super$1(_this, derived, args) {
43
- derived = _get_prototype_of$1(derived);
44
- return _possible_constructor_return$1(_this, _is_native_reflect_construct$1() ? Reflect.construct(derived, args || [], _get_prototype_of$1(_this).constructor) : derived.apply(_this, args));
45
- }
46
- function _class_call_check$1(instance, Constructor) {
47
- if (!(instance instanceof Constructor)) {
48
- throw new TypeError("Cannot call a class as a function");
49
- }
50
- }
51
- function _defineProperties(target, props) {
52
- for(var i = 0; i < props.length; i++){
53
- var descriptor = props[i];
54
- descriptor.enumerable = descriptor.enumerable || false;
55
- descriptor.configurable = true;
56
- if ("value" in descriptor) descriptor.writable = true;
57
- Object.defineProperty(target, descriptor.key, descriptor);
58
- }
59
- }
60
- function _create_class(Constructor, protoProps, staticProps) {
61
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
62
- return Constructor;
63
- }
64
- function _define_property$3(obj, key, value) {
65
- if (key in obj) {
66
- Object.defineProperty(obj, key, {
67
- value: value,
68
- enumerable: true,
69
- configurable: true,
70
- writable: true
71
- });
72
- } else {
73
- obj[key] = value;
74
- }
75
- return obj;
76
- }
77
- function _get_prototype_of$1(o) {
78
- _get_prototype_of$1 = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
79
- return o.__proto__ || Object.getPrototypeOf(o);
80
- };
81
- return _get_prototype_of$1(o);
82
- }
83
- function _inherits$1(subClass, superClass) {
84
- if (typeof superClass !== "function" && superClass !== null) {
85
- throw new TypeError("Super expression must either be null or a function");
86
- }
87
- subClass.prototype = Object.create(superClass && superClass.prototype, {
88
- constructor: {
89
- value: subClass,
90
- writable: true,
91
- configurable: true
92
- }
93
- });
94
- if (superClass) _set_prototype_of$1(subClass, superClass);
95
- }
96
- function _instanceof(left, right) {
97
- "@swc/helpers - instanceof";
98
- if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
99
- return !!right[Symbol.hasInstance](left);
100
- } else {
101
- return left instanceof right;
102
- }
103
- }
104
- function _possible_constructor_return$1(self, call) {
105
- if (call && (_type_of$1(call) === "object" || typeof call === "function")) {
106
- return call;
107
- }
108
- return _assert_this_initialized$1(self);
109
- }
110
- function _set_prototype_of$1(o, p) {
111
- _set_prototype_of$1 = Object.setPrototypeOf || function setPrototypeOf(o, p) {
112
- o.__proto__ = p;
113
- return o;
114
- };
115
- return _set_prototype_of$1(o, p);
116
- }
117
- function _type_of$1(obj) {
118
- "@swc/helpers - typeof";
119
- return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
120
- }
121
- function _is_native_reflect_construct$1() {
122
- try {
123
- var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
124
- } catch (_) {}
125
- return (_is_native_reflect_construct$1 = function() {
126
- return !!result;
127
- })();
128
- }
129
- function _ts_generator$6(thisArg, body) {
130
- var f, y, t, _ = {
131
- label: 0,
132
- sent: function() {
133
- if (t[0] & 1) throw t[1];
134
- return t[1];
135
- },
136
- trys: [],
137
- ops: []
138
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
139
- return d(g, "next", {
140
- value: verb(0)
141
- }), d(g, "throw", {
142
- value: verb(1)
143
- }), d(g, "return", {
144
- value: verb(2)
145
- }), typeof Symbol === "function" && d(g, Symbol.iterator, {
146
- value: function() {
147
- return this;
148
- }
149
- }), g;
150
- function verb(n) {
151
- return function(v) {
152
- return step([
153
- n,
154
- v
155
- ]);
156
- };
157
- }
158
- function step(op) {
159
- if (f) throw new TypeError("Generator is already executing.");
160
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
161
- 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;
162
- if (y = 0, t) op = [
163
- op[0] & 2,
164
- t.value
165
- ];
166
- switch(op[0]){
167
- case 0:
168
- case 1:
169
- t = op;
170
- break;
171
- case 4:
172
- _.label++;
173
- return {
174
- value: op[1],
175
- done: false
176
- };
177
- case 5:
178
- _.label++;
179
- y = op[1];
180
- op = [
181
- 0
182
- ];
183
- continue;
184
- case 7:
185
- op = _.ops.pop();
186
- _.trys.pop();
187
- continue;
188
- default:
189
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
190
- _ = 0;
191
- continue;
192
- }
193
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
194
- _.label = op[1];
195
- break;
196
- }
197
- if (op[0] === 6 && _.label < t[1]) {
198
- _.label = t[1];
199
- t = op;
200
- break;
201
- }
202
- if (t && _.label < t[2]) {
203
- _.label = t[2];
204
- _.ops.push(op);
205
- break;
206
- }
207
- if (t[2]) _.ops.pop();
208
- _.trys.pop();
209
- continue;
210
- }
211
- op = body.call(thisArg, _);
212
- } catch (e) {
213
- op = [
214
- 6,
215
- e
216
- ];
217
- y = 0;
218
- } finally{
219
- f = t = 0;
220
- }
221
- if (op[0] & 5) throw op[1];
222
- return {
223
- value: op[0] ? op[1] : void 0,
224
- done: true
225
- };
226
- }
227
- }
228
- /**
229
- * Cal.com Server Error
230
- */ var CalcomServerError = /*#__PURE__*/ function(BaseError) {
231
- _inherits$1(CalcomServerError, BaseError);
232
- function CalcomServerError(error) {
233
- _class_call_check$1(this, CalcomServerError);
234
- var _this;
235
- _this = _call_super$1(this, CalcomServerError, [
236
- error.message
237
- ]), _define_property$3(_this, "error", void 0);
238
- _this.error = error;
239
- return _this;
240
- }
241
- _create_class(CalcomServerError, [
242
- {
243
- key: "code",
244
- get: function get() {
245
- return this.error.code;
246
- }
247
- }
248
- ]);
249
- return CalcomServerError;
250
- }(makeError.BaseError);
251
- /**
252
- * Cal.com Server Error that includes the FetchResponseError
253
- */ var CalcomServerFetchResponseError = /*#__PURE__*/ function(CalcomServerError) {
254
- _inherits$1(CalcomServerFetchResponseError, CalcomServerError);
255
- function CalcomServerFetchResponseError(data, responseError) {
256
- _class_call_check$1(this, CalcomServerFetchResponseError);
257
- var _this;
258
- _this = _call_super$1(this, CalcomServerFetchResponseError, [
259
- data
260
- ]), _define_property$3(_this, "data", void 0), _define_property$3(_this, "responseError", void 0);
261
- _this.data = data;
262
- _this.responseError = responseError;
263
- return _this;
264
- }
265
- return CalcomServerFetchResponseError;
266
- }(CalcomServerError);
267
- /**
268
- * Creates a logCalcomServerErrorFunction that logs the error to console.
269
- *
270
- * @param calcomApiNamePrefix - Prefix to use when logging. I.E. CalcomError, etc.
271
- * @returns A LogCalcomServerErrorFunction that logs errors with the given prefix.
272
- *
273
- * @__NO_SIDE_EFFECTS__
274
- */ function logCalcomServerErrorFunction(calcomApiNamePrefix) {
275
- return function(error) {
276
- if (_instanceof(error, CalcomServerFetchResponseError)) {
277
- console.log("".concat(calcomApiNamePrefix, "Error(").concat(error.responseError.response.status, "): "), {
278
- error: error,
279
- errorData: error.data
280
- });
281
- } else if (_instanceof(error, CalcomServerError)) {
282
- console.log("".concat(calcomApiNamePrefix, "Error(code:").concat(error.code, "): "), {
283
- error: error
284
- });
285
- } else {
286
- console.log("".concat(calcomApiNamePrefix, "Error(name:").concat(error.name, "): "), {
287
- error: error
288
- });
289
- }
290
- };
291
- }
292
- /**
293
- * Wraps a ConfiguredFetch to support handling errors returned by fetch.
294
- *
295
- * @param parseCalcomError - Function to parse a FetchResponseError into a CalcomServerError.
296
- * @param defaultLogError - Default error logging function used when no override is provided.
297
- * @returns A factory that wraps any ConfiguredFetch with Cal.com error handling.
298
- *
299
- * @__NO_SIDE_EFFECTS__
300
- */ function handleCalcomErrorFetchFactory(parseCalcomError, defaultLogError) {
301
- return function(fetch$1) {
302
- var logError = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : defaultLogError;
303
- return function(x, y) {
304
- return _async_to_generator$6(function() {
305
- var e, error;
306
- return _ts_generator$6(this, function(_state) {
307
- switch(_state.label){
308
- case 0:
309
- _state.trys.push([
310
- 0,
311
- 2,
312
- ,
313
- 5
314
- ]);
315
- return [
316
- 4,
317
- fetch$1(x, y)
318
- ];
319
- case 1:
320
- return [
321
- 2,
322
- _state.sent()
323
- ]; // await to catch thrown errors
324
- case 2:
325
- e = _state.sent();
326
- if (!_instanceof(e, fetch.FetchResponseError)) return [
327
- 3,
328
- 4
329
- ];
330
- return [
331
- 4,
332
- parseCalcomError(e)
333
- ];
334
- case 3:
335
- error = _state.sent();
336
- if (error) {
337
- logError(error); // log before throwing.
338
- throw error;
339
- }
340
- _state.label = 4;
341
- case 4:
342
- throw e;
343
- case 5:
344
- return [
345
- 2
346
- ];
347
- }
348
- });
349
- })();
350
- };
351
- };
352
- }
353
- // MARK: Parsed Errors
354
- /**
355
- * The status code that indicates too many requests have been made.
356
- */ var CALCOM_TOO_MANY_REQUESTS_HTTP_STATUS_CODE = 429;
357
- var CALCOM_RATE_LIMIT_LIMIT_HEADER = 'X-RateLimit-Limit';
358
- var CALCOM_RATE_LIMIT_REMAINING_HEADER = 'X-RateLimit-Remaining';
359
- var CALCOM_RATE_LIMIT_RESET_HEADER = 'X-RateLimit-Reset';
360
- var DEFAULT_CALCOM_API_RATE_LIMIT = 100;
361
- var DEFAULT_CALCOM_API_RATE_LIMIT_RESET_PERIOD = 60 * util.MS_IN_SECOND;
362
- /**
363
- * Extracts Cal.com rate limit information from HTTP response headers.
364
- *
365
- * @param headers - The HTTP response headers to parse.
366
- * @returns Parsed rate limit details, or null if no rate limit headers are present.
367
- */ function calcomRateLimitHeaderDetails(headers) {
368
- var limitHeader = headers.get(CALCOM_RATE_LIMIT_LIMIT_HEADER);
369
- var remainingHeader = headers.get(CALCOM_RATE_LIMIT_REMAINING_HEADER);
370
- var resetHeader = headers.get(CALCOM_RATE_LIMIT_RESET_HEADER);
371
- var result = null;
372
- if (limitHeader != null || remainingHeader != null || resetHeader != null) {
373
- var limit = limitHeader ? Number(limitHeader) : undefined;
374
- var remaining = remainingHeader ? Number(remainingHeader) : undefined;
375
- var resetAt = resetHeader ? new Date(Number(resetHeader) * util.MS_IN_SECOND) : undefined;
376
- result = {
377
- limit: limit,
378
- remaining: remaining,
379
- resetAt: resetAt
380
- };
381
- }
382
- return result;
383
- }
384
- var CalcomTooManyRequestsError = /*#__PURE__*/ function(CalcomServerFetchResponseError) {
385
- _inherits$1(CalcomTooManyRequestsError, CalcomServerFetchResponseError);
386
- function CalcomTooManyRequestsError() {
387
- _class_call_check$1(this, CalcomTooManyRequestsError);
388
- return _call_super$1(this, CalcomTooManyRequestsError, arguments);
389
- }
390
- _create_class(CalcomTooManyRequestsError, [
391
- {
392
- key: "headerDetails",
393
- get: function get() {
394
- return calcomRateLimitHeaderDetails(this.responseError.response.headers);
395
- }
396
- }
397
- ]);
398
- return CalcomTooManyRequestsError;
399
- }(CalcomServerFetchResponseError);
400
- /**
401
- * Function that parses/transforms a CalcomServerErrorData into a general CalcomServerError or other known error type.
402
- *
403
- * @param calcomServerError - The parsed error data from the Cal.com response body.
404
- * @param responseError - The original FetchResponseError containing the HTTP response.
405
- * @returns A CalcomServerFetchResponseError (or subclass like CalcomTooManyRequestsError), or undefined if unrecognized.
406
- */ function parseCalcomServerErrorData(calcomServerError, responseError) {
407
- var result;
408
- if (responseError.response.status === CALCOM_TOO_MANY_REQUESTS_HTTP_STATUS_CODE) {
409
- result = new CalcomTooManyRequestsError(calcomServerError, responseError);
410
- console.warn('CalcomTooManyRequestsError', {
411
- result: result,
412
- responseError: responseError,
413
- headerDetails: result.headerDetails
414
- });
415
- } else if (calcomServerError) {
416
- switch(calcomServerError.code){
417
- default:
418
- result = new CalcomServerFetchResponseError(calcomServerError, responseError);
419
- break;
420
- }
421
- }
422
- return result;
423
- }
424
-
425
- function asyncGeneratorStep$5(gen, resolve, reject, _next, _throw, key, arg) {
426
- try {
427
- var info = gen[key](arg);
428
- var value = info.value;
429
- } catch (error) {
430
- reject(error);
431
- return;
432
- }
433
- if (info.done) {
434
- resolve(value);
435
- } else {
436
- Promise.resolve(value).then(_next, _throw);
437
- }
438
- }
439
- function _async_to_generator$5(fn) {
440
- return function() {
441
- var self = this, args = arguments;
442
- return new Promise(function(resolve, reject) {
443
- var gen = fn.apply(self, args);
444
- function _next(value) {
445
- asyncGeneratorStep$5(gen, resolve, reject, _next, _throw, "next", value);
446
- }
447
- function _throw(err) {
448
- asyncGeneratorStep$5(gen, resolve, reject, _next, _throw, "throw", err);
449
- }
450
- _next(undefined);
451
- });
452
- };
453
- }
454
- function _ts_generator$5(thisArg, body) {
455
- var f, y, t, _ = {
456
- label: 0,
457
- sent: function() {
458
- if (t[0] & 1) throw t[1];
459
- return t[1];
460
- },
461
- trys: [],
462
- ops: []
463
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
464
- return d(g, "next", {
465
- value: verb(0)
466
- }), d(g, "throw", {
467
- value: verb(1)
468
- }), d(g, "return", {
469
- value: verb(2)
470
- }), typeof Symbol === "function" && d(g, Symbol.iterator, {
471
- value: function() {
472
- return this;
473
- }
474
- }), g;
475
- function verb(n) {
476
- return function(v) {
477
- return step([
478
- n,
479
- v
480
- ]);
481
- };
482
- }
483
- function step(op) {
484
- if (f) throw new TypeError("Generator is already executing.");
485
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
486
- 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;
487
- if (y = 0, t) op = [
488
- op[0] & 2,
489
- t.value
490
- ];
491
- switch(op[0]){
492
- case 0:
493
- case 1:
494
- t = op;
495
- break;
496
- case 4:
497
- _.label++;
498
- return {
499
- value: op[1],
500
- done: false
501
- };
502
- case 5:
503
- _.label++;
504
- y = op[1];
505
- op = [
506
- 0
507
- ];
508
- continue;
509
- case 7:
510
- op = _.ops.pop();
511
- _.trys.pop();
512
- continue;
513
- default:
514
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
515
- _ = 0;
516
- continue;
517
- }
518
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
519
- _.label = op[1];
520
- break;
521
- }
522
- if (op[0] === 6 && _.label < t[1]) {
523
- _.label = t[1];
524
- t = op;
525
- break;
526
- }
527
- if (t && _.label < t[2]) {
528
- _.label = t[2];
529
- _.ops.push(op);
530
- break;
531
- }
532
- if (t[2]) _.ops.pop();
533
- _.trys.pop();
534
- continue;
535
- }
536
- op = body.call(thisArg, _);
537
- } catch (e) {
538
- op = [
539
- 6,
540
- e
541
- ];
542
- y = 0;
543
- } finally{
544
- f = t = 0;
545
- }
546
- if (op[0] & 5) throw op[1];
547
- return {
548
- value: op[0] ? op[1] : void 0,
549
- done: true
550
- };
551
- }
552
- }
553
- // MARK: Parser
554
- var logCalcomErrorToConsole = logCalcomServerErrorFunction('Calcom');
555
- /**
556
- * Flattens a Cal.com API error response body into {@link CalcomServerErrorData}.
557
- *
558
- * Reads the nested `error` envelope when present, and otherwise treats the body as already
559
- * flat — so an endpoint that returns a bare error object still yields its code and message.
560
- *
561
- * @param body - The parsed error response body.
562
- * @returns The flattened error data.
563
- */ function calcomServerErrorDataFromApiErrorResponseBody(body) {
564
- var _ref, _ref1, _ref2;
565
- var error = body.error, status = body.status;
566
- var flatBody = body;
567
- return {
568
- code: (_ref = error === null || error === void 0 ? void 0 : error.code) !== null && _ref !== void 0 ? _ref : flatBody.code,
569
- message: (_ref1 = error === null || error === void 0 ? void 0 : error.message) !== null && _ref1 !== void 0 ? _ref1 : flatBody.message,
570
- details: (_ref2 = error === null || error === void 0 ? void 0 : error.details) !== null && _ref2 !== void 0 ? _ref2 : flatBody.details,
571
- status: status !== null && status !== void 0 ? status : undefined
572
- };
573
- }
574
- /**
575
- * Parses a FetchResponseError from a Cal.com API call into a typed CalcomServerError.
576
- * Attempts to extract JSON error data from the response body.
577
- *
578
- * @param responseError - The fetch response error to parse.
579
- * @returns A parsed CalcomServerError, or undefined if the response body cannot be parsed.
580
- */ function parseCalcomApiError(responseError) {
581
- return _async_to_generator$5(function() {
582
- var body, result;
583
- return _ts_generator$5(this, function(_state) {
584
- switch(_state.label){
585
- case 0:
586
- return [
587
- 4,
588
- responseError.response.json().catch(function(_x) {
589
- return undefined;
590
- })
591
- ];
592
- case 1:
593
- body = _state.sent();
594
- if (body) {
595
- result = parseCalcomApiServerErrorResponseData(calcomServerErrorDataFromApiErrorResponseBody(body), responseError);
596
- }
597
- return [
598
- 2,
599
- result
600
- ];
601
- }
602
- });
603
- })();
604
- }
605
- /**
606
- * Parses Cal.com API server error response data into a specific error type.
607
- * Delegates to {@link parseCalcomServerErrorData} for general error classification.
608
- *
609
- * @param calcomServerError - The parsed error data from the Cal.com response body.
610
- * @param responseError - The original FetchResponseError containing the HTTP response.
611
- * @returns A parsed CalcomServerError, or undefined if the error data is falsy.
612
- */ function parseCalcomApiServerErrorResponseData(calcomServerError, responseError) {
613
- var result;
614
- if (calcomServerError) {
615
- switch(calcomServerError.code){
616
- default:
617
- result = parseCalcomServerErrorData(calcomServerError, responseError);
618
- break;
619
- }
620
- }
621
- return result;
622
- }
623
- var handleCalcomErrorFetch = handleCalcomErrorFetchFactory(parseCalcomApiError, logCalcomErrorToConsole);
624
-
625
- function _assert_this_initialized(self) {
626
- if (self === void 0) {
627
- throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
628
- }
629
- return self;
630
- }
631
- function asyncGeneratorStep$4(gen, resolve, reject, _next, _throw, key, arg) {
632
- try {
633
- var info = gen[key](arg);
634
- var value = info.value;
635
- } catch (error) {
636
- reject(error);
637
- return;
638
- }
639
- if (info.done) {
640
- resolve(value);
641
- } else {
642
- Promise.resolve(value).then(_next, _throw);
643
- }
644
- }
645
- function _async_to_generator$4(fn) {
646
- return function() {
647
- var self = this, args = arguments;
648
- return new Promise(function(resolve, reject) {
649
- var gen = fn.apply(self, args);
650
- function _next(value) {
651
- asyncGeneratorStep$4(gen, resolve, reject, _next, _throw, "next", value);
652
- }
653
- function _throw(err) {
654
- asyncGeneratorStep$4(gen, resolve, reject, _next, _throw, "throw", err);
655
- }
656
- _next(undefined);
657
- });
658
- };
659
- }
660
- function _call_super(_this, derived, args) {
661
- derived = _get_prototype_of(derived);
662
- return _possible_constructor_return(_this, _is_native_reflect_construct() ? Reflect.construct(derived, args || [], _get_prototype_of(_this).constructor) : derived.apply(_this, args));
663
- }
664
- function _class_call_check(instance, Constructor) {
665
- if (!(instance instanceof Constructor)) {
666
- throw new TypeError("Cannot call a class as a function");
667
- }
668
- }
669
- function _define_property$2(obj, key, value) {
670
- if (key in obj) {
671
- Object.defineProperty(obj, key, {
672
- value: value,
673
- enumerable: true,
674
- configurable: true,
675
- writable: true
676
- });
677
- } else {
678
- obj[key] = value;
679
- }
680
- return obj;
681
- }
682
- function _get_prototype_of(o) {
683
- _get_prototype_of = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
684
- return o.__proto__ || Object.getPrototypeOf(o);
685
- };
686
- return _get_prototype_of(o);
687
- }
688
- function _inherits(subClass, superClass) {
689
- if (typeof superClass !== "function" && superClass !== null) {
690
- throw new TypeError("Super expression must either be null or a function");
691
- }
692
- subClass.prototype = Object.create(superClass && superClass.prototype, {
693
- constructor: {
694
- value: subClass,
695
- writable: true,
696
- configurable: true
697
- }
698
- });
699
- if (superClass) _set_prototype_of(subClass, superClass);
700
- }
701
- function _possible_constructor_return(self, call) {
702
- if (call && (_type_of(call) === "object" || typeof call === "function")) {
703
- return call;
704
- }
705
- return _assert_this_initialized(self);
706
- }
707
- function _set_prototype_of(o, p) {
708
- _set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o, p) {
709
- o.__proto__ = p;
710
- return o;
711
- };
712
- return _set_prototype_of(o, p);
713
- }
714
- function _type_of(obj) {
715
- "@swc/helpers - typeof";
716
- return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
717
- }
718
- function _is_native_reflect_construct() {
719
- try {
720
- var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
721
- } catch (_) {}
722
- return (_is_native_reflect_construct = function() {
723
- return !!result;
724
- })();
725
- }
726
- function _ts_generator$4(thisArg, body) {
727
- var f, y, t, _ = {
728
- label: 0,
729
- sent: function() {
730
- if (t[0] & 1) throw t[1];
731
- return t[1];
732
- },
733
- trys: [],
734
- ops: []
735
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
736
- return d(g, "next", {
737
- value: verb(0)
738
- }), d(g, "throw", {
739
- value: verb(1)
740
- }), d(g, "return", {
741
- value: verb(2)
742
- }), typeof Symbol === "function" && d(g, Symbol.iterator, {
743
- value: function() {
744
- return this;
745
- }
746
- }), g;
747
- function verb(n) {
748
- return function(v) {
749
- return step([
750
- n,
751
- v
752
- ]);
753
- };
754
- }
755
- function step(op) {
756
- if (f) throw new TypeError("Generator is already executing.");
757
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
758
- 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;
759
- if (y = 0, t) op = [
760
- op[0] & 2,
761
- t.value
762
- ];
763
- switch(op[0]){
764
- case 0:
765
- case 1:
766
- t = op;
767
- break;
768
- case 4:
769
- _.label++;
770
- return {
771
- value: op[1],
772
- done: false
773
- };
774
- case 5:
775
- _.label++;
776
- y = op[1];
777
- op = [
778
- 0
779
- ];
780
- continue;
781
- case 7:
782
- op = _.ops.pop();
783
- _.trys.pop();
784
- continue;
785
- default:
786
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
787
- _ = 0;
788
- continue;
789
- }
790
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
791
- _.label = op[1];
792
- break;
793
- }
794
- if (op[0] === 6 && _.label < t[1]) {
795
- _.label = t[1];
796
- t = op;
797
- break;
798
- }
799
- if (t && _.label < t[2]) {
800
- _.label = t[2];
801
- _.ops.push(op);
802
- break;
803
- }
804
- if (t[2]) _.ops.pop();
805
- _.trys.pop();
806
- continue;
807
- }
808
- op = body.call(thisArg, _);
809
- } catch (e) {
810
- op = [
811
- 6,
812
- e
813
- ];
814
- y = 0;
815
- } finally{
816
- f = t = 0;
817
- }
818
- if (op[0] & 5) throw op[1];
819
- return {
820
- value: op[0] ? op[1] : void 0,
821
- done: true
822
- };
823
- }
824
- }
825
- /**
826
- * Error in the following cases:
827
- * - the refresh token string is invalid
828
- */ var CALCOM_OAUTH_INVALID_GRANT_ERROR_CODE = 'invalid_grant';
829
- /**
830
- * Thrown if the call to the Cal.com API creating an access token using a refresh token fails.
831
- */ var CalcomOAuthAccessTokenError = /*#__PURE__*/ function(FetchRequestFactoryError) {
832
- _inherits(CalcomOAuthAccessTokenError, FetchRequestFactoryError);
833
- function CalcomOAuthAccessTokenError(errorCode) {
834
- _class_call_check(this, CalcomOAuthAccessTokenError);
835
- var _this;
836
- _this = _call_super(this, CalcomOAuthAccessTokenError, [
837
- "CalcomOAuthAccessTokenError: ".concat(errorCode)
838
- ]), _define_property$2(_this, "errorCode", void 0);
839
- _this.errorCode = errorCode;
840
- return _this;
841
- }
842
- return CalcomOAuthAccessTokenError;
843
- }(fetch.FetchRequestFactoryError);
844
- /**
845
- * Thrown if a valid CalcomAccessToken cannot be retrieved successfully.
846
- */ var CalcomOAuthAuthFailureError = /*#__PURE__*/ function(FetchRequestFactoryError) {
847
- _inherits(CalcomOAuthAuthFailureError, FetchRequestFactoryError);
848
- function CalcomOAuthAuthFailureError(reason) {
849
- _class_call_check(this, CalcomOAuthAuthFailureError);
850
- var _this;
851
- _this = _call_super(this, CalcomOAuthAuthFailureError, [
852
- "Failed to retrieve proper authentication for the API call. Reason: ".concat(reason)
853
- ]), _define_property$2(_this, "reason", void 0);
854
- _this.reason = reason;
855
- return _this;
856
- }
857
- return CalcomOAuthAuthFailureError;
858
- }(fetch.FetchRequestFactoryError);
859
- var logCalcomOAuthErrorToConsole = logCalcomServerErrorFunction('CalcomOAuth');
860
- /**
861
- * Parses a FetchResponseError from a Cal.com OAuth call into a typed error.
862
- * Attempts to extract JSON error data from the response body.
863
- *
864
- * @param responseError - The fetch response error to parse.
865
- * @returns A parsed CalcomServerError or CalcomOAuthAccessTokenError, or undefined if unparseable.
866
- */ function parseCalcomOAuthError(responseError) {
867
- return _async_to_generator$4(function() {
868
- var data, result;
869
- return _ts_generator$4(this, function(_state) {
870
- switch(_state.label){
871
- case 0:
872
- return [
873
- 4,
874
- responseError.response.json().catch(function(_x) {
875
- return undefined;
876
- })
877
- ];
878
- case 1:
879
- data = _state.sent();
880
- if (data) {
881
- result = parseCalcomOAuthServerErrorResponseData(data, responseError);
882
- }
883
- return [
884
- 2,
885
- result
886
- ];
887
- }
888
- });
889
- })();
890
- }
891
- /**
892
- * Parses Cal.com OAuth server error response data into a specific error type.
893
- * Handles known error codes like `invalid_grant` and delegates unknown errors
894
- * to {@link parseCalcomServerErrorData}.
895
- *
896
- * @param calcomServerError - The parsed error data from the Cal.com OAuth response body.
897
- * @param responseError - The original FetchResponseError containing the HTTP response.
898
- * @returns A parsed error instance, or undefined if the error data is falsy.
899
- */ function parseCalcomOAuthServerErrorResponseData(calcomServerError, responseError) {
900
- var result;
901
- if (calcomServerError) {
902
- var potentialErrorStringCode = calcomServerError.error;
903
- var errorCode = potentialErrorStringCode !== null && potentialErrorStringCode !== void 0 ? potentialErrorStringCode : calcomServerError.code;
904
- switch(errorCode){
905
- case CALCOM_OAUTH_INVALID_GRANT_ERROR_CODE:
906
- result = new CalcomOAuthAccessTokenError(errorCode);
907
- break;
908
- default:
909
- result = parseCalcomServerErrorData(calcomServerError, responseError);
910
- break;
911
- }
912
- }
913
- return result;
914
- }
915
- var handleCalcomOAuthErrorFetch = handleCalcomErrorFetchFactory(parseCalcomOAuthError, logCalcomOAuthErrorToConsole);
916
-
917
- function asyncGeneratorStep$3(gen, resolve, reject, _next, _throw, key, arg) {
918
- try {
919
- var info = gen[key](arg);
920
- var value = info.value;
921
- } catch (error) {
922
- reject(error);
923
- return;
924
- }
925
- if (info.done) {
926
- resolve(value);
927
- } else {
928
- Promise.resolve(value).then(_next, _throw);
929
- }
930
- }
931
- function _async_to_generator$3(fn) {
932
- return function() {
933
- var self = this, args = arguments;
934
- return new Promise(function(resolve, reject) {
935
- var gen = fn.apply(self, args);
936
- function _next(value) {
937
- asyncGeneratorStep$3(gen, resolve, reject, _next, _throw, "next", value);
938
- }
939
- function _throw(err) {
940
- asyncGeneratorStep$3(gen, resolve, reject, _next, _throw, "throw", err);
941
- }
942
- _next(undefined);
943
- });
944
- };
945
- }
946
- function _ts_generator$3(thisArg, body) {
947
- var f, y, t, _ = {
948
- label: 0,
949
- sent: function() {
950
- if (t[0] & 1) throw t[1];
951
- return t[1];
952
- },
953
- trys: [],
954
- ops: []
955
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
956
- return d(g, "next", {
957
- value: verb(0)
958
- }), d(g, "throw", {
959
- value: verb(1)
960
- }), d(g, "return", {
961
- value: verb(2)
962
- }), typeof Symbol === "function" && d(g, Symbol.iterator, {
963
- value: function() {
964
- return this;
965
- }
966
- }), g;
967
- function verb(n) {
968
- return function(v) {
969
- return step([
970
- n,
971
- v
972
- ]);
973
- };
974
- }
975
- function step(op) {
976
- if (f) throw new TypeError("Generator is already executing.");
977
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
978
- 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;
979
- if (y = 0, t) op = [
980
- op[0] & 2,
981
- t.value
982
- ];
983
- switch(op[0]){
984
- case 0:
985
- case 1:
986
- t = op;
987
- break;
988
- case 4:
989
- _.label++;
990
- return {
991
- value: op[1],
992
- done: false
993
- };
994
- case 5:
995
- _.label++;
996
- y = op[1];
997
- op = [
998
- 0
999
- ];
1000
- continue;
1001
- case 7:
1002
- op = _.ops.pop();
1003
- _.trys.pop();
1004
- continue;
1005
- default:
1006
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
1007
- _ = 0;
1008
- continue;
1009
- }
1010
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
1011
- _.label = op[1];
1012
- break;
1013
- }
1014
- if (op[0] === 6 && _.label < t[1]) {
1015
- _.label = t[1];
1016
- t = op;
1017
- break;
1018
- }
1019
- if (t && _.label < t[2]) {
1020
- _.label = t[2];
1021
- _.ops.push(op);
1022
- break;
1023
- }
1024
- if (t[2]) _.ops.pop();
1025
- _.trys.pop();
1026
- continue;
1027
- }
1028
- op = body.call(thisArg, _);
1029
- } catch (e) {
1030
- op = [
1031
- 6,
1032
- e
1033
- ];
1034
- y = 0;
1035
- } finally{
1036
- f = t = 0;
1037
- }
1038
- if (op[0] & 5) throw op[1];
1039
- return {
1040
- value: op[0] ? op[1] : void 0,
1041
- done: true
1042
- };
1043
- }
1044
- }
1045
- /**
1046
- * Generates a new CalcomAccessTokenStringFactory.
1047
- * Wraps a CalcomAccessTokenFactory to extract just the access token string,
1048
- * throwing a CalcomOAuthAuthFailureError if the token is missing.
1049
- *
1050
- * @param calcomAccessTokenFactory - The factory that produces CalcomAccessToken objects.
1051
- * @returns A factory function that returns the access token string.
1052
- *
1053
- * @__NO_SIDE_EFFECTS__
1054
- */ function calcomAccessTokenStringFactory(calcomAccessTokenFactory) {
1055
- return function() {
1056
- return _async_to_generator$3(function() {
1057
- var token;
1058
- return _ts_generator$3(this, function(_state) {
1059
- switch(_state.label){
1060
- case 0:
1061
- return [
1062
- 4,
1063
- calcomAccessTokenFactory()
1064
- ];
1065
- case 1:
1066
- token = _state.sent();
1067
- if (!(token === null || token === void 0 ? void 0 : token.accessToken)) {
1068
- throw new CalcomOAuthAuthFailureError();
1069
- }
1070
- return [
1071
- 2,
1072
- token.accessToken
1073
- ];
1074
- }
1075
- });
1076
- })();
1077
- };
1078
- }
1079
-
1080
- var DEFAULT_CALCOM_RATE_LIMITED_TOO_MANY_REQUESTS_LOG_FUNCTION = function DEFAULT_CALCOM_RATE_LIMITED_TOO_MANY_REQUESTS_LOG_FUNCTION(headers) {
1081
- console.warn("calcomRateLimitedFetchHandler(): Too many requests made. The limit is ".concat(headers.limit, " requests per reset period. ResetAt is set for ").concat(headers.resetAt, "."));
1082
- };
1083
- /**
1084
- * Creates a rate-limited fetch handler configured for Cal.com API rate limits.
1085
- * Automatically adjusts based on rate limit response headers and retries on 429 responses.
1086
- *
1087
- * @param config - Optional rate limiter configuration overrides.
1088
- * @returns A CalcomRateLimitedFetchHandler that enforces rate limiting.
1089
- */ function calcomRateLimitedFetchHandler(config) {
1090
- var _ref, _ref1, _ref2;
1091
- var onTooManyRequests = (config === null || config === void 0 ? void 0 : config.onTooManyRequests) === false ? undefined : (_ref = config === null || config === void 0 ? void 0 : config.onTooManyRequests) !== null && _ref !== void 0 ? _ref : DEFAULT_CALCOM_RATE_LIMITED_TOO_MANY_REQUESTS_LOG_FUNCTION;
1092
- var defaultLimit = (_ref1 = config === null || config === void 0 ? void 0 : config.maxRateLimit) !== null && _ref1 !== void 0 ? _ref1 : DEFAULT_CALCOM_API_RATE_LIMIT;
1093
- var defaultResetPeriod = (_ref2 = config === null || config === void 0 ? void 0 : config.resetPeriod) !== null && _ref2 !== void 0 ? _ref2 : DEFAULT_CALCOM_API_RATE_LIMIT_RESET_PERIOD;
1094
- function configForLimit(limit, resetAt) {
1095
- return {
1096
- limit: defaultLimit,
1097
- startLimitAt: 10,
1098
- cooldownRate: 1.2,
1099
- exponentRate: 1.08,
1100
- maxWaitTime: util.MS_IN_SECOND * 10,
1101
- resetPeriod: defaultResetPeriod,
1102
- resetAt: resetAt
1103
- };
1104
- }
1105
- var defaultConfig = configForLimit();
1106
- var rateLimiter = util.resetPeriodPromiseRateLimiter(defaultConfig);
1107
- return fetch.rateLimitedFetchHandler({
1108
- rateLimiter: rateLimiter,
1109
- updateWithResponse: function updateWithResponse(response, fetchResponseError) {
1110
- var hasRemainingHeader = response.headers.has(CALCOM_RATE_LIMIT_REMAINING_HEADER);
1111
- var shouldRetry = false;
1112
- if (hasRemainingHeader) {
1113
- var headerDetails = calcomRateLimitHeaderDetails(response.headers);
1114
- if (headerDetails) {
1115
- var limit = headerDetails.limit, remaining = headerDetails.remaining, resetAt = headerDetails.resetAt;
1116
- if (response.status === CALCOM_TOO_MANY_REQUESTS_HTTP_STATUS_CODE) {
1117
- shouldRetry = true;
1118
- try {
1119
- void (onTooManyRequests === null || onTooManyRequests === void 0 ? void 0 : onTooManyRequests(headerDetails, response, fetchResponseError));
1120
- } catch (unused) {
1121
- // ignore logging errors
1122
- }
1123
- }
1124
- if (limit != null && resetAt != null && remaining != null) {
1125
- if (limit !== defaultLimit) {
1126
- var newConfig = configForLimit(limit, resetAt);
1127
- rateLimiter.setConfig(newConfig, false);
1128
- }
1129
- rateLimiter.setRemainingLimit(remaining);
1130
- rateLimiter.setNextResetAt(resetAt);
1131
- }
1132
- }
1133
- } else if (response.status === CALCOM_TOO_MANY_REQUESTS_HTTP_STATUS_CODE) {
1134
- shouldRetry = true;
1135
- try {
1136
- var headerDetails1 = {};
1137
- void (onTooManyRequests === null || onTooManyRequests === void 0 ? void 0 : onTooManyRequests(headerDetails1, response, fetchResponseError));
1138
- } catch (unused) {
1139
- // ignore logging errors
1140
- }
1141
- }
1142
- return shouldRetry;
1143
- }
1144
- });
1145
- }
1146
-
1147
- /**
1148
- * The Cal.com API URL.
1149
- */ var CALCOM_API_URL = 'https://api.cal.com/v2';
1150
-
1151
- function asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, key, arg) {
1152
- try {
1153
- var info = gen[key](arg);
1154
- var value = info.value;
1155
- } catch (error) {
1156
- reject(error);
1157
- return;
1158
- }
1159
- if (info.done) {
1160
- resolve(value);
1161
- } else {
1162
- Promise.resolve(value).then(_next, _throw);
1163
- }
1164
- }
1165
- function _async_to_generator$2(fn) {
1166
- return function() {
1167
- var self = this, args = arguments;
1168
- return new Promise(function(resolve, reject) {
1169
- var gen = fn.apply(self, args);
1170
- function _next(value) {
1171
- asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, "next", value);
1172
- }
1173
- function _throw(err) {
1174
- asyncGeneratorStep$2(gen, resolve, reject, _next, _throw, "throw", err);
1175
- }
1176
- _next(undefined);
1177
- });
1178
- };
1179
- }
1180
- function _ts_generator$2(thisArg, body) {
1181
- var f, y, t, _ = {
1182
- label: 0,
1183
- sent: function() {
1184
- if (t[0] & 1) throw t[1];
1185
- return t[1];
1186
- },
1187
- trys: [],
1188
- ops: []
1189
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
1190
- return d(g, "next", {
1191
- value: verb(0)
1192
- }), d(g, "throw", {
1193
- value: verb(1)
1194
- }), d(g, "return", {
1195
- value: verb(2)
1196
- }), typeof Symbol === "function" && d(g, Symbol.iterator, {
1197
- value: function() {
1198
- return this;
1199
- }
1200
- }), g;
1201
- function verb(n) {
1202
- return function(v) {
1203
- return step([
1204
- n,
1205
- v
1206
- ]);
1207
- };
1208
- }
1209
- function step(op) {
1210
- if (f) throw new TypeError("Generator is already executing.");
1211
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
1212
- 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;
1213
- if (y = 0, t) op = [
1214
- op[0] & 2,
1215
- t.value
1216
- ];
1217
- switch(op[0]){
1218
- case 0:
1219
- case 1:
1220
- t = op;
1221
- break;
1222
- case 4:
1223
- _.label++;
1224
- return {
1225
- value: op[1],
1226
- done: false
1227
- };
1228
- case 5:
1229
- _.label++;
1230
- y = op[1];
1231
- op = [
1232
- 0
1233
- ];
1234
- continue;
1235
- case 7:
1236
- op = _.ops.pop();
1237
- _.trys.pop();
1238
- continue;
1239
- default:
1240
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
1241
- _ = 0;
1242
- continue;
1243
- }
1244
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
1245
- _.label = op[1];
1246
- break;
1247
- }
1248
- if (op[0] === 6 && _.label < t[1]) {
1249
- _.label = t[1];
1250
- t = op;
1251
- break;
1252
- }
1253
- if (t && _.label < t[2]) {
1254
- _.label = t[2];
1255
- _.ops.push(op);
1256
- break;
1257
- }
1258
- if (t[2]) _.ops.pop();
1259
- _.trys.pop();
1260
- continue;
1261
- }
1262
- op = body.call(thisArg, _);
1263
- } catch (e) {
1264
- op = [
1265
- 6,
1266
- e
1267
- ];
1268
- y = 0;
1269
- } finally{
1270
- f = t = 0;
1271
- }
1272
- if (op[0] & 5) throw op[1];
1273
- return {
1274
- value: op[0] ? op[1] : void 0,
1275
- done: true
1276
- };
1277
- }
1278
- }
1279
- /**
1280
- * Creates a {@link CalcomFactory} that produces fully configured Cal.com API instances.
1281
- * Sets up rate limiting, error handling, OAuth token management, and both server
1282
- * and per-user fetch contexts.
1283
- *
1284
- * @param factoryConfig - Configuration including OAuth context, rate limiter, and optional fetch/logging overrides.
1285
- * @returns A factory function that accepts a CalcomConfig and produces a Calcom instance.
1286
- *
1287
- * @__NO_SIDE_EFFECTS__
1288
- */ function calcomFactory(factoryConfig) {
1289
- var oauthContext = factoryConfig.oauthContext;
1290
- var serverAccessTokenStringFactory = calcomAccessTokenStringFactory(oauthContext.loadAccessToken);
1291
- var fetchHandler = calcomRateLimitedFetchHandler(factoryConfig.rateLimiterConfig);
1292
- var logCalcomServerErrorFunction = factoryConfig.logCalcomServerErrorFunction, _factoryConfig_fetchFactory = factoryConfig.fetchFactory, fetchFactory = _factoryConfig_fetchFactory === void 0 ? function(input) {
1293
- return fetch.fetchApiFetchService.makeFetch({
1294
- baseUrl: CALCOM_API_URL,
1295
- baseRequest: function baseRequest() {
1296
- return _async_to_generator$2(function() {
1297
- var _tmp, _tmp1, _, _1;
1298
- return _ts_generator$2(this, function(_state) {
1299
- switch(_state.label){
1300
- case 0:
1301
- _tmp = {};
1302
- _tmp1 = {
1303
- 'Content-Type': 'application/json'
1304
- };
1305
- _1 = (_ = "Bearer ").concat;
1306
- return [
1307
- 4,
1308
- input.calcomAccessTokenStringFactory()
1309
- ];
1310
- case 1:
1311
- return [
1312
- 2,
1313
- (_tmp.headers = (_tmp1.Authorization = _1.apply(_, [
1314
- _state.sent()
1315
- ]), _tmp1), _tmp)
1316
- ];
1317
- }
1318
- });
1319
- })();
1320
- },
1321
- fetchHandler: fetchHandler,
1322
- timeout: 20 * 1000,
1323
- requireOkResponse: true,
1324
- useTimeout: true // use timeout
1325
- });
1326
- } : _factoryConfig_fetchFactory;
1327
- return function(config) {
1328
- var baseFetch = fetchFactory({
1329
- calcomAccessTokenStringFactory: serverAccessTokenStringFactory
1330
- });
1331
- var serverFetch = handleCalcomErrorFetch(baseFetch, logCalcomServerErrorFunction);
1332
- var serverFetchJson = fetch.fetchJsonFunction(serverFetch, {
1333
- handleFetchJsonParseErrorFunction: fetch.returnNullHandleFetchJsonParseErrorFunction
1334
- });
1335
- // MARK: Make Public Context
1336
- var makePublicContext = function makePublicContext() {
1337
- var publicFetch = fetch.fetchApiFetchService.makeFetch({
1338
- baseUrl: CALCOM_API_URL,
1339
- baseRequest: {
1340
- headers: {
1341
- 'Content-Type': 'application/json'
1342
- }
1343
- },
1344
- fetchHandler: fetchHandler,
1345
- timeout: 20 * 1000,
1346
- requireOkResponse: true,
1347
- useTimeout: true
1348
- });
1349
- var publicHandledFetch = handleCalcomErrorFetch(publicFetch, logCalcomServerErrorFunction);
1350
- var publicFetchJson = fetch.fetchJsonFunction(publicHandledFetch, {
1351
- handleFetchJsonParseErrorFunction: fetch.returnNullHandleFetchJsonParseErrorFunction
1352
- });
1353
- return {
1354
- fetch: publicHandledFetch,
1355
- fetchJson: publicFetchJson
1356
- };
1357
- };
1358
- // MARK: Make User Context
1359
- var makeUserContext = function makeUserContext(input) {
1360
- var userAccessTokenFactory = oauthContext.makeAccessTokenFactory(input);
1361
- var userAccessTokenStringFactory = calcomAccessTokenStringFactory(userAccessTokenFactory);
1362
- var userBaseFetch = fetchFactory({
1363
- calcomAccessTokenStringFactory: userAccessTokenStringFactory
1364
- });
1365
- var userFetch = handleCalcomErrorFetch(userBaseFetch, logCalcomServerErrorFunction);
1366
- var userFetchJson = fetch.fetchJsonFunction(userFetch, {
1367
- handleFetchJsonParseErrorFunction: fetch.returnNullHandleFetchJsonParseErrorFunction
1368
- });
1369
- var result = {
1370
- calcomServerContext: calcomContext,
1371
- type: 'user',
1372
- fetch: userFetch,
1373
- fetchJson: userFetchJson,
1374
- userFetch: userFetch,
1375
- userFetchJson: userFetchJson,
1376
- calcomRateLimiter: fetchHandler._rateLimiter
1377
- };
1378
- return result;
1379
- };
1380
- var calcomContext = {
1381
- type: 'server',
1382
- fetch: serverFetch,
1383
- fetchJson: serverFetchJson,
1384
- serverFetch: serverFetch,
1385
- serverFetchJson: serverFetchJson,
1386
- makeUserContext: makeUserContext,
1387
- makePublicContext: makePublicContext,
1388
- config: config,
1389
- calcomRateLimiter: fetchHandler._rateLimiter
1390
- };
1391
- var calcom = {
1392
- calcomServerContext: calcomContext
1393
- };
1394
- return calcom;
1395
- };
1396
- }
1397
-
1398
- function _define_property$1(obj, key, value) {
1399
- if (key in obj) {
1400
- Object.defineProperty(obj, key, {
1401
- value: value,
1402
- enumerable: true,
1403
- configurable: true,
1404
- writable: true
1405
- });
1406
- } else {
1407
- obj[key] = value;
1408
- }
1409
- return obj;
1410
- }
1411
- /**
1412
- * Cal.com API version header constants.
1413
- *
1414
- * Each endpoint group requires a specific cal-api-version header value.
1415
- */ var CALCOM_API_VERSION_SCHEDULES = '2024-06-11';
1416
- var CALCOM_API_VERSION_SLOTS = '2024-09-04';
1417
- var CALCOM_API_VERSION_BOOKINGS = '2024-08-13';
1418
- var CALCOM_API_VERSION_EVENT_TYPES = '2024-06-14';
1419
- var CALCOM_API_VERSION_CALENDARS = '2024-06-11';
1420
- var CALCOM_API_VERSION_ME = '2024-08-13';
1421
- var CALCOM_API_VERSION_HEADER = 'cal-api-version';
1422
- /**
1423
- * Returns a headers object with the cal-api-version header set.
1424
- *
1425
- * @param version - The Cal.com API version string to include in the header.
1426
- * @returns A headers record containing the cal-api-version header.
1427
- */ function calcomApiVersionHeaders(version) {
1428
- return _define_property$1({}, CALCOM_API_VERSION_HEADER, version);
1429
- }
1430
-
1431
- /**
1432
- * Retrieves the profile of the currently authenticated Cal.com user.
1433
- *
1434
- * @param context - The Cal.com API context providing authentication and fetch capabilities.
1435
- * @returns Retrieves the authenticated user's profile.
1436
- *
1437
- * @see https://cal.com/docs/api-reference/v2/me
1438
- *
1439
- * @example
1440
- * ```ts
1441
- * const response = await getMe(context)();
1442
- * console.log(response.data.email);
1443
- * ```
1444
- */ function getMe(context) {
1445
- return function() {
1446
- return context.fetchJson('/me', {
1447
- method: 'GET',
1448
- headers: calcomApiVersionHeaders(CALCOM_API_VERSION_ME)
1449
- });
1450
- };
1451
- }
1452
-
1453
- /**
1454
- * Retrieves all schedules for the authenticated user, including availability rules and overrides.
1455
- *
1456
- * @param context - The Cal.com API context providing authentication and fetch capabilities.
1457
- * @returns Retrieves all schedules.
1458
- *
1459
- * @see https://cal.com/docs/api-reference/v2/schedules/get-all-schedules
1460
- *
1461
- * @example
1462
- * ```ts
1463
- * const response = await getSchedules(context)();
1464
- * response.data.forEach(schedule => console.log(schedule.name, schedule.timeZone));
1465
- * ```
1466
- */ function getSchedules(context) {
1467
- return function() {
1468
- return context.fetchJson('/schedules', {
1469
- method: 'GET',
1470
- headers: calcomApiVersionHeaders(CALCOM_API_VERSION_SCHEDULES)
1471
- });
1472
- };
1473
- }
1474
-
1475
- /**
1476
- * Queries available booking slots for a given event type within a date range.
1477
- * This endpoint is public and does not require authentication.
1478
- *
1479
- * Identify the event type by `eventTypeId`, or by `eventTypeSlug` + `username`/`teamSlug`.
1480
- *
1481
- * @param context - The Cal.com API context (authenticated or public)
1482
- * @returns Queries available slots for the given input.
1483
- *
1484
- * The `cal-api-version` header is REQUIRED here — without it the endpoint 404s.
1485
- *
1486
- * @see https://cal.com/docs/api-reference/v2/slots/get-available-time-slots-for-an-event-type
1487
- *
1488
- * @example
1489
- * ```ts
1490
- * const response = await getAvailableSlots(context)({
1491
- * start: '2026-03-17T00:00:00.000Z',
1492
- * end: '2026-03-24T00:00:00.000Z',
1493
- * eventTypeId: 12345
1494
- * });
1495
- *
1496
- * for (const [date, slots] of Object.entries(response.data)) {
1497
- * console.log(date, slots.map(s => s.start));
1498
- * }
1499
- * ```
1500
- */ function getAvailableSlots(context) {
1501
- return function(input) {
1502
- var params = fetch.makeUrlSearchParams(input);
1503
- return context.fetchJson("/slots?".concat(params), {
1504
- method: 'GET',
1505
- headers: calcomApiVersionHeaders(CALCOM_API_VERSION_SLOTS)
1506
- });
1507
- };
1508
- }
1509
-
1510
- /**
1511
- * Creates a new booking for the specified event type. The `attendee` represents the person
1512
- * booking (the client), not the host. This endpoint can be called without authentication.
1513
- *
1514
- * @param context - The Cal.com API context providing authentication and fetch capabilities.
1515
- * @returns Creates a booking from the given input.
1516
- *
1517
- * @see https://cal.com/docs/api-reference/v2/bookings/create-a-booking
1518
- *
1519
- * @example
1520
- * ```ts
1521
- * const response = await createBooking(context)({
1522
- * start: '2026-03-20T14:00:00.000Z',
1523
- * eventTypeId: 12345,
1524
- * attendee: { name: 'Jane Doe', email: 'jane@example.com', timeZone: 'America/New_York' }
1525
- * });
1526
- * console.log(response.data.uid);
1527
- * ```
1528
- *
1529
- * @__NO_SIDE_EFFECTS__
1530
- */ function createBooking(context) {
1531
- return function(input) {
1532
- return context.fetchJson('/bookings', {
1533
- method: 'POST',
1534
- headers: calcomApiVersionHeaders(CALCOM_API_VERSION_BOOKINGS),
1535
- body: JSON.stringify(input)
1536
- });
1537
- };
1538
- }
1539
- /**
1540
- * Retrieves the bookings visible to the authenticated user, newest page first.
1541
- *
1542
- * Paginated: read {@link CalcomGetBookingsResponse.pagination} rather than assuming `data` holds
1543
- * everything, as the endpoint caps a page even with no `take`.
1544
- *
1545
- * @param context - The Cal.com API context providing authentication and fetch capabilities.
1546
- * @returns Retrieves a page of bookings for the given input.
1547
- *
1548
- * @see https://cal.com/docs/api-reference/v2/bookings/get-all-bookings
1549
- *
1550
- * @example
1551
- * ```ts
1552
- * const response = await getBookings(context)({ take: 10, status: 'upcoming', sortStart: 'asc' });
1553
- * console.log(response.pagination.totalItems, response.data.map(b => b.uid));
1554
- * ```
1555
- */ function getBookings(context) {
1556
- return function(input) {
1557
- var params = fetch.makeUrlSearchParams(input);
1558
- return context.fetchJson("/bookings?".concat(params), {
1559
- method: 'GET',
1560
- headers: calcomApiVersionHeaders(CALCOM_API_VERSION_BOOKINGS)
1561
- });
1562
- };
1563
- }
1564
- /**
1565
- * Retrieves a booking by its unique UID.
1566
- *
1567
- * @param context - The Cal.com API context providing authentication and fetch capabilities.
1568
- * @returns Retrieves a booking by its UID.
1569
- *
1570
- * @see https://cal.com/docs/api-reference/v2/bookings/get-a-booking
1571
- *
1572
- * @example
1573
- * ```ts
1574
- * const response = await getBooking(context)('abc-123-uid');
1575
- * console.log(response.data.title, response.data.status);
1576
- * ```
1577
- */ function getBooking(context) {
1578
- return function(uid) {
1579
- return context.fetchJson("/bookings/".concat(uid), {
1580
- method: 'GET',
1581
- headers: calcomApiVersionHeaders(CALCOM_API_VERSION_BOOKINGS)
1582
- });
1583
- };
1584
- }
1585
- /**
1586
- * Cancels a booking by its unique UID, with an optional cancellation reason.
1587
- *
1588
- * @param context - The Cal.com API context providing authentication and fetch capabilities.
1589
- * @returns Cancels a booking by UID.
1590
- *
1591
- * @see https://cal.com/docs/api-reference/v2/bookings/cancel-a-booking
1592
- *
1593
- * @example
1594
- * ```ts
1595
- * await cancelBooking(context)({ uid: 'abc-123-uid', cancellationReason: 'Schedule conflict' });
1596
- * ```
1597
- */ function cancelBooking(context) {
1598
- return function(input) {
1599
- var body = {};
1600
- if (input.cancellationReason) {
1601
- body['cancellationReason'] = input.cancellationReason;
1602
- }
1603
- return context.fetchJson("/bookings/".concat(input.uid, "/cancel"), {
1604
- method: 'POST',
1605
- headers: calcomApiVersionHeaders(CALCOM_API_VERSION_BOOKINGS),
1606
- body: JSON.stringify(body)
1607
- });
1608
- };
1609
- }
1610
-
1611
- /**
1612
- * Retrieves all event types for the authenticated user.
1613
- *
1614
- * @param context - The Cal.com API context providing authentication and fetch capabilities.
1615
- * @returns Retrieves all event types.
1616
- *
1617
- * @see https://cal.com/docs/api-reference/v2/event-types/get-all-event-types
1618
- *
1619
- * @example
1620
- * ```ts
1621
- * const response = await getEventTypes(context)();
1622
- * response.data.forEach(et => console.log(et.title, et.slug, et.lengthInMinutes));
1623
- * ```
1624
- */ function getEventTypes(context) {
1625
- return function() {
1626
- return context.fetchJson('/event-types', {
1627
- method: 'GET',
1628
- headers: calcomApiVersionHeaders(CALCOM_API_VERSION_EVENT_TYPES)
1629
- });
1630
- };
1631
- }
1632
- /**
1633
- * Creates a new event type for the authenticated user.
1634
- *
1635
- * @param context - The Cal.com API context providing authentication and fetch capabilities.
1636
- * @returns Creates a new event type from the given input.
1637
- *
1638
- * @see https://cal.com/docs/api-reference/v2/event-types/create-an-event-type
1639
- *
1640
- * @example
1641
- * ```ts
1642
- * const response = await createEventType(context)({
1643
- * title: 'Mentoring Session',
1644
- * slug: 'mentoring-session',
1645
- * lengthInMinutes: 30
1646
- * });
1647
- * console.log(response.data.id);
1648
- * ```
1649
- *
1650
- * @__NO_SIDE_EFFECTS__
1651
- */ function createEventType(context) {
1652
- return function(input) {
1653
- return context.fetchJson('/event-types', {
1654
- method: 'POST',
1655
- headers: calcomApiVersionHeaders(CALCOM_API_VERSION_EVENT_TYPES),
1656
- body: JSON.stringify(input)
1657
- });
1658
- };
1659
- }
1660
- /**
1661
- * Updates an existing event type by ID.
1662
- *
1663
- * @param context - The Cal.com API context providing authentication and fetch capabilities.
1664
- * @returns Updates an event type by ID.
1665
- *
1666
- * @see https://cal.com/docs/api-reference/v2/event-types/update-an-event-type
1667
- *
1668
- * @example
1669
- * ```ts
1670
- * await updateEventType(context)(12345, { title: 'Updated Session Title' });
1671
- * ```
1672
- */ function updateEventType(context) {
1673
- return function(eventTypeId, input) {
1674
- return context.fetchJson("/event-types/".concat(eventTypeId), {
1675
- method: 'PATCH',
1676
- headers: calcomApiVersionHeaders(CALCOM_API_VERSION_EVENT_TYPES),
1677
- body: JSON.stringify(input)
1678
- });
1679
- };
1680
- }
1681
- /**
1682
- * Deletes an event type by ID.
1683
- *
1684
- * @param context - The Cal.com API context providing authentication and fetch capabilities.
1685
- * @returns Deletes an event type by ID.
1686
- *
1687
- * @see https://cal.com/docs/api-reference/v2/event-types/delete-an-event-type
1688
- *
1689
- * @example
1690
- * ```ts
1691
- * await deleteEventType(context)(12345);
1692
- * ```
1693
- */ function deleteEventType(context) {
1694
- return function(eventTypeId) {
1695
- return context.fetchJson("/event-types/".concat(eventTypeId), {
1696
- method: 'DELETE',
1697
- headers: calcomApiVersionHeaders(CALCOM_API_VERSION_EVENT_TYPES)
1698
- });
1699
- };
1700
- }
1701
-
1702
- function asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, key, arg) {
1703
- try {
1704
- var info = gen[key](arg);
1705
- var value = info.value;
1706
- } catch (error) {
1707
- reject(error);
1708
- return;
1709
- }
1710
- if (info.done) {
1711
- resolve(value);
1712
- } else {
1713
- Promise.resolve(value).then(_next, _throw);
1714
- }
1715
- }
1716
- function _async_to_generator$1(fn) {
1717
- return function() {
1718
- var self = this, args = arguments;
1719
- return new Promise(function(resolve, reject) {
1720
- var gen = fn.apply(self, args);
1721
- function _next(value) {
1722
- asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, "next", value);
1723
- }
1724
- function _throw(err) {
1725
- asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, "throw", err);
1726
- }
1727
- _next(undefined);
1728
- });
1729
- };
1730
- }
1731
- function _define_property(obj, key, value) {
1732
- if (key in obj) {
1733
- Object.defineProperty(obj, key, {
1734
- value: value,
1735
- enumerable: true,
1736
- configurable: true,
1737
- writable: true
1738
- });
1739
- } else {
1740
- obj[key] = value;
1741
- }
1742
- return obj;
1743
- }
1744
- function _object_spread(target) {
1745
- for(var i = 1; i < arguments.length; i++){
1746
- var source = arguments[i] != null ? arguments[i] : {};
1747
- var ownKeys = Object.keys(source);
1748
- if (typeof Object.getOwnPropertySymbols === "function") {
1749
- ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
1750
- return Object.getOwnPropertyDescriptor(source, sym).enumerable;
1751
- }));
1752
- }
1753
- ownKeys.forEach(function(key) {
1754
- _define_property(target, key, source[key]);
1755
- });
1756
- }
1757
- return target;
1758
- }
1759
- function ownKeys(object, enumerableOnly) {
1760
- var keys = Object.keys(object);
1761
- if (Object.getOwnPropertySymbols) {
1762
- var symbols = Object.getOwnPropertySymbols(object);
1763
- keys.push.apply(keys, symbols);
1764
- }
1765
- return keys;
1766
- }
1767
- function _object_spread_props(target, source) {
1768
- source = source != null ? source : {};
1769
- if (Object.getOwnPropertyDescriptors) {
1770
- Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
1771
- } else {
1772
- ownKeys(Object(source)).forEach(function(key) {
1773
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
1774
- });
1775
- }
1776
- return target;
1777
- }
1778
- function _ts_generator$1(thisArg, body) {
1779
- var f, y, t, _ = {
1780
- label: 0,
1781
- sent: function() {
1782
- if (t[0] & 1) throw t[1];
1783
- return t[1];
1784
- },
1785
- trys: [],
1786
- ops: []
1787
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
1788
- return d(g, "next", {
1789
- value: verb(0)
1790
- }), d(g, "throw", {
1791
- value: verb(1)
1792
- }), d(g, "return", {
1793
- value: verb(2)
1794
- }), typeof Symbol === "function" && d(g, Symbol.iterator, {
1795
- value: function() {
1796
- return this;
1797
- }
1798
- }), g;
1799
- function verb(n) {
1800
- return function(v) {
1801
- return step([
1802
- n,
1803
- v
1804
- ]);
1805
- };
1806
- }
1807
- function step(op) {
1808
- if (f) throw new TypeError("Generator is already executing.");
1809
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
1810
- 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;
1811
- if (y = 0, t) op = [
1812
- op[0] & 2,
1813
- t.value
1814
- ];
1815
- switch(op[0]){
1816
- case 0:
1817
- case 1:
1818
- t = op;
1819
- break;
1820
- case 4:
1821
- _.label++;
1822
- return {
1823
- value: op[1],
1824
- done: false
1825
- };
1826
- case 5:
1827
- _.label++;
1828
- y = op[1];
1829
- op = [
1830
- 0
1831
- ];
1832
- continue;
1833
- case 7:
1834
- op = _.ops.pop();
1835
- _.trys.pop();
1836
- continue;
1837
- default:
1838
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
1839
- _ = 0;
1840
- continue;
1841
- }
1842
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
1843
- _.label = op[1];
1844
- break;
1845
- }
1846
- if (op[0] === 6 && _.label < t[1]) {
1847
- _.label = t[1];
1848
- t = op;
1849
- break;
1850
- }
1851
- if (t && _.label < t[2]) {
1852
- _.label = t[2];
1853
- _.ops.push(op);
1854
- break;
1855
- }
1856
- if (t[2]) _.ops.pop();
1857
- _.trys.pop();
1858
- continue;
1859
- }
1860
- op = body.call(thisArg, _);
1861
- } catch (e) {
1862
- op = [
1863
- 6,
1864
- e
1865
- ];
1866
- y = 0;
1867
- } finally{
1868
- f = t = 0;
1869
- }
1870
- if (op[0] & 5) throw op[1];
1871
- return {
1872
- value: op[0] ? op[1] : void 0,
1873
- done: true
1874
- };
1875
- }
1876
- }
1877
- /**
1878
- * Retrieves all connected calendars and the destination calendar for the authenticated user.
1879
- *
1880
- * @param context - The Cal.com API context providing authentication and fetch capabilities.
1881
- * @returns Retrieves all connected calendars.
1882
- *
1883
- * @see https://cal.com/docs/api-reference/v2/calendars/get-all-calendars
1884
- *
1885
- * @example
1886
- * ```ts
1887
- * const response = await getCalendars(context)();
1888
- * response.data.connectedCalendars.forEach(cc => console.log(cc.integration.slug, cc.calendars.length));
1889
- * ```
1890
- */ function getCalendars(context) {
1891
- return function() {
1892
- return context.fetchJson('/calendars', {
1893
- method: 'GET',
1894
- headers: calcomApiVersionHeaders(CALCOM_API_VERSION_CALENDARS)
1895
- });
1896
- };
1897
- }
1898
- /**
1899
- * Selects the calendars to load busy times from, out of a set of connected calendars.
1900
- *
1901
- * Prefers the calendars Cal.com is configured to check for conflicts (`isSelected`), and falls
1902
- * back to a connection's primary calendar when that connection has nothing selected.
1903
- *
1904
- * @param connectedCalendars - The connected calendars to select from.
1905
- * @returns The calendars to load.
1906
- */ function calcomCalendarsToLoadFromConnectedCalendars(connectedCalendars) {
1907
- return connectedCalendars.flatMap(function(connection) {
1908
- var selectedCalendars = connection.calendars.filter(function(x) {
1909
- return x.isSelected;
1910
- });
1911
- var primaryCalendars = connection.primary ? [
1912
- connection.primary
1913
- ] : [];
1914
- var calendars = selectedCalendars.length > 0 ? selectedCalendars : primaryCalendars;
1915
- return calendars.map(function(x) {
1916
- return {
1917
- credentialId: x.credentialId,
1918
- externalId: x.externalId
1919
- };
1920
- });
1921
- });
1922
- }
1923
- /**
1924
- * Retrieves busy time ranges across the given calendars for a date range.
1925
- *
1926
- * A caller cannot address this endpoint without first knowing its calendars, so this is the
1927
- * single-request primitive — see {@link getBusyTimesForConnectedCalendars} to resolve them too.
1928
- *
1929
- * @param context - The Cal.com API context providing authentication and fetch capabilities.
1930
- * @returns Retrieves busy time ranges for a date range.
1931
- *
1932
- * @see https://cal.com/docs/api-reference/v2/calendars/get-busy-times
1933
- *
1934
- * @example
1935
- * ```ts
1936
- * const response = await getBusyTimes(context)({
1937
- * dateFrom: '2026-03-17',
1938
- * dateTo: '2026-03-24',
1939
- * timeZone: 'America/Chicago',
1940
- * calendarsToLoad: [{ credentialId: 1845764, externalId: 'someone@example.com' }]
1941
- * });
1942
- * response.data.forEach(bt => console.log(bt.start, bt.end));
1943
- * ```
1944
- */ function getBusyTimes(context) {
1945
- return function(input) {
1946
- var params = fetch.makeUrlSearchParams({
1947
- timeZone: input.timeZone,
1948
- loggedInUsersTz: input.loggedInUsersTz,
1949
- dateFrom: input.dateFrom,
1950
- dateTo: input.dateTo,
1951
- calendarsToLoad: input.calendarsToLoad
1952
- }, {
1953
- useBracketNotation: true
1954
- });
1955
- return context.fetchJson("/calendars/busy-times?".concat(params), {
1956
- method: 'GET',
1957
- headers: calcomApiVersionHeaders(CALCOM_API_VERSION_CALENDARS)
1958
- });
1959
- };
1960
- }
1961
- /**
1962
- * Retrieves busy time ranges across the user's connected calendars for a date range.
1963
- *
1964
- * Convenience over {@link getBusyTimes}: loads the connected calendars first and derives
1965
- * `calendarsToLoad` via {@link calcomCalendarsToLoadFromConnectedCalendars}, so a caller does not
1966
- * have to know Cal.com's `isSelected`/primary selection rule. Issues two requests.
1967
- *
1968
- * @param context - The Cal.com API context providing authentication and fetch capabilities.
1969
- * @returns Retrieves busy time ranges across the user's connected calendars.
1970
- *
1971
- * @example
1972
- * ```ts
1973
- * const response = await getBusyTimesForConnectedCalendars(context)({
1974
- * dateFrom: '2026-03-17',
1975
- * dateTo: '2026-03-24',
1976
- * loggedInUsersTz: 'UTC'
1977
- * });
1978
- * ```
1979
- */ function getBusyTimesForConnectedCalendars(context) {
1980
- return function(input) {
1981
- return _async_to_generator$1(function() {
1982
- var calendarsResponse, calendarsToLoad;
1983
- return _ts_generator$1(this, function(_state) {
1984
- switch(_state.label){
1985
- case 0:
1986
- return [
1987
- 4,
1988
- getCalendars(context)()
1989
- ];
1990
- case 1:
1991
- calendarsResponse = _state.sent();
1992
- calendarsToLoad = calcomCalendarsToLoadFromConnectedCalendars(calendarsResponse.data.connectedCalendars);
1993
- return [
1994
- 2,
1995
- getBusyTimes(context)(_object_spread_props(_object_spread({}, input), {
1996
- calendarsToLoad: calendarsToLoad
1997
- }))
1998
- ];
1999
- }
2000
- });
2001
- })();
2002
- };
2003
- }
2004
-
2005
- /**
2006
- * All {@link CalcomWebhookTimeRelativeTrigger} values.
2007
- */ var ALL_CALCOM_WEBHOOK_TIME_RELATIVE_TRIGGERS = [
2008
- 'AFTER_HOSTS_CAL_VIDEO_NO_SHOW',
2009
- 'AFTER_GUESTS_CAL_VIDEO_NO_SHOW'
2010
- ];
2011
- /**
2012
- * All {@link CalcomWebhookVersion} values, oldest first.
2013
- */ var ALL_CALCOM_WEBHOOK_VERSIONS = [
2014
- '2021-10-20',
2015
- '2026-07-27'
2016
- ];
2017
- /**
2018
- * All {@link CalcomWebhookTimeUnit} values, smallest first.
2019
- */ var ALL_CALCOM_WEBHOOK_TIME_UNITS = [
2020
- 'MINUTE',
2021
- 'HOUR',
2022
- 'DAY'
2023
- ];
2024
- /**
2025
- * Maps each {@link CalcomWebhookTimeUnit} to the equivalent `@dereekb/util` {@link TimeUnit}.
2026
- */ var CALCOM_WEBHOOK_TIME_UNIT_TIME_UNIT_MAP = {
2027
- MINUTE: 'min',
2028
- HOUR: 'h',
2029
- DAY: 'd'
2030
- };
2031
- /**
2032
- * Converts a Cal.com webhook time offset to a `@dereekb/util` {@link TimeDuration}, so the
2033
- * duration utilities (`timeDurationToMilliseconds()`, `convertTimeDuration()`, ...) apply to it.
2034
- *
2035
- * @param offset - The webhook time offset to convert.
2036
- * @returns The equivalent TimeDuration.
2037
- *
2038
- * @example
2039
- * ```ts
2040
- * timeDurationToMilliseconds(calcomWebhookTimeOffsetToTimeDuration({ time: 5, timeUnit: 'MINUTE' })); // 300000
2041
- * ```
2042
- *
2043
- * @__NO_SIDE_EFFECTS__
2044
- */ function calcomWebhookTimeOffsetToTimeDuration(offset) {
2045
- return {
2046
- amount: offset.time,
2047
- unit: CALCOM_WEBHOOK_TIME_UNIT_TIME_UNIT_MAP[offset.timeUnit]
2048
- };
2049
- }
2050
- /**
2051
- * Reads a webhook's {@link CalcomWebhookTimeOffset} out of the sibling `time`/`timeUnit` fields.
2052
- *
2053
- * Returns undefined unless both halves are present, as the API returns them null on a webhook
2054
- * with no {@link CalcomWebhookTimeRelativeTrigger} and a magnitude with no unit means nothing.
2055
- *
2056
- * @param webhook - The webhook to read the offset from.
2057
- * @returns The webhook's time offset, or undefined when it has none.
2058
- *
2059
- * @__NO_SIDE_EFFECTS__
2060
- */ function calcomWebhookTimeOffsetFromWebhook(webhook) {
2061
- var time = webhook.time, timeUnit = webhook.timeUnit;
2062
- return time != null && timeUnit != null ? {
2063
- time: time,
2064
- timeUnit: timeUnit
2065
- } : undefined;
2066
- }
2067
- /**
2068
- * Creates a webhook subscription for the authenticated user. Webhooks notify your app
2069
- * when specified events occur (e.g., bookings created, cancelled, rescheduled).
2070
- *
2071
- * @param context - The Cal.com API context providing authentication and fetch capabilities.
2072
- * @returns Creates a webhook subscription from the given input.
2073
- *
2074
- * @see https://cal.com/docs/api-reference/v2/webhooks/create-a-webhook
2075
- *
2076
- * @example
2077
- * ```ts
2078
- * const response = await createWebhook(context)({
2079
- * subscriberUrl: 'https://example.com/webhook/calcom',
2080
- * triggers: ['BOOKING_CREATED', 'BOOKING_CANCELLED'],
2081
- * active: true
2082
- * });
2083
- * console.log(response.data.id);
2084
- * ```
2085
- *
2086
- * @__NO_SIDE_EFFECTS__
2087
- */ function createWebhook(context) {
2088
- return function(input) {
2089
- return context.fetchJson('/webhooks', {
2090
- method: 'POST',
2091
- body: JSON.stringify(input)
2092
- });
2093
- };
2094
- }
2095
- /**
2096
- * Retrieves all webhooks for the authenticated user.
2097
- *
2098
- * @param context - The Cal.com API context providing authentication and fetch capabilities.
2099
- * @returns Retrieves all webhooks.
2100
- *
2101
- * @see https://cal.com/docs/api-reference/v2/webhooks/get-all-webhooks
2102
- *
2103
- * @example
2104
- * ```ts
2105
- * const response = await getWebhooks(context)();
2106
- * response.data.forEach(wh => console.log(wh.subscriberUrl, wh.triggers));
2107
- * ```
2108
- */ function getWebhooks(context) {
2109
- return function() {
2110
- return context.fetchJson('/webhooks', {
2111
- method: 'GET'
2112
- });
2113
- };
2114
- }
2115
- /**
2116
- * Retrieves a specific webhook by ID.
2117
- *
2118
- * @param context - The Cal.com API context providing authentication and fetch capabilities.
2119
- * @returns Retrieves a specific webhook by ID.
2120
- *
2121
- * @see https://cal.com/docs/api-reference/v2/webhooks/get-a-webhook
2122
- *
2123
- * @example
2124
- * ```ts
2125
- * const response = await getWebhook(context)(42);
2126
- * console.log(response.data.subscriberUrl);
2127
- * ```
2128
- */ function getWebhook(context) {
2129
- return function(webhookId) {
2130
- return context.fetchJson("/webhooks/".concat(webhookId), {
2131
- method: 'GET'
2132
- });
2133
- };
2134
- }
2135
- /**
2136
- * Updates an existing webhook by ID.
2137
- *
2138
- * @param context - The Cal.com API context providing authentication and fetch capabilities.
2139
- * @returns Updates an existing webhook by ID.
2140
- *
2141
- * @see https://cal.com/docs/api-reference/v2/webhooks/update-a-webhook
2142
- *
2143
- * @example
2144
- * ```ts
2145
- * await updateWebhook(context)(42, { active: false });
2146
- * ```
2147
- */ function updateWebhook(context) {
2148
- return function(webhookId, input) {
2149
- return context.fetchJson("/webhooks/".concat(webhookId), {
2150
- method: 'PATCH',
2151
- body: JSON.stringify(input)
2152
- });
2153
- };
2154
- }
2155
- /**
2156
- * Deletes a webhook by ID.
2157
- *
2158
- * @param context - The Cal.com API context providing authentication and fetch capabilities.
2159
- * @returns Deletes a webhook by ID.
2160
- *
2161
- * @see https://cal.com/docs/api-reference/v2/webhooks/delete-a-webhook
2162
- *
2163
- * @example
2164
- * ```ts
2165
- * await deleteWebhook(context)(42);
2166
- * ```
2167
- */ function deleteWebhook(context) {
2168
- return function(webhookId) {
2169
- return context.fetchJson("/webhooks/".concat(webhookId), {
2170
- method: 'DELETE'
2171
- });
2172
- };
2173
- }
2174
-
2175
- /**
2176
- * The Cal.com OAuth API base URL.
2177
- *
2178
- * Endpoint paths are appended to this base, so it intentionally carries no endpoint segment of
2179
- * its own. This is the single place the OAuth host and prefix are encoded.
2180
- */ var CALCOM_OAUTH_API_URL = 'https://api.cal.com/v2/auth/oauth2';
2181
- /**
2182
- * The Cal.com OAuth token endpoint path, relative to {@link CALCOM_OAUTH_API_URL}.
2183
- */ var CALCOM_OAUTH_TOKEN_PATH = '/token';
2184
- /**
2185
- * The Cal.com OAuth authorize URL.
2186
- */ var CALCOM_OAUTH_AUTHORIZE_URL = 'https://app.cal.com/auth/oauth2/authorize';
2187
- /**
2188
- * Returns whether the credential is a {@link CalcomApiKeyCredential}.
2189
- *
2190
- * @param credential - The credential to check.
2191
- * @returns True when the credential carries an api key.
2192
- *
2193
- * @__NO_SIDE_EFFECTS__
2194
- */ function isCalcomApiKeyCredential(credential) {
2195
- return 'apiKey' in credential;
2196
- }
2197
- /**
2198
- * Builds a {@link CalcomAuthCredential} from flat, optional values, as an environment-facing
2199
- * configuration provides them.
2200
- *
2201
- * An api key wins when both are present: it does not expire, so it skips the refresh loop entirely.
2202
- * The cache attaches only to the refresh-token arm, since an api key has no token to cache. Empty
2203
- * strings count as absent, so an unset environment variable read as `''` does not become a
2204
- * credential that sends `Bearer `.
2205
- *
2206
- * @param values - The flat credential values.
2207
- * @returns The equivalent credential, or undefined when neither value is present.
2208
- *
2209
- * @__NO_SIDE_EFFECTS__
2210
- */ function calcomAuthCredentialFromValues(values) {
2211
- var apiKey = values.apiKey, refreshToken = values.refreshToken, accessTokenCache = values.accessTokenCache;
2212
- var result;
2213
- if (apiKey) {
2214
- result = {
2215
- apiKey: apiKey
2216
- };
2217
- } else if (refreshToken) {
2218
- result = {
2219
- refreshToken: refreshToken,
2220
- accessTokenCache: accessTokenCache
2221
- };
2222
- }
2223
- return result;
2224
- }
2225
- // COMPAT: Deprecated aliases
2226
- /**
2227
- * @deprecated use {@link CALCOM_OAUTH_API_URL} instead. This was previously used as the fetch base
2228
- * URL while the endpoint path `/oauth/token` was also appended, resolving to a doubly-pathed URL.
2229
- */ var CALCOM_OAUTH_TOKEN_URL = "".concat(CALCOM_OAUTH_API_URL).concat(CALCOM_OAUTH_TOKEN_PATH);
2230
-
2231
- /**
2232
- * Refreshes an access token using a refresh token. Cal.com rotates refresh tokens
2233
- * on every use, so the new `refresh_token` from the response must be persisted.
2234
- *
2235
- * Cal.com uses JSON body (not Basic Auth) for token requests.
2236
- *
2237
- * @param context - The Cal.com OAuth context providing client credentials and fetch capabilities.
2238
- * @returns Refreshes an access token using the given refresh token.
2239
- *
2240
- * @see https://cal.com/docs/api-reference/v2/oauth/refresh-an-existing-access-token
2241
- *
2242
- * @example
2243
- * ```ts
2244
- * const response = await refreshAccessToken(context)({ refreshToken: 'existing-refresh-token' });
2245
- * console.log(response.access_token, response.refresh_token);
2246
- * ```
2247
- */ function refreshAccessToken(context) {
2248
- var client = context.config.client;
2249
- return function(input) {
2250
- var fetchJsonInput = {
2251
- method: 'POST',
2252
- body: JSON.stringify({
2253
- grant_type: 'refresh_token',
2254
- client_id: client === null || client === void 0 ? void 0 : client.clientId,
2255
- client_secret: client === null || client === void 0 ? void 0 : client.clientSecret,
2256
- refresh_token: input.refreshToken
2257
- })
2258
- };
2259
- return context.fetchJson(CALCOM_OAUTH_TOKEN_PATH, fetchJsonInput);
2260
- };
2261
- }
2262
- /**
2263
- * Exchanges an OAuth authorization code for access and refresh tokens.
2264
- * Used during the initial OAuth flow when a user authorizes your app.
2265
- *
2266
- * Cal.com uses JSON body (not Basic Auth) for token requests.
2267
- *
2268
- * @param context - The Cal.com OAuth context providing client credentials and fetch capabilities.
2269
- * @returns Exchanges an authorization code for access and refresh tokens.
2270
- *
2271
- * @see https://cal.com/docs/api-reference/v2/oauth/exchange-an-authorization-code-for-access-tokens
2272
- *
2273
- * @example
2274
- * ```ts
2275
- * const response = await exchangeAuthorizationCode(context)({
2276
- * code: 'auth-code-from-redirect',
2277
- * redirectUri: 'https://example.com/callback'
2278
- * });
2279
- * console.log(response.access_token, response.refresh_token);
2280
- * ```
2281
- */ function exchangeAuthorizationCode(context) {
2282
- var client = context.config.client;
2283
- return function(input) {
2284
- var fetchJsonInput = {
2285
- method: 'POST',
2286
- body: JSON.stringify({
2287
- grant_type: 'authorization_code',
2288
- client_id: client === null || client === void 0 ? void 0 : client.clientId,
2289
- client_secret: client === null || client === void 0 ? void 0 : client.clientSecret,
2290
- code: input.code,
2291
- redirect_uri: input.redirectUri
2292
- })
2293
- };
2294
- return context.fetchJson(CALCOM_OAUTH_TOKEN_PATH, fetchJsonInput);
2295
- };
2296
- }
2297
-
2298
- /**
2299
- * Every granular Cal.com OAuth scope.
2300
- *
2301
- * A runtime list rather than a bare type union, so a configured scope can be validated instead of
2302
- * being passed through to the consent screen and refused there.
2303
- *
2304
- * @see https://cal.com/docs/api-reference/v2/oauth
2305
- */ var ALL_CALCOM_OAUTH_SCOPES = [
2306
- 'PROFILE_READ',
2307
- 'PROFILE_WRITE',
2308
- 'BOOKING_READ',
2309
- 'BOOKING_WRITE',
2310
- 'SCHEDULE_READ',
2311
- 'SCHEDULE_WRITE',
2312
- 'EVENT_TYPE_READ',
2313
- 'EVENT_TYPE_WRITE',
2314
- 'APPS_READ',
2315
- 'APPS_WRITE',
2316
- 'WEBHOOK_READ',
2317
- 'WEBHOOK_WRITE'
2318
- ];
2319
- /**
2320
- * Returns whether the input is a known {@link CalcomOAuthScope}.
2321
- *
2322
- * @param value - The value to check.
2323
- * @returns True when the value is a known Cal.com OAuth scope.
2324
- */ function isCalcomOAuthScope(value) {
2325
- return ALL_CALCOM_OAUTH_SCOPES.includes(value);
2326
- }
2327
- /**
2328
- * The delimiter used to join scopes in the `scope` query parameter.
2329
- *
2330
- * OAuth2 specifies a space-delimited list. Cal.com's granular scopes are documented without an
2331
- * explicit delimiter, so this is isolated here: if the consent screen rejects the `scope`
2332
- * parameter, this is the only value that needs to change.
2333
- */ var CALCOM_OAUTH_SCOPE_DELIMITER = ' ';
2334
- /**
2335
- * The `response_type` used by the authorization-code flow.
2336
- */ var CALCOM_OAUTH_AUTHORIZE_RESPONSE_TYPE = 'code';
2337
- /**
2338
- * Creates a {@link CalcomOAuthAuthorizeUrlFactory} that composes the Cal.com authorize URL that a
2339
- * user's browser is redirected to in order to begin the authorization-code flow.
2340
- *
2341
- * The client id, redirect URI, and scopes are fixed by the config, since a consumer holds those
2342
- * constant and varies only the per-request `state`.
2343
- *
2344
- * @param config - The client id, redirect URI, and scopes to request.
2345
- * @returns A factory that builds an authorize URL for the given params.
2346
- *
2347
- * @see https://cal.com/docs/api-reference/v2/oauth
2348
- *
2349
- * @example
2350
- * ```ts
2351
- * const authorizeUrlFactory = calcomOAuthAuthorizeUrlFactory({
2352
- * clientId: 'client-id',
2353
- * redirectUri: 'http://localhost:9901/oauth/calcom/callback',
2354
- * scopes: ['PROFILE_READ', 'BOOKING_READ']
2355
- * });
2356
- *
2357
- * const url = authorizeUrlFactory({ state: 'signed-state' });
2358
- * ```
2359
- *
2360
- * @__NO_SIDE_EFFECTS__
2361
- */ function calcomOAuthAuthorizeUrlFactory(config) {
2362
- var clientId = config.clientId, redirectUri = config.redirectUri, scopes = config.scopes, inputAuthorizeUrl = config.authorizeUrl;
2363
- var authorizeUrl = inputAuthorizeUrl !== null && inputAuthorizeUrl !== void 0 ? inputAuthorizeUrl : CALCOM_OAUTH_AUTHORIZE_URL;
2364
- var scope = scopes.join(CALCOM_OAUTH_SCOPE_DELIMITER);
2365
- return function(params) {
2366
- var url = new URL(authorizeUrl);
2367
- var state = params === null || params === void 0 ? void 0 : params.state;
2368
- url.searchParams.set('client_id', clientId);
2369
- url.searchParams.set('redirect_uri', redirectUri);
2370
- url.searchParams.set('response_type', CALCOM_OAUTH_AUTHORIZE_RESPONSE_TYPE);
2371
- url.searchParams.set('scope', scope);
2372
- if (state != null) {
2373
- url.searchParams.set('state', state);
2374
- }
2375
- return url.toString();
2376
- };
2377
- }
2378
-
2379
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
2380
- try {
2381
- var info = gen[key](arg);
2382
- var value = info.value;
2383
- } catch (error) {
2384
- reject(error);
2385
- return;
2386
- }
2387
- if (info.done) {
2388
- resolve(value);
2389
- } else {
2390
- Promise.resolve(value).then(_next, _throw);
2391
- }
2392
- }
2393
- function _async_to_generator(fn) {
2394
- return function() {
2395
- var self = this, args = arguments;
2396
- return new Promise(function(resolve, reject) {
2397
- var gen = fn.apply(self, args);
2398
- function _next(value) {
2399
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
2400
- }
2401
- function _throw(err) {
2402
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
2403
- }
2404
- _next(undefined);
2405
- });
2406
- };
2407
- }
2408
- function _ts_generator(thisArg, body) {
2409
- var f, y, t, _ = {
2410
- label: 0,
2411
- sent: function() {
2412
- if (t[0] & 1) throw t[1];
2413
- return t[1];
2414
- },
2415
- trys: [],
2416
- ops: []
2417
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
2418
- return d(g, "next", {
2419
- value: verb(0)
2420
- }), d(g, "throw", {
2421
- value: verb(1)
2422
- }), d(g, "return", {
2423
- value: verb(2)
2424
- }), typeof Symbol === "function" && d(g, Symbol.iterator, {
2425
- value: function() {
2426
- return this;
2427
- }
2428
- }), g;
2429
- function verb(n) {
2430
- return function(v) {
2431
- return step([
2432
- n,
2433
- v
2434
- ]);
2435
- };
2436
- }
2437
- function step(op) {
2438
- if (f) throw new TypeError("Generator is already executing.");
2439
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
2440
- 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;
2441
- if (y = 0, t) op = [
2442
- op[0] & 2,
2443
- t.value
2444
- ];
2445
- switch(op[0]){
2446
- case 0:
2447
- case 1:
2448
- t = op;
2449
- break;
2450
- case 4:
2451
- _.label++;
2452
- return {
2453
- value: op[1],
2454
- done: false
2455
- };
2456
- case 5:
2457
- _.label++;
2458
- y = op[1];
2459
- op = [
2460
- 0
2461
- ];
2462
- continue;
2463
- case 7:
2464
- op = _.ops.pop();
2465
- _.trys.pop();
2466
- continue;
2467
- default:
2468
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
2469
- _ = 0;
2470
- continue;
2471
- }
2472
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
2473
- _.label = op[1];
2474
- break;
2475
- }
2476
- if (op[0] === 6 && _.label < t[1]) {
2477
- _.label = t[1];
2478
- t = op;
2479
- break;
2480
- }
2481
- if (t && _.label < t[2]) {
2482
- _.label = t[2];
2483
- _.ops.push(op);
2484
- break;
2485
- }
2486
- if (t[2]) _.ops.pop();
2487
- _.trys.pop();
2488
- continue;
2489
- }
2490
- op = body.call(thisArg, _);
2491
- } catch (e) {
2492
- op = [
2493
- 6,
2494
- e
2495
- ];
2496
- y = 0;
2497
- } finally{
2498
- f = t = 0;
2499
- }
2500
- if (op[0] & 5) throw op[1];
2501
- return {
2502
- value: op[0] ? op[1] : void 0,
2503
- done: true
2504
- };
2505
- }
2506
- }
2507
- /**
2508
- * Maps a {@link CalcomOAuthTokenResponse} to a {@link CalcomAccessToken}.
2509
- *
2510
- * Pure: the caller owns the rotated refresh token that comes back on the result, so each token
2511
- * scope (server-level vs per-user) tracks its own rotation instead of sharing one variable.
2512
- *
2513
- * @param response - The token response returned by the Cal.com token endpoint.
2514
- * @returns The equivalent CalcomAccessToken, with `expiresAt` resolved against the current time.
2515
- *
2516
- * @__NO_SIDE_EFFECTS__
2517
- */ function calcomAccessTokenFromTokenResponse(response) {
2518
- var createdAt = Date.now();
2519
- var access_token = response.access_token, refresh_token = response.refresh_token, scope = response.scope, expires_in = response.expires_in;
2520
- var accessToken = {
2521
- accessToken: access_token,
2522
- refreshToken: refresh_token,
2523
- expiresIn: expires_in,
2524
- expiresAt: new Date(createdAt + expires_in * util.MS_IN_SECOND),
2525
- scope: scope !== null && scope !== void 0 ? scope : ''
2526
- };
2527
- return accessToken;
2528
- }
2529
- /**
2530
- * The lifetime given to the synthetic access token an api key is wrapped in.
2531
- *
2532
- * Cal.com api keys do not expire; the value only has to outlive any process holding one, so the
2533
- * token satisfies the same expiration check every other token goes through.
2534
- */ var CALCOM_API_KEY_ACCESS_TOKEN_EXPIRATION = util.MS_IN_DAY * 365 * 100;
2535
- /**
2536
- * Wraps a {@link CalcomApiKey} as a static {@link CalcomAccessToken}.
2537
- *
2538
- * An api key is already a bearer token acting as the user who created it, so there is nothing to
2539
- * exchange and nothing to refresh.
2540
- *
2541
- * @param apiKey - The Cal.com api key.
2542
- * @returns The equivalent static CalcomAccessToken.
2543
- *
2544
- * @__NO_SIDE_EFFECTS__
2545
- */ function calcomAccessTokenFromApiKey(apiKey) {
2546
- var accessToken = {
2547
- accessToken: apiKey,
2548
- refreshToken: '',
2549
- expiresIn: Number.MAX_SAFE_INTEGER,
2550
- expiresAt: new Date(Date.now() + CALCOM_API_KEY_ACCESS_TOKEN_EXPIRATION),
2551
- scope: ''
2552
- };
2553
- return accessToken;
2554
- }
2555
- /**
2556
- * Creates a {@link CalcomOAuthFactory} that produces configured Cal.com OAuth instances.
2557
- * Supports both API key authentication (static token, no refresh) and full OAuth
2558
- * refresh token flow with automatic token rotation.
2559
- *
2560
- * @param factoryConfig - Configuration including optional fetch factory and error logging.
2561
- * @returns A factory function that accepts a CalcomOAuthConfig and produces a CalcomOAuth instance.
2562
- *
2563
- * @__NO_SIDE_EFFECTS__
2564
- */ function calcomOAuthFactory(factoryConfig) {
2565
- var _factoryConfig_fetchHandler;
2566
- var fetchHandler = (_factoryConfig_fetchHandler = factoryConfig.fetchHandler) !== null && _factoryConfig_fetchHandler !== void 0 ? _factoryConfig_fetchHandler : calcomRateLimitedFetchHandler();
2567
- var logCalcomServerErrorFunction = factoryConfig.logCalcomServerErrorFunction, _factoryConfig_fetchFactory = factoryConfig.fetchFactory, fetchFactory = _factoryConfig_fetchFactory === void 0 ? function(_) {
2568
- return fetch.fetchApiFetchService.makeFetch({
2569
- baseUrl: CALCOM_OAUTH_API_URL,
2570
- baseRequest: {
2571
- headers: {
2572
- 'Content-Type': 'application/json'
2573
- }
2574
- },
2575
- fetchHandler: fetchHandler,
2576
- timeout: 20 * 1000,
2577
- requireOkResponse: true,
2578
- useTimeout: true // use timeout
2579
- });
2580
- } : _factoryConfig_fetchFactory;
2581
- return function(config) {
2582
- var defaultAuth = config.defaultAuth, client = config.client;
2583
- var hasApiKeyDefault = defaultAuth != null && isCalcomApiKeyCredential(defaultAuth) && !!defaultAuth.apiKey;
2584
- // an API key IS the token; every other credential is an exchange the token endpoint authenticates
2585
- // with the client id and secret. With neither, no token could ever be produced
2586
- if (!hasApiKeyDefault && client == null) {
2587
- throw new Error('CalcomOAuthConfig can authenticate nothing. Provide `defaultAuth: { apiKey }` for ambient calls, `client` (clientId+clientSecret) to exchange any refresh token, or both.');
2588
- }
2589
- var baseFetch = fetchFactory();
2590
- var fetch$1 = handleCalcomOAuthErrorFetch(baseFetch, logCalcomServerErrorFunction);
2591
- var fetchJson = fetch.fetchJsonFunction(fetch$1, {
2592
- handleFetchJsonParseErrorFunction: fetch.returnNullHandleFetchJsonParseErrorFunction
2593
- });
2594
- // MARK: Access Tokens
2595
- var makeAccessTokenFactory = function makeAccessTokenFactory(credential) {
2596
- var result;
2597
- if (isCalcomApiKeyCredential(credential)) {
2598
- var apiKey = credential.apiKey;
2599
- // presence, not truthiness, is what discriminates the union — so without this an empty key
2600
- // would be handed back as a valid static token and every call would send `Bearer `
2601
- if (!apiKey) {
2602
- throw new Error('CalcomApiKeyCredential.apiKey is empty.');
2603
- }
2604
- var apiKeyToken = calcomAccessTokenFromApiKey(apiKey);
2605
- result = function result() {
2606
- return _async_to_generator(function() {
2607
- return _ts_generator(this, function(_state) {
2608
- return [
2609
- 2,
2610
- apiKeyToken
2611
- ];
2612
- });
2613
- })();
2614
- };
2615
- } else {
2616
- // a token for a specific grant can only come from that grant's refresh token, exchanged
2617
- // against the OAuth client. An API key is a different user's identity and cannot stand in
2618
- if (client == null) {
2619
- throw new Error('makeAccessTokenFactory() requires a `client` (clientId+clientSecret) to exchange a refresh token credential. A Cal.com configuration with only an api key cannot create one.');
2620
- }
2621
- /**
2622
- * Tracks THIS credential's rotated refresh token, since Cal.com rotates on every use.
2623
- *
2624
- * Declared per invocation, so every credential — the default one as much as any per-user one
2625
- * — rotates in isolation and refreshing one never overwrites another's token.
2626
- */ var latestRefreshToken = credential.refreshToken;
2627
- var tokenRefresher = function tokenRefresher() {
2628
- return _async_to_generator(function() {
2629
- var response, accessToken;
2630
- return _ts_generator(this, function(_state) {
2631
- switch(_state.label){
2632
- case 0:
2633
- return [
2634
- 4,
2635
- refreshAccessToken(oauthContext)({
2636
- refreshToken: latestRefreshToken
2637
- })
2638
- ];
2639
- case 1:
2640
- response = _state.sent();
2641
- accessToken = calcomAccessTokenFromTokenResponse(response);
2642
- latestRefreshToken = accessToken.refreshToken;
2643
- return [
2644
- 2,
2645
- accessToken
2646
- ];
2647
- }
2648
- });
2649
- })();
2650
- };
2651
- result = calcomOAuthAccessTokenFactory({
2652
- tokenRefresher: tokenRefresher,
2653
- accessTokenCache: credential.accessTokenCache
2654
- });
2655
- }
2656
- return result;
2657
- };
2658
- // built once, so the default credential's in-memory tier and its rotation are shared across the
2659
- // whole context instead of restarting on every call
2660
- var loadAccessToken = defaultAuth == null ? function() {
2661
- return _async_to_generator(function() {
2662
- return _ts_generator(this, function(_state) {
2663
- throw new CalcomOAuthAuthFailureError('No `defaultAuth` is configured on this CalcomOAuthConfig, so there is no ambient credential to authenticate with. Use makeAccessTokenFactory(credential) for a named credential.');
2664
- });
2665
- })();
2666
- } : makeAccessTokenFactory(defaultAuth);
2667
- var oauthContext = {
2668
- fetch: fetch$1,
2669
- fetchJson: fetchJson,
2670
- loadAccessToken: loadAccessToken,
2671
- makeAccessTokenFactory: makeAccessTokenFactory,
2672
- config: config
2673
- };
2674
- var calcomOAuth = {
2675
- oauthContext: oauthContext
2676
- };
2677
- return calcomOAuth;
2678
- };
2679
- }
2680
- /**
2681
- * Creates a CalcomAccessTokenFactory with multi-tier caching.
2682
- * Checks the in-memory cache first, then the external cache, and finally refreshes
2683
- * from the token refresher if no valid token is available.
2684
- *
2685
- * @param config - Configuration including the token refresher, optional cache, and expiration buffer.
2686
- * @returns A CalcomAccessTokenFactory that returns a valid access token on each call.
2687
- *
2688
- * @__NO_SIDE_EFFECTS__
2689
- */ function calcomOAuthAccessTokenFactory(config) {
2690
- var tokenRefresher = config.tokenRefresher, accessTokenCache = config.accessTokenCache, inputTokenExpirationBuffer = config.tokenExpirationBuffer;
2691
- var tokenExpirationBuffer = inputTokenExpirationBuffer !== null && inputTokenExpirationBuffer !== void 0 ? inputTokenExpirationBuffer : util.MS_IN_MINUTE;
2692
- /**
2693
- * Caches the token internally here until it expires.
2694
- */ var currentToken = null;
2695
- return function() {
2696
- return _async_to_generator(function() {
2697
- var cachedToken, isExpired, e;
2698
- return _ts_generator(this, function(_state) {
2699
- switch(_state.label){
2700
- case 0:
2701
- if (!!currentToken) return [
2702
- 3,
2703
- 2
2704
- ];
2705
- return [
2706
- 4,
2707
- accessTokenCache === null || accessTokenCache === void 0 ? void 0 : accessTokenCache.loadCachedToken()
2708
- ];
2709
- case 1:
2710
- cachedToken = _state.sent();
2711
- if (cachedToken) {
2712
- currentToken = cachedToken;
2713
- }
2714
- _state.label = 2;
2715
- case 2:
2716
- // check expiration
2717
- if (currentToken != null) {
2718
- isExpired = Date.now() + tokenExpirationBuffer >= currentToken.expiresAt.getTime();
2719
- if (isExpired) {
2720
- currentToken = null;
2721
- }
2722
- }
2723
- if (!!currentToken) return [
2724
- 3,
2725
- 10
2726
- ];
2727
- _state.label = 3;
2728
- case 3:
2729
- _state.trys.push([
2730
- 3,
2731
- 5,
2732
- ,
2733
- 6
2734
- ]);
2735
- return [
2736
- 4,
2737
- tokenRefresher()
2738
- ];
2739
- case 4:
2740
- currentToken = _state.sent();
2741
- return [
2742
- 3,
2743
- 6
2744
- ];
2745
- case 5:
2746
- e = _state.sent();
2747
- console.error("calcomOAuthAccessTokenFactory(): Failed retrieving new token from tokenRefresher: ", e);
2748
- throw new CalcomOAuthAuthFailureError('Token Refresh Failed');
2749
- case 6:
2750
- if (!currentToken) return [
2751
- 3,
2752
- 10
2753
- ];
2754
- _state.label = 7;
2755
- case 7:
2756
- _state.trys.push([
2757
- 7,
2758
- 9,
2759
- ,
2760
- 10
2761
- ]);
2762
- return [
2763
- 4,
2764
- accessTokenCache === null || accessTokenCache === void 0 ? void 0 : accessTokenCache.updateCachedToken(currentToken)
2765
- ];
2766
- case 8:
2767
- _state.sent();
2768
- return [
2769
- 3,
2770
- 10
2771
- ];
2772
- case 9:
2773
- _state.sent();
2774
- return [
2775
- 3,
2776
- 10
2777
- ];
2778
- case 10:
2779
- return [
2780
- 2,
2781
- currentToken
2782
- ];
2783
- }
2784
- });
2785
- })();
2786
- };
2787
- }
2788
-
2789
- exports.ALL_CALCOM_OAUTH_SCOPES = ALL_CALCOM_OAUTH_SCOPES;
2790
- exports.ALL_CALCOM_WEBHOOK_TIME_RELATIVE_TRIGGERS = ALL_CALCOM_WEBHOOK_TIME_RELATIVE_TRIGGERS;
2791
- exports.ALL_CALCOM_WEBHOOK_TIME_UNITS = ALL_CALCOM_WEBHOOK_TIME_UNITS;
2792
- exports.ALL_CALCOM_WEBHOOK_VERSIONS = ALL_CALCOM_WEBHOOK_VERSIONS;
2793
- exports.CALCOM_API_KEY_ACCESS_TOKEN_EXPIRATION = CALCOM_API_KEY_ACCESS_TOKEN_EXPIRATION;
2794
- exports.CALCOM_API_URL = CALCOM_API_URL;
2795
- exports.CALCOM_API_VERSION_BOOKINGS = CALCOM_API_VERSION_BOOKINGS;
2796
- exports.CALCOM_API_VERSION_CALENDARS = CALCOM_API_VERSION_CALENDARS;
2797
- exports.CALCOM_API_VERSION_EVENT_TYPES = CALCOM_API_VERSION_EVENT_TYPES;
2798
- exports.CALCOM_API_VERSION_HEADER = CALCOM_API_VERSION_HEADER;
2799
- exports.CALCOM_API_VERSION_ME = CALCOM_API_VERSION_ME;
2800
- exports.CALCOM_API_VERSION_SCHEDULES = CALCOM_API_VERSION_SCHEDULES;
2801
- exports.CALCOM_API_VERSION_SLOTS = CALCOM_API_VERSION_SLOTS;
2802
- exports.CALCOM_OAUTH_API_URL = CALCOM_OAUTH_API_URL;
2803
- exports.CALCOM_OAUTH_AUTHORIZE_RESPONSE_TYPE = CALCOM_OAUTH_AUTHORIZE_RESPONSE_TYPE;
2804
- exports.CALCOM_OAUTH_AUTHORIZE_URL = CALCOM_OAUTH_AUTHORIZE_URL;
2805
- exports.CALCOM_OAUTH_INVALID_GRANT_ERROR_CODE = CALCOM_OAUTH_INVALID_GRANT_ERROR_CODE;
2806
- exports.CALCOM_OAUTH_SCOPE_DELIMITER = CALCOM_OAUTH_SCOPE_DELIMITER;
2807
- exports.CALCOM_OAUTH_TOKEN_PATH = CALCOM_OAUTH_TOKEN_PATH;
2808
- exports.CALCOM_OAUTH_TOKEN_URL = CALCOM_OAUTH_TOKEN_URL;
2809
- exports.CALCOM_RATE_LIMIT_LIMIT_HEADER = CALCOM_RATE_LIMIT_LIMIT_HEADER;
2810
- exports.CALCOM_RATE_LIMIT_REMAINING_HEADER = CALCOM_RATE_LIMIT_REMAINING_HEADER;
2811
- exports.CALCOM_RATE_LIMIT_RESET_HEADER = CALCOM_RATE_LIMIT_RESET_HEADER;
2812
- exports.CALCOM_TOO_MANY_REQUESTS_HTTP_STATUS_CODE = CALCOM_TOO_MANY_REQUESTS_HTTP_STATUS_CODE;
2813
- exports.CALCOM_WEBHOOK_TIME_UNIT_TIME_UNIT_MAP = CALCOM_WEBHOOK_TIME_UNIT_TIME_UNIT_MAP;
2814
- exports.CalcomOAuthAccessTokenError = CalcomOAuthAccessTokenError;
2815
- exports.CalcomOAuthAuthFailureError = CalcomOAuthAuthFailureError;
2816
- exports.CalcomServerError = CalcomServerError;
2817
- exports.CalcomServerFetchResponseError = CalcomServerFetchResponseError;
2818
- exports.CalcomTooManyRequestsError = CalcomTooManyRequestsError;
2819
- exports.DEFAULT_CALCOM_API_RATE_LIMIT = DEFAULT_CALCOM_API_RATE_LIMIT;
2820
- exports.DEFAULT_CALCOM_API_RATE_LIMIT_RESET_PERIOD = DEFAULT_CALCOM_API_RATE_LIMIT_RESET_PERIOD;
2821
- exports.DEFAULT_CALCOM_RATE_LIMITED_TOO_MANY_REQUESTS_LOG_FUNCTION = DEFAULT_CALCOM_RATE_LIMITED_TOO_MANY_REQUESTS_LOG_FUNCTION;
2822
- exports.calcomAccessTokenFromApiKey = calcomAccessTokenFromApiKey;
2823
- exports.calcomAccessTokenFromTokenResponse = calcomAccessTokenFromTokenResponse;
2824
- exports.calcomAccessTokenStringFactory = calcomAccessTokenStringFactory;
2825
- exports.calcomApiVersionHeaders = calcomApiVersionHeaders;
2826
- exports.calcomAuthCredentialFromValues = calcomAuthCredentialFromValues;
2827
- exports.calcomCalendarsToLoadFromConnectedCalendars = calcomCalendarsToLoadFromConnectedCalendars;
2828
- exports.calcomFactory = calcomFactory;
2829
- exports.calcomOAuthAccessTokenFactory = calcomOAuthAccessTokenFactory;
2830
- exports.calcomOAuthAuthorizeUrlFactory = calcomOAuthAuthorizeUrlFactory;
2831
- exports.calcomOAuthFactory = calcomOAuthFactory;
2832
- exports.calcomRateLimitHeaderDetails = calcomRateLimitHeaderDetails;
2833
- exports.calcomRateLimitedFetchHandler = calcomRateLimitedFetchHandler;
2834
- exports.calcomServerErrorDataFromApiErrorResponseBody = calcomServerErrorDataFromApiErrorResponseBody;
2835
- exports.calcomWebhookTimeOffsetFromWebhook = calcomWebhookTimeOffsetFromWebhook;
2836
- exports.calcomWebhookTimeOffsetToTimeDuration = calcomWebhookTimeOffsetToTimeDuration;
2837
- exports.cancelBooking = cancelBooking;
2838
- exports.createBooking = createBooking;
2839
- exports.createEventType = createEventType;
2840
- exports.createWebhook = createWebhook;
2841
- exports.deleteEventType = deleteEventType;
2842
- exports.deleteWebhook = deleteWebhook;
2843
- exports.exchangeAuthorizationCode = exchangeAuthorizationCode;
2844
- exports.getAvailableSlots = getAvailableSlots;
2845
- exports.getBooking = getBooking;
2846
- exports.getBookings = getBookings;
2847
- exports.getBusyTimes = getBusyTimes;
2848
- exports.getBusyTimesForConnectedCalendars = getBusyTimesForConnectedCalendars;
2849
- exports.getCalendars = getCalendars;
2850
- exports.getEventTypes = getEventTypes;
2851
- exports.getMe = getMe;
2852
- exports.getSchedules = getSchedules;
2853
- exports.getWebhook = getWebhook;
2854
- exports.getWebhooks = getWebhooks;
2855
- exports.handleCalcomErrorFetch = handleCalcomErrorFetch;
2856
- exports.handleCalcomErrorFetchFactory = handleCalcomErrorFetchFactory;
2857
- exports.handleCalcomOAuthErrorFetch = handleCalcomOAuthErrorFetch;
2858
- exports.isCalcomApiKeyCredential = isCalcomApiKeyCredential;
2859
- exports.isCalcomOAuthScope = isCalcomOAuthScope;
2860
- exports.logCalcomErrorToConsole = logCalcomErrorToConsole;
2861
- exports.logCalcomOAuthErrorToConsole = logCalcomOAuthErrorToConsole;
2862
- exports.logCalcomServerErrorFunction = logCalcomServerErrorFunction;
2863
- exports.parseCalcomApiError = parseCalcomApiError;
2864
- exports.parseCalcomApiServerErrorResponseData = parseCalcomApiServerErrorResponseData;
2865
- exports.parseCalcomOAuthError = parseCalcomOAuthError;
2866
- exports.parseCalcomOAuthServerErrorResponseData = parseCalcomOAuthServerErrorResponseData;
2867
- exports.parseCalcomServerErrorData = parseCalcomServerErrorData;
2868
- exports.refreshAccessToken = refreshAccessToken;
2869
- exports.updateEventType = updateEventType;
2870
- exports.updateWebhook = updateWebhook;