@dereekb/calcom 13.38.0 → 13.40.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,2990 +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
- * Creates a new schedule for the authenticated user.
1476
- *
1477
- * @param context - The Cal.com API context providing authentication and fetch capabilities.
1478
- * @returns Creates a new schedule from the given input.
1479
- *
1480
- * @see https://cal.com/docs/api-reference/v2/schedules/create-a-schedule
1481
- *
1482
- * @example
1483
- * ```ts
1484
- * const response = await createSchedule(context)({
1485
- * name: 'Coaching Hours',
1486
- * timeZone: 'America/Chicago',
1487
- * isDefault: false,
1488
- * availability: [{ days: ['Monday', 'Friday'], startTime: '08:00', endTime: '12:00' }],
1489
- * overrides: [{ date: '2026-12-24', startTime: '10:00', endTime: '11:00' }]
1490
- * });
1491
- * console.log(response.data.id);
1492
- * ```
1493
- */ function createSchedule(context) {
1494
- return function(input) {
1495
- return context.fetchJson('/schedules', {
1496
- method: 'POST',
1497
- headers: calcomApiVersionHeaders(CALCOM_API_VERSION_SCHEDULES),
1498
- body: JSON.stringify(input)
1499
- });
1500
- };
1501
- }
1502
- /**
1503
- * Retrieves the authenticated user's default schedule.
1504
- *
1505
- * @param context - The Cal.com API context providing authentication and fetch capabilities.
1506
- * @returns Retrieves the default schedule.
1507
- *
1508
- * @see https://cal.com/docs/api-reference/v2/schedules/get-default-schedule
1509
- *
1510
- * @example
1511
- * ```ts
1512
- * const response = await getDefaultSchedule(context)();
1513
- * console.log(response.data?.name, response.data?.timeZone);
1514
- * ```
1515
- */ function getDefaultSchedule(context) {
1516
- return function() {
1517
- return context.fetchJson('/schedules/default', {
1518
- method: 'GET',
1519
- headers: calcomApiVersionHeaders(CALCOM_API_VERSION_SCHEDULES)
1520
- });
1521
- };
1522
- }
1523
- /**
1524
- * Retrieves a single schedule by ID.
1525
- *
1526
- * @param context - The Cal.com API context providing authentication and fetch capabilities.
1527
- * @returns Retrieves a schedule by ID.
1528
- *
1529
- * @see https://cal.com/docs/api-reference/v2/schedules/get-a-schedule
1530
- *
1531
- * @example
1532
- * ```ts
1533
- * const response = await getSchedule(context)(588440);
1534
- * console.log(response.data.availability, response.data.overrides);
1535
- * ```
1536
- */ function getSchedule(context) {
1537
- return function(scheduleId) {
1538
- return context.fetchJson("/schedules/".concat(scheduleId), {
1539
- method: 'GET',
1540
- headers: calcomApiVersionHeaders(CALCOM_API_VERSION_SCHEDULES)
1541
- });
1542
- };
1543
- }
1544
- /**
1545
- * Updates an existing schedule by ID.
1546
- *
1547
- * @param context - The Cal.com API context providing authentication and fetch capabilities.
1548
- * @returns Updates a schedule by ID.
1549
- *
1550
- * @see https://cal.com/docs/api-reference/v2/schedules/update-a-schedule
1551
- *
1552
- * @example
1553
- * ```ts
1554
- * // replaces the weekly rules and marks the whole of Christmas Day unavailable
1555
- * await updateSchedule(context)(588440, {
1556
- * availability: [{ days: ['Monday'], startTime: '09:00', endTime: '17:00' }],
1557
- * overrides: [{ date: '2026-12-25', startTime: '00:00', endTime: '00:00' }]
1558
- * });
1559
- * ```
1560
- */ function updateSchedule(context) {
1561
- return function(scheduleId, input) {
1562
- return context.fetchJson("/schedules/".concat(scheduleId), {
1563
- method: 'PATCH',
1564
- headers: calcomApiVersionHeaders(CALCOM_API_VERSION_SCHEDULES),
1565
- body: JSON.stringify(input)
1566
- });
1567
- };
1568
- }
1569
- /**
1570
- * Deletes a schedule by ID.
1571
- *
1572
- * @param context - The Cal.com API context providing authentication and fetch capabilities.
1573
- * @returns Deletes a schedule by ID.
1574
- *
1575
- * @see https://cal.com/docs/api-reference/v2/schedules/delete-a-schedule
1576
- *
1577
- * @example
1578
- * ```ts
1579
- * await deleteSchedule(context)(588440);
1580
- * ```
1581
- */ function deleteSchedule(context) {
1582
- return function(scheduleId) {
1583
- return context.fetchJson("/schedules/".concat(scheduleId), {
1584
- method: 'DELETE',
1585
- headers: calcomApiVersionHeaders(CALCOM_API_VERSION_SCHEDULES)
1586
- });
1587
- };
1588
- }
1589
-
1590
- /**
1591
- * Queries available booking slots for a given event type within a date range.
1592
- * This endpoint is public and does not require authentication.
1593
- *
1594
- * Identify the event type by `eventTypeId`, or by `eventTypeSlug` + `username`/`teamSlug`.
1595
- *
1596
- * @param context - The Cal.com API context (authenticated or public)
1597
- * @returns Queries available slots for the given input.
1598
- *
1599
- * The `cal-api-version` header is REQUIRED here — without it the endpoint 404s.
1600
- *
1601
- * @see https://cal.com/docs/api-reference/v2/slots/get-available-time-slots-for-an-event-type
1602
- *
1603
- * @example
1604
- * ```ts
1605
- * const response = await getAvailableSlots(context)({
1606
- * start: '2026-03-17T00:00:00.000Z',
1607
- * end: '2026-03-24T00:00:00.000Z',
1608
- * eventTypeId: 12345
1609
- * });
1610
- *
1611
- * for (const [date, slots] of Object.entries(response.data)) {
1612
- * console.log(date, slots.map(s => s.start));
1613
- * }
1614
- * ```
1615
- */ function getAvailableSlots(context) {
1616
- return function(input) {
1617
- var params = fetch.makeUrlSearchParams(input);
1618
- return context.fetchJson("/slots?".concat(params), {
1619
- method: 'GET',
1620
- headers: calcomApiVersionHeaders(CALCOM_API_VERSION_SLOTS)
1621
- });
1622
- };
1623
- }
1624
-
1625
- /**
1626
- * Creates a new booking for the specified event type. The `attendee` represents the person
1627
- * booking (the client), not the host. This endpoint can be called without authentication.
1628
- *
1629
- * @param context - The Cal.com API context providing authentication and fetch capabilities.
1630
- * @returns Creates a booking from the given input.
1631
- *
1632
- * @see https://cal.com/docs/api-reference/v2/bookings/create-a-booking
1633
- *
1634
- * @example
1635
- * ```ts
1636
- * const response = await createBooking(context)({
1637
- * start: '2026-03-20T14:00:00.000Z',
1638
- * eventTypeId: 12345,
1639
- * attendee: { name: 'Jane Doe', email: 'jane@example.com', timeZone: 'America/New_York' }
1640
- * });
1641
- * console.log(response.data.uid);
1642
- * ```
1643
- *
1644
- * @__NO_SIDE_EFFECTS__
1645
- */ function createBooking(context) {
1646
- return function(input) {
1647
- return context.fetchJson('/bookings', {
1648
- method: 'POST',
1649
- headers: calcomApiVersionHeaders(CALCOM_API_VERSION_BOOKINGS),
1650
- body: JSON.stringify(input)
1651
- });
1652
- };
1653
- }
1654
- /**
1655
- * Retrieves the bookings visible to the authenticated user, newest page first.
1656
- *
1657
- * Paginated: read {@link CalcomGetBookingsResponse.pagination} rather than assuming `data` holds
1658
- * everything, as the endpoint caps a page even with no `take`.
1659
- *
1660
- * @param context - The Cal.com API context providing authentication and fetch capabilities.
1661
- * @returns Retrieves a page of bookings for the given input.
1662
- *
1663
- * @see https://cal.com/docs/api-reference/v2/bookings/get-all-bookings
1664
- *
1665
- * @example
1666
- * ```ts
1667
- * const response = await getBookings(context)({ take: 10, status: 'upcoming', sortStart: 'asc' });
1668
- * console.log(response.pagination.totalItems, response.data.map(b => b.uid));
1669
- * ```
1670
- */ function getBookings(context) {
1671
- return function(input) {
1672
- var params = fetch.makeUrlSearchParams(input);
1673
- return context.fetchJson("/bookings?".concat(params), {
1674
- method: 'GET',
1675
- headers: calcomApiVersionHeaders(CALCOM_API_VERSION_BOOKINGS)
1676
- });
1677
- };
1678
- }
1679
- /**
1680
- * Retrieves a booking by its unique UID.
1681
- *
1682
- * @param context - The Cal.com API context providing authentication and fetch capabilities.
1683
- * @returns Retrieves a booking by its UID.
1684
- *
1685
- * @see https://cal.com/docs/api-reference/v2/bookings/get-a-booking
1686
- *
1687
- * @example
1688
- * ```ts
1689
- * const response = await getBooking(context)('abc-123-uid');
1690
- * console.log(response.data.title, response.data.status);
1691
- * ```
1692
- */ function getBooking(context) {
1693
- return function(uid) {
1694
- return context.fetchJson("/bookings/".concat(uid), {
1695
- method: 'GET',
1696
- headers: calcomApiVersionHeaders(CALCOM_API_VERSION_BOOKINGS)
1697
- });
1698
- };
1699
- }
1700
- /**
1701
- * Cancels a booking by its unique UID, with an optional cancellation reason.
1702
- *
1703
- * @param context - The Cal.com API context providing authentication and fetch capabilities.
1704
- * @returns Cancels a booking by UID.
1705
- *
1706
- * @see https://cal.com/docs/api-reference/v2/bookings/cancel-a-booking
1707
- *
1708
- * @example
1709
- * ```ts
1710
- * await cancelBooking(context)({ uid: 'abc-123-uid', cancellationReason: 'Schedule conflict' });
1711
- * ```
1712
- */ function cancelBooking(context) {
1713
- return function(input) {
1714
- var body = {};
1715
- if (input.cancellationReason) {
1716
- body['cancellationReason'] = input.cancellationReason;
1717
- }
1718
- return context.fetchJson("/bookings/".concat(input.uid, "/cancel"), {
1719
- method: 'POST',
1720
- headers: calcomApiVersionHeaders(CALCOM_API_VERSION_BOOKINGS),
1721
- body: JSON.stringify(body)
1722
- });
1723
- };
1724
- }
1725
-
1726
- /**
1727
- * Retrieves all event types for the authenticated user.
1728
- *
1729
- * @param context - The Cal.com API context providing authentication and fetch capabilities.
1730
- * @returns Retrieves all event types.
1731
- *
1732
- * @see https://cal.com/docs/api-reference/v2/event-types/get-all-event-types
1733
- *
1734
- * @example
1735
- * ```ts
1736
- * const response = await getEventTypes(context)();
1737
- * response.data.forEach(et => console.log(et.title, et.slug, et.lengthInMinutes));
1738
- * ```
1739
- */ function getEventTypes(context) {
1740
- return function() {
1741
- return context.fetchJson('/event-types', {
1742
- method: 'GET',
1743
- headers: calcomApiVersionHeaders(CALCOM_API_VERSION_EVENT_TYPES)
1744
- });
1745
- };
1746
- }
1747
- /**
1748
- * Creates a new event type for the authenticated user.
1749
- *
1750
- * @param context - The Cal.com API context providing authentication and fetch capabilities.
1751
- * @returns Creates a new event type from the given input.
1752
- *
1753
- * @see https://cal.com/docs/api-reference/v2/event-types/create-an-event-type
1754
- *
1755
- * @example
1756
- * ```ts
1757
- * const response = await createEventType(context)({
1758
- * title: 'Mentoring Session',
1759
- * slug: 'mentoring-session',
1760
- * lengthInMinutes: 30
1761
- * });
1762
- * console.log(response.data.id);
1763
- * ```
1764
- *
1765
- * @__NO_SIDE_EFFECTS__
1766
- */ function createEventType(context) {
1767
- return function(input) {
1768
- return context.fetchJson('/event-types', {
1769
- method: 'POST',
1770
- headers: calcomApiVersionHeaders(CALCOM_API_VERSION_EVENT_TYPES),
1771
- body: JSON.stringify(input)
1772
- });
1773
- };
1774
- }
1775
- /**
1776
- * Updates an existing event type by ID.
1777
- *
1778
- * @param context - The Cal.com API context providing authentication and fetch capabilities.
1779
- * @returns Updates an event type by ID.
1780
- *
1781
- * @see https://cal.com/docs/api-reference/v2/event-types/update-an-event-type
1782
- *
1783
- * @example
1784
- * ```ts
1785
- * await updateEventType(context)(12345, { title: 'Updated Session Title' });
1786
- * ```
1787
- */ function updateEventType(context) {
1788
- return function(eventTypeId, input) {
1789
- return context.fetchJson("/event-types/".concat(eventTypeId), {
1790
- method: 'PATCH',
1791
- headers: calcomApiVersionHeaders(CALCOM_API_VERSION_EVENT_TYPES),
1792
- body: JSON.stringify(input)
1793
- });
1794
- };
1795
- }
1796
- /**
1797
- * Deletes an event type by ID.
1798
- *
1799
- * @param context - The Cal.com API context providing authentication and fetch capabilities.
1800
- * @returns Deletes an event type by ID.
1801
- *
1802
- * @see https://cal.com/docs/api-reference/v2/event-types/delete-an-event-type
1803
- *
1804
- * @example
1805
- * ```ts
1806
- * await deleteEventType(context)(12345);
1807
- * ```
1808
- */ function deleteEventType(context) {
1809
- return function(eventTypeId) {
1810
- return context.fetchJson("/event-types/".concat(eventTypeId), {
1811
- method: 'DELETE',
1812
- headers: calcomApiVersionHeaders(CALCOM_API_VERSION_EVENT_TYPES)
1813
- });
1814
- };
1815
- }
1816
-
1817
- function asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, key, arg) {
1818
- try {
1819
- var info = gen[key](arg);
1820
- var value = info.value;
1821
- } catch (error) {
1822
- reject(error);
1823
- return;
1824
- }
1825
- if (info.done) {
1826
- resolve(value);
1827
- } else {
1828
- Promise.resolve(value).then(_next, _throw);
1829
- }
1830
- }
1831
- function _async_to_generator$1(fn) {
1832
- return function() {
1833
- var self = this, args = arguments;
1834
- return new Promise(function(resolve, reject) {
1835
- var gen = fn.apply(self, args);
1836
- function _next(value) {
1837
- asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, "next", value);
1838
- }
1839
- function _throw(err) {
1840
- asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, "throw", err);
1841
- }
1842
- _next(undefined);
1843
- });
1844
- };
1845
- }
1846
- function _define_property(obj, key, value) {
1847
- if (key in obj) {
1848
- Object.defineProperty(obj, key, {
1849
- value: value,
1850
- enumerable: true,
1851
- configurable: true,
1852
- writable: true
1853
- });
1854
- } else {
1855
- obj[key] = value;
1856
- }
1857
- return obj;
1858
- }
1859
- function _object_spread(target) {
1860
- for(var i = 1; i < arguments.length; i++){
1861
- var source = arguments[i] != null ? arguments[i] : {};
1862
- var ownKeys = Object.keys(source);
1863
- if (typeof Object.getOwnPropertySymbols === "function") {
1864
- ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
1865
- return Object.getOwnPropertyDescriptor(source, sym).enumerable;
1866
- }));
1867
- }
1868
- ownKeys.forEach(function(key) {
1869
- _define_property(target, key, source[key]);
1870
- });
1871
- }
1872
- return target;
1873
- }
1874
- function ownKeys(object, enumerableOnly) {
1875
- var keys = Object.keys(object);
1876
- if (Object.getOwnPropertySymbols) {
1877
- var symbols = Object.getOwnPropertySymbols(object);
1878
- keys.push.apply(keys, symbols);
1879
- }
1880
- return keys;
1881
- }
1882
- function _object_spread_props(target, source) {
1883
- source = source != null ? source : {};
1884
- if (Object.getOwnPropertyDescriptors) {
1885
- Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
1886
- } else {
1887
- ownKeys(Object(source)).forEach(function(key) {
1888
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
1889
- });
1890
- }
1891
- return target;
1892
- }
1893
- function _ts_generator$1(thisArg, body) {
1894
- var f, y, t, _ = {
1895
- label: 0,
1896
- sent: function() {
1897
- if (t[0] & 1) throw t[1];
1898
- return t[1];
1899
- },
1900
- trys: [],
1901
- ops: []
1902
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
1903
- return d(g, "next", {
1904
- value: verb(0)
1905
- }), d(g, "throw", {
1906
- value: verb(1)
1907
- }), d(g, "return", {
1908
- value: verb(2)
1909
- }), typeof Symbol === "function" && d(g, Symbol.iterator, {
1910
- value: function() {
1911
- return this;
1912
- }
1913
- }), g;
1914
- function verb(n) {
1915
- return function(v) {
1916
- return step([
1917
- n,
1918
- v
1919
- ]);
1920
- };
1921
- }
1922
- function step(op) {
1923
- if (f) throw new TypeError("Generator is already executing.");
1924
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
1925
- 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;
1926
- if (y = 0, t) op = [
1927
- op[0] & 2,
1928
- t.value
1929
- ];
1930
- switch(op[0]){
1931
- case 0:
1932
- case 1:
1933
- t = op;
1934
- break;
1935
- case 4:
1936
- _.label++;
1937
- return {
1938
- value: op[1],
1939
- done: false
1940
- };
1941
- case 5:
1942
- _.label++;
1943
- y = op[1];
1944
- op = [
1945
- 0
1946
- ];
1947
- continue;
1948
- case 7:
1949
- op = _.ops.pop();
1950
- _.trys.pop();
1951
- continue;
1952
- default:
1953
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
1954
- _ = 0;
1955
- continue;
1956
- }
1957
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
1958
- _.label = op[1];
1959
- break;
1960
- }
1961
- if (op[0] === 6 && _.label < t[1]) {
1962
- _.label = t[1];
1963
- t = op;
1964
- break;
1965
- }
1966
- if (t && _.label < t[2]) {
1967
- _.label = t[2];
1968
- _.ops.push(op);
1969
- break;
1970
- }
1971
- if (t[2]) _.ops.pop();
1972
- _.trys.pop();
1973
- continue;
1974
- }
1975
- op = body.call(thisArg, _);
1976
- } catch (e) {
1977
- op = [
1978
- 6,
1979
- e
1980
- ];
1981
- y = 0;
1982
- } finally{
1983
- f = t = 0;
1984
- }
1985
- if (op[0] & 5) throw op[1];
1986
- return {
1987
- value: op[0] ? op[1] : void 0,
1988
- done: true
1989
- };
1990
- }
1991
- }
1992
- /**
1993
- * Retrieves all connected calendars and the destination calendar for the authenticated user.
1994
- *
1995
- * @param context - The Cal.com API context providing authentication and fetch capabilities.
1996
- * @returns Retrieves all connected calendars.
1997
- *
1998
- * @see https://cal.com/docs/api-reference/v2/calendars/get-all-calendars
1999
- *
2000
- * @example
2001
- * ```ts
2002
- * const response = await getCalendars(context)();
2003
- * response.data.connectedCalendars.forEach(cc => console.log(cc.integration.slug, cc.calendars.length));
2004
- * ```
2005
- */ function getCalendars(context) {
2006
- return function() {
2007
- return context.fetchJson('/calendars', {
2008
- method: 'GET',
2009
- headers: calcomApiVersionHeaders(CALCOM_API_VERSION_CALENDARS)
2010
- });
2011
- };
2012
- }
2013
- /**
2014
- * Selects the calendars to load busy times from, out of a set of connected calendars.
2015
- *
2016
- * Prefers the calendars Cal.com is configured to check for conflicts (`isSelected`), and falls
2017
- * back to a connection's primary calendar when that connection has nothing selected.
2018
- *
2019
- * @param connectedCalendars - The connected calendars to select from.
2020
- * @returns The calendars to load.
2021
- */ function calcomCalendarsToLoadFromConnectedCalendars(connectedCalendars) {
2022
- return connectedCalendars.flatMap(function(connection) {
2023
- var selectedCalendars = connection.calendars.filter(function(x) {
2024
- return x.isSelected;
2025
- });
2026
- var primaryCalendars = connection.primary ? [
2027
- connection.primary
2028
- ] : [];
2029
- var calendars = selectedCalendars.length > 0 ? selectedCalendars : primaryCalendars;
2030
- return calendars.map(function(x) {
2031
- return {
2032
- credentialId: x.credentialId,
2033
- externalId: x.externalId
2034
- };
2035
- });
2036
- });
2037
- }
2038
- /**
2039
- * Retrieves busy time ranges across the given calendars for a date range.
2040
- *
2041
- * A caller cannot address this endpoint without first knowing its calendars, so this is the
2042
- * single-request primitive — see {@link getBusyTimesForConnectedCalendars} to resolve them too.
2043
- *
2044
- * @param context - The Cal.com API context providing authentication and fetch capabilities.
2045
- * @returns Retrieves busy time ranges for a date range.
2046
- *
2047
- * @see https://cal.com/docs/api-reference/v2/calendars/get-busy-times
2048
- *
2049
- * @example
2050
- * ```ts
2051
- * const response = await getBusyTimes(context)({
2052
- * dateFrom: '2026-03-17',
2053
- * dateTo: '2026-03-24',
2054
- * timeZone: 'America/Chicago',
2055
- * calendarsToLoad: [{ credentialId: 1845764, externalId: 'someone@example.com' }]
2056
- * });
2057
- * response.data.forEach(bt => console.log(bt.start, bt.end));
2058
- * ```
2059
- */ function getBusyTimes(context) {
2060
- return function(input) {
2061
- var params = fetch.makeUrlSearchParams({
2062
- timeZone: input.timeZone,
2063
- loggedInUsersTz: input.loggedInUsersTz,
2064
- dateFrom: input.dateFrom,
2065
- dateTo: input.dateTo,
2066
- calendarsToLoad: input.calendarsToLoad
2067
- }, {
2068
- useBracketNotation: true
2069
- });
2070
- return context.fetchJson("/calendars/busy-times?".concat(params), {
2071
- method: 'GET',
2072
- headers: calcomApiVersionHeaders(CALCOM_API_VERSION_CALENDARS)
2073
- });
2074
- };
2075
- }
2076
- /**
2077
- * Retrieves busy time ranges across the user's connected calendars for a date range.
2078
- *
2079
- * Convenience over {@link getBusyTimes}: loads the connected calendars first and derives
2080
- * `calendarsToLoad` via {@link calcomCalendarsToLoadFromConnectedCalendars}, so a caller does not
2081
- * have to know Cal.com's `isSelected`/primary selection rule. Issues two requests.
2082
- *
2083
- * @param context - The Cal.com API context providing authentication and fetch capabilities.
2084
- * @returns Retrieves busy time ranges across the user's connected calendars.
2085
- *
2086
- * @example
2087
- * ```ts
2088
- * const response = await getBusyTimesForConnectedCalendars(context)({
2089
- * dateFrom: '2026-03-17',
2090
- * dateTo: '2026-03-24',
2091
- * loggedInUsersTz: 'UTC'
2092
- * });
2093
- * ```
2094
- */ function getBusyTimesForConnectedCalendars(context) {
2095
- return function(input) {
2096
- return _async_to_generator$1(function() {
2097
- var calendarsResponse, calendarsToLoad;
2098
- return _ts_generator$1(this, function(_state) {
2099
- switch(_state.label){
2100
- case 0:
2101
- return [
2102
- 4,
2103
- getCalendars(context)()
2104
- ];
2105
- case 1:
2106
- calendarsResponse = _state.sent();
2107
- calendarsToLoad = calcomCalendarsToLoadFromConnectedCalendars(calendarsResponse.data.connectedCalendars);
2108
- return [
2109
- 2,
2110
- getBusyTimes(context)(_object_spread_props(_object_spread({}, input), {
2111
- calendarsToLoad: calendarsToLoad
2112
- }))
2113
- ];
2114
- }
2115
- });
2116
- })();
2117
- };
2118
- }
2119
-
2120
- /**
2121
- * All {@link CalcomWebhookTimeRelativeTrigger} values.
2122
- */ var ALL_CALCOM_WEBHOOK_TIME_RELATIVE_TRIGGERS = [
2123
- 'AFTER_HOSTS_CAL_VIDEO_NO_SHOW',
2124
- 'AFTER_GUESTS_CAL_VIDEO_NO_SHOW'
2125
- ];
2126
- /**
2127
- * All {@link CalcomWebhookVersion} values, oldest first.
2128
- */ var ALL_CALCOM_WEBHOOK_VERSIONS = [
2129
- '2021-10-20',
2130
- '2026-07-27'
2131
- ];
2132
- /**
2133
- * All {@link CalcomWebhookTimeUnit} values, smallest first.
2134
- */ var ALL_CALCOM_WEBHOOK_TIME_UNITS = [
2135
- 'MINUTE',
2136
- 'HOUR',
2137
- 'DAY'
2138
- ];
2139
- /**
2140
- * Maps each {@link CalcomWebhookTimeUnit} to the equivalent `@dereekb/util` {@link TimeUnit}.
2141
- */ var CALCOM_WEBHOOK_TIME_UNIT_TIME_UNIT_MAP = {
2142
- MINUTE: 'min',
2143
- HOUR: 'h',
2144
- DAY: 'd'
2145
- };
2146
- /**
2147
- * Converts a Cal.com webhook time offset to a `@dereekb/util` {@link TimeDuration}, so the
2148
- * duration utilities (`timeDurationToMilliseconds()`, `convertTimeDuration()`, ...) apply to it.
2149
- *
2150
- * @param offset - The webhook time offset to convert.
2151
- * @returns The equivalent TimeDuration.
2152
- *
2153
- * @example
2154
- * ```ts
2155
- * timeDurationToMilliseconds(calcomWebhookTimeOffsetToTimeDuration({ time: 5, timeUnit: 'MINUTE' })); // 300000
2156
- * ```
2157
- *
2158
- * @__NO_SIDE_EFFECTS__
2159
- */ function calcomWebhookTimeOffsetToTimeDuration(offset) {
2160
- return {
2161
- amount: offset.time,
2162
- unit: CALCOM_WEBHOOK_TIME_UNIT_TIME_UNIT_MAP[offset.timeUnit]
2163
- };
2164
- }
2165
- /**
2166
- * Reads a webhook's {@link CalcomWebhookTimeOffset} out of the sibling `time`/`timeUnit` fields.
2167
- *
2168
- * Returns undefined unless both halves are present, as the API returns them null on a webhook
2169
- * with no {@link CalcomWebhookTimeRelativeTrigger} and a magnitude with no unit means nothing.
2170
- *
2171
- * @param webhook - The webhook to read the offset from.
2172
- * @returns The webhook's time offset, or undefined when it has none.
2173
- *
2174
- * @__NO_SIDE_EFFECTS__
2175
- */ function calcomWebhookTimeOffsetFromWebhook(webhook) {
2176
- var time = webhook.time, timeUnit = webhook.timeUnit;
2177
- return time != null && timeUnit != null ? {
2178
- time: time,
2179
- timeUnit: timeUnit
2180
- } : undefined;
2181
- }
2182
- /**
2183
- * Creates a webhook subscription for the authenticated user. Webhooks notify your app
2184
- * when specified events occur (e.g., bookings created, cancelled, rescheduled).
2185
- *
2186
- * @param context - The Cal.com API context providing authentication and fetch capabilities.
2187
- * @returns Creates a webhook subscription from the given input.
2188
- *
2189
- * @see https://cal.com/docs/api-reference/v2/webhooks/create-a-webhook
2190
- *
2191
- * @example
2192
- * ```ts
2193
- * const response = await createWebhook(context)({
2194
- * subscriberUrl: 'https://example.com/webhook/calcom',
2195
- * triggers: ['BOOKING_CREATED', 'BOOKING_CANCELLED'],
2196
- * active: true
2197
- * });
2198
- * console.log(response.data.id);
2199
- * ```
2200
- *
2201
- * @__NO_SIDE_EFFECTS__
2202
- */ function createWebhook(context) {
2203
- return function(input) {
2204
- return context.fetchJson('/webhooks', {
2205
- method: 'POST',
2206
- body: JSON.stringify(input)
2207
- });
2208
- };
2209
- }
2210
- /**
2211
- * Retrieves all webhooks for the authenticated user.
2212
- *
2213
- * @param context - The Cal.com API context providing authentication and fetch capabilities.
2214
- * @returns Retrieves all webhooks.
2215
- *
2216
- * @see https://cal.com/docs/api-reference/v2/webhooks/get-all-webhooks
2217
- *
2218
- * @example
2219
- * ```ts
2220
- * const response = await getWebhooks(context)();
2221
- * response.data.forEach(wh => console.log(wh.subscriberUrl, wh.triggers));
2222
- * ```
2223
- */ function getWebhooks(context) {
2224
- return function() {
2225
- return context.fetchJson('/webhooks', {
2226
- method: 'GET'
2227
- });
2228
- };
2229
- }
2230
- /**
2231
- * Retrieves a specific webhook by ID.
2232
- *
2233
- * @param context - The Cal.com API context providing authentication and fetch capabilities.
2234
- * @returns Retrieves a specific webhook by ID.
2235
- *
2236
- * @see https://cal.com/docs/api-reference/v2/webhooks/get-a-webhook
2237
- *
2238
- * @example
2239
- * ```ts
2240
- * const response = await getWebhook(context)(42);
2241
- * console.log(response.data.subscriberUrl);
2242
- * ```
2243
- */ function getWebhook(context) {
2244
- return function(webhookId) {
2245
- return context.fetchJson("/webhooks/".concat(webhookId), {
2246
- method: 'GET'
2247
- });
2248
- };
2249
- }
2250
- /**
2251
- * Updates an existing webhook by ID.
2252
- *
2253
- * @param context - The Cal.com API context providing authentication and fetch capabilities.
2254
- * @returns Updates an existing webhook by ID.
2255
- *
2256
- * @see https://cal.com/docs/api-reference/v2/webhooks/update-a-webhook
2257
- *
2258
- * @example
2259
- * ```ts
2260
- * await updateWebhook(context)(42, { active: false });
2261
- * ```
2262
- */ function updateWebhook(context) {
2263
- return function(webhookId, input) {
2264
- return context.fetchJson("/webhooks/".concat(webhookId), {
2265
- method: 'PATCH',
2266
- body: JSON.stringify(input)
2267
- });
2268
- };
2269
- }
2270
- /**
2271
- * Deletes a webhook by ID.
2272
- *
2273
- * @param context - The Cal.com API context providing authentication and fetch capabilities.
2274
- * @returns Deletes a webhook by ID.
2275
- *
2276
- * @see https://cal.com/docs/api-reference/v2/webhooks/delete-a-webhook
2277
- *
2278
- * @example
2279
- * ```ts
2280
- * await deleteWebhook(context)(42);
2281
- * ```
2282
- */ function deleteWebhook(context) {
2283
- return function(webhookId) {
2284
- return context.fetchJson("/webhooks/".concat(webhookId), {
2285
- method: 'DELETE'
2286
- });
2287
- };
2288
- }
2289
-
2290
- /**
2291
- * The Cal.com OAuth API base URL.
2292
- *
2293
- * Endpoint paths are appended to this base, so it intentionally carries no endpoint segment of
2294
- * its own. This is the single place the OAuth host and prefix are encoded.
2295
- */ var CALCOM_OAUTH_API_URL = 'https://api.cal.com/v2/auth/oauth2';
2296
- /**
2297
- * The Cal.com OAuth token endpoint path, relative to {@link CALCOM_OAUTH_API_URL}.
2298
- */ var CALCOM_OAUTH_TOKEN_PATH = '/token';
2299
- /**
2300
- * The Cal.com OAuth authorize URL.
2301
- */ var CALCOM_OAUTH_AUTHORIZE_URL = 'https://app.cal.com/auth/oauth2/authorize';
2302
- /**
2303
- * Returns whether the credential is a {@link CalcomApiKeyCredential}.
2304
- *
2305
- * @param credential - The credential to check.
2306
- * @returns True when the credential carries an api key.
2307
- *
2308
- * @__NO_SIDE_EFFECTS__
2309
- */ function isCalcomApiKeyCredential(credential) {
2310
- return 'apiKey' in credential;
2311
- }
2312
- /**
2313
- * Builds a {@link CalcomAuthCredential} from flat, optional values, as an environment-facing
2314
- * configuration provides them.
2315
- *
2316
- * An api key wins when both are present: it does not expire, so it skips the refresh loop entirely.
2317
- * The cache attaches only to the refresh-token arm, since an api key has no token to cache. Empty
2318
- * strings count as absent, so an unset environment variable read as `''` does not become a
2319
- * credential that sends `Bearer `.
2320
- *
2321
- * @param values - The flat credential values.
2322
- * @returns The equivalent credential, or undefined when neither value is present.
2323
- *
2324
- * @__NO_SIDE_EFFECTS__
2325
- */ function calcomAuthCredentialFromValues(values) {
2326
- var apiKey = values.apiKey, refreshToken = values.refreshToken, accessTokenCache = values.accessTokenCache;
2327
- var result;
2328
- if (apiKey) {
2329
- result = {
2330
- apiKey: apiKey
2331
- };
2332
- } else if (refreshToken) {
2333
- result = {
2334
- refreshToken: refreshToken,
2335
- accessTokenCache: accessTokenCache
2336
- };
2337
- }
2338
- return result;
2339
- }
2340
- // COMPAT: Deprecated aliases
2341
- /**
2342
- * @deprecated use {@link CALCOM_OAUTH_API_URL} instead. This was previously used as the fetch base
2343
- * URL while the endpoint path `/oauth/token` was also appended, resolving to a doubly-pathed URL.
2344
- */ var CALCOM_OAUTH_TOKEN_URL = "".concat(CALCOM_OAUTH_API_URL).concat(CALCOM_OAUTH_TOKEN_PATH);
2345
-
2346
- /**
2347
- * Refreshes an access token using a refresh token. Cal.com rotates refresh tokens
2348
- * on every use, so the new `refresh_token` from the response must be persisted.
2349
- *
2350
- * Cal.com uses JSON body (not Basic Auth) for token requests.
2351
- *
2352
- * @param context - The Cal.com OAuth context providing client credentials and fetch capabilities.
2353
- * @returns Refreshes an access token using the given refresh token.
2354
- *
2355
- * @see https://cal.com/docs/api-reference/v2/oauth/refresh-an-existing-access-token
2356
- *
2357
- * @example
2358
- * ```ts
2359
- * const response = await refreshAccessToken(context)({ refreshToken: 'existing-refresh-token' });
2360
- * console.log(response.access_token, response.refresh_token);
2361
- * ```
2362
- */ function refreshAccessToken(context) {
2363
- var client = context.config.client;
2364
- return function(input) {
2365
- var fetchJsonInput = {
2366
- method: 'POST',
2367
- body: JSON.stringify({
2368
- grant_type: 'refresh_token',
2369
- client_id: client === null || client === void 0 ? void 0 : client.clientId,
2370
- client_secret: client === null || client === void 0 ? void 0 : client.clientSecret,
2371
- refresh_token: input.refreshToken
2372
- })
2373
- };
2374
- return context.fetchJson(CALCOM_OAUTH_TOKEN_PATH, fetchJsonInput);
2375
- };
2376
- }
2377
- /**
2378
- * Exchanges an OAuth authorization code for access and refresh tokens.
2379
- * Used during the initial OAuth flow when a user authorizes your app.
2380
- *
2381
- * Cal.com uses JSON body (not Basic Auth) for token requests.
2382
- *
2383
- * @param context - The Cal.com OAuth context providing client credentials and fetch capabilities.
2384
- * @returns Exchanges an authorization code for access and refresh tokens.
2385
- *
2386
- * @see https://cal.com/docs/api-reference/v2/oauth/exchange-an-authorization-code-for-access-tokens
2387
- *
2388
- * @example
2389
- * ```ts
2390
- * const response = await exchangeAuthorizationCode(context)({
2391
- * code: 'auth-code-from-redirect',
2392
- * redirectUri: 'https://example.com/callback'
2393
- * });
2394
- * console.log(response.access_token, response.refresh_token);
2395
- * ```
2396
- */ function exchangeAuthorizationCode(context) {
2397
- var client = context.config.client;
2398
- return function(input) {
2399
- var fetchJsonInput = {
2400
- method: 'POST',
2401
- body: JSON.stringify({
2402
- grant_type: 'authorization_code',
2403
- client_id: client === null || client === void 0 ? void 0 : client.clientId,
2404
- client_secret: client === null || client === void 0 ? void 0 : client.clientSecret,
2405
- code: input.code,
2406
- redirect_uri: input.redirectUri
2407
- })
2408
- };
2409
- return context.fetchJson(CALCOM_OAUTH_TOKEN_PATH, fetchJsonInput);
2410
- };
2411
- }
2412
-
2413
- /**
2414
- * Every granular Cal.com OAuth scope.
2415
- *
2416
- * A runtime list rather than a bare type union, so a configured scope can be validated instead of
2417
- * being passed through to the consent screen and refused there.
2418
- *
2419
- * @see https://cal.com/docs/api-reference/v2/oauth
2420
- */ var ALL_CALCOM_OAUTH_SCOPES = [
2421
- 'PROFILE_READ',
2422
- 'PROFILE_WRITE',
2423
- 'BOOKING_READ',
2424
- 'BOOKING_WRITE',
2425
- 'SCHEDULE_READ',
2426
- 'SCHEDULE_WRITE',
2427
- 'EVENT_TYPE_READ',
2428
- 'EVENT_TYPE_WRITE',
2429
- 'APPS_READ',
2430
- 'APPS_WRITE',
2431
- 'WEBHOOK_READ',
2432
- 'WEBHOOK_WRITE'
2433
- ];
2434
- /**
2435
- * Returns whether the input is a known {@link CalcomOAuthScope}.
2436
- *
2437
- * @param value - The value to check.
2438
- * @returns True when the value is a known Cal.com OAuth scope.
2439
- */ function isCalcomOAuthScope(value) {
2440
- return ALL_CALCOM_OAUTH_SCOPES.includes(value);
2441
- }
2442
- /**
2443
- * The delimiter used to join scopes in the `scope` query parameter.
2444
- *
2445
- * OAuth2 specifies a space-delimited list. Cal.com's granular scopes are documented without an
2446
- * explicit delimiter, so this is isolated here: if the consent screen rejects the `scope`
2447
- * parameter, this is the only value that needs to change.
2448
- */ var CALCOM_OAUTH_SCOPE_DELIMITER = ' ';
2449
- /**
2450
- * The `response_type` used by the authorization-code flow.
2451
- */ var CALCOM_OAUTH_AUTHORIZE_RESPONSE_TYPE = 'code';
2452
- /**
2453
- * Creates a {@link CalcomOAuthAuthorizeUrlFactory} that composes the Cal.com authorize URL that a
2454
- * user's browser is redirected to in order to begin the authorization-code flow.
2455
- *
2456
- * The client id, redirect URI, and scopes are fixed by the config, since a consumer holds those
2457
- * constant and varies only the per-request `state`.
2458
- *
2459
- * @param config - The client id, redirect URI, and scopes to request.
2460
- * @returns A factory that builds an authorize URL for the given params.
2461
- *
2462
- * @see https://cal.com/docs/api-reference/v2/oauth
2463
- *
2464
- * @example
2465
- * ```ts
2466
- * const authorizeUrlFactory = calcomOAuthAuthorizeUrlFactory({
2467
- * clientId: 'client-id',
2468
- * redirectUri: 'http://localhost:9901/oauth/calcom/callback',
2469
- * scopes: ['PROFILE_READ', 'BOOKING_READ']
2470
- * });
2471
- *
2472
- * const url = authorizeUrlFactory({ state: 'signed-state' });
2473
- * ```
2474
- *
2475
- * @__NO_SIDE_EFFECTS__
2476
- */ function calcomOAuthAuthorizeUrlFactory(config) {
2477
- var clientId = config.clientId, redirectUri = config.redirectUri, scopes = config.scopes, inputAuthorizeUrl = config.authorizeUrl;
2478
- var authorizeUrl = inputAuthorizeUrl !== null && inputAuthorizeUrl !== void 0 ? inputAuthorizeUrl : CALCOM_OAUTH_AUTHORIZE_URL;
2479
- var scope = scopes.join(CALCOM_OAUTH_SCOPE_DELIMITER);
2480
- return function(params) {
2481
- var url = new URL(authorizeUrl);
2482
- var state = params === null || params === void 0 ? void 0 : params.state;
2483
- url.searchParams.set('client_id', clientId);
2484
- url.searchParams.set('redirect_uri', redirectUri);
2485
- url.searchParams.set('response_type', CALCOM_OAUTH_AUTHORIZE_RESPONSE_TYPE);
2486
- url.searchParams.set('scope', scope);
2487
- if (state != null) {
2488
- url.searchParams.set('state', state);
2489
- }
2490
- return url.toString();
2491
- };
2492
- }
2493
-
2494
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
2495
- try {
2496
- var info = gen[key](arg);
2497
- var value = info.value;
2498
- } catch (error) {
2499
- reject(error);
2500
- return;
2501
- }
2502
- if (info.done) {
2503
- resolve(value);
2504
- } else {
2505
- Promise.resolve(value).then(_next, _throw);
2506
- }
2507
- }
2508
- function _async_to_generator(fn) {
2509
- return function() {
2510
- var self = this, args = arguments;
2511
- return new Promise(function(resolve, reject) {
2512
- var gen = fn.apply(self, args);
2513
- function _next(value) {
2514
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
2515
- }
2516
- function _throw(err) {
2517
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
2518
- }
2519
- _next(undefined);
2520
- });
2521
- };
2522
- }
2523
- function _ts_generator(thisArg, body) {
2524
- var f, y, t, _ = {
2525
- label: 0,
2526
- sent: function() {
2527
- if (t[0] & 1) throw t[1];
2528
- return t[1];
2529
- },
2530
- trys: [],
2531
- ops: []
2532
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
2533
- return d(g, "next", {
2534
- value: verb(0)
2535
- }), d(g, "throw", {
2536
- value: verb(1)
2537
- }), d(g, "return", {
2538
- value: verb(2)
2539
- }), typeof Symbol === "function" && d(g, Symbol.iterator, {
2540
- value: function() {
2541
- return this;
2542
- }
2543
- }), g;
2544
- function verb(n) {
2545
- return function(v) {
2546
- return step([
2547
- n,
2548
- v
2549
- ]);
2550
- };
2551
- }
2552
- function step(op) {
2553
- if (f) throw new TypeError("Generator is already executing.");
2554
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
2555
- 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;
2556
- if (y = 0, t) op = [
2557
- op[0] & 2,
2558
- t.value
2559
- ];
2560
- switch(op[0]){
2561
- case 0:
2562
- case 1:
2563
- t = op;
2564
- break;
2565
- case 4:
2566
- _.label++;
2567
- return {
2568
- value: op[1],
2569
- done: false
2570
- };
2571
- case 5:
2572
- _.label++;
2573
- y = op[1];
2574
- op = [
2575
- 0
2576
- ];
2577
- continue;
2578
- case 7:
2579
- op = _.ops.pop();
2580
- _.trys.pop();
2581
- continue;
2582
- default:
2583
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
2584
- _ = 0;
2585
- continue;
2586
- }
2587
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
2588
- _.label = op[1];
2589
- break;
2590
- }
2591
- if (op[0] === 6 && _.label < t[1]) {
2592
- _.label = t[1];
2593
- t = op;
2594
- break;
2595
- }
2596
- if (t && _.label < t[2]) {
2597
- _.label = t[2];
2598
- _.ops.push(op);
2599
- break;
2600
- }
2601
- if (t[2]) _.ops.pop();
2602
- _.trys.pop();
2603
- continue;
2604
- }
2605
- op = body.call(thisArg, _);
2606
- } catch (e) {
2607
- op = [
2608
- 6,
2609
- e
2610
- ];
2611
- y = 0;
2612
- } finally{
2613
- f = t = 0;
2614
- }
2615
- if (op[0] & 5) throw op[1];
2616
- return {
2617
- value: op[0] ? op[1] : void 0,
2618
- done: true
2619
- };
2620
- }
2621
- }
2622
- /**
2623
- * Maps a {@link CalcomOAuthTokenResponse} to a {@link CalcomAccessToken}.
2624
- *
2625
- * Pure: the caller owns the rotated refresh token that comes back on the result, so each token
2626
- * scope (server-level vs per-user) tracks its own rotation instead of sharing one variable.
2627
- *
2628
- * @param response - The token response returned by the Cal.com token endpoint.
2629
- * @returns The equivalent CalcomAccessToken, with `expiresAt` resolved against the current time.
2630
- *
2631
- * @__NO_SIDE_EFFECTS__
2632
- */ function calcomAccessTokenFromTokenResponse(response) {
2633
- var createdAt = Date.now();
2634
- var access_token = response.access_token, refresh_token = response.refresh_token, scope = response.scope, expires_in = response.expires_in;
2635
- var accessToken = {
2636
- accessToken: access_token,
2637
- refreshToken: refresh_token,
2638
- expiresIn: expires_in,
2639
- expiresAt: new Date(createdAt + expires_in * util.MS_IN_SECOND),
2640
- scope: scope !== null && scope !== void 0 ? scope : ''
2641
- };
2642
- return accessToken;
2643
- }
2644
- /**
2645
- * The lifetime given to the synthetic access token an api key is wrapped in.
2646
- *
2647
- * Cal.com api keys do not expire; the value only has to outlive any process holding one, so the
2648
- * token satisfies the same expiration check every other token goes through.
2649
- */ var CALCOM_API_KEY_ACCESS_TOKEN_EXPIRATION = util.MS_IN_DAY * 365 * 100;
2650
- /**
2651
- * Wraps a {@link CalcomApiKey} as a static {@link CalcomAccessToken}.
2652
- *
2653
- * An api key is already a bearer token acting as the user who created it, so there is nothing to
2654
- * exchange and nothing to refresh.
2655
- *
2656
- * @param apiKey - The Cal.com api key.
2657
- * @returns The equivalent static CalcomAccessToken.
2658
- *
2659
- * @__NO_SIDE_EFFECTS__
2660
- */ function calcomAccessTokenFromApiKey(apiKey) {
2661
- var accessToken = {
2662
- accessToken: apiKey,
2663
- refreshToken: '',
2664
- expiresIn: Number.MAX_SAFE_INTEGER,
2665
- expiresAt: new Date(Date.now() + CALCOM_API_KEY_ACCESS_TOKEN_EXPIRATION),
2666
- scope: ''
2667
- };
2668
- return accessToken;
2669
- }
2670
- /**
2671
- * Creates a {@link CalcomOAuthFactory} that produces configured Cal.com OAuth instances.
2672
- * Supports both API key authentication (static token, no refresh) and full OAuth
2673
- * refresh token flow with automatic token rotation.
2674
- *
2675
- * @param factoryConfig - Configuration including optional fetch factory and error logging.
2676
- * @returns A factory function that accepts a CalcomOAuthConfig and produces a CalcomOAuth instance.
2677
- *
2678
- * @__NO_SIDE_EFFECTS__
2679
- */ function calcomOAuthFactory(factoryConfig) {
2680
- var _factoryConfig_fetchHandler;
2681
- var fetchHandler = (_factoryConfig_fetchHandler = factoryConfig.fetchHandler) !== null && _factoryConfig_fetchHandler !== void 0 ? _factoryConfig_fetchHandler : calcomRateLimitedFetchHandler();
2682
- var logCalcomServerErrorFunction = factoryConfig.logCalcomServerErrorFunction, _factoryConfig_fetchFactory = factoryConfig.fetchFactory, fetchFactory = _factoryConfig_fetchFactory === void 0 ? function(_) {
2683
- return fetch.fetchApiFetchService.makeFetch({
2684
- baseUrl: CALCOM_OAUTH_API_URL,
2685
- baseRequest: {
2686
- headers: {
2687
- 'Content-Type': 'application/json'
2688
- }
2689
- },
2690
- fetchHandler: fetchHandler,
2691
- timeout: 20 * 1000,
2692
- requireOkResponse: true,
2693
- useTimeout: true // use timeout
2694
- });
2695
- } : _factoryConfig_fetchFactory;
2696
- return function(config) {
2697
- var defaultAuth = config.defaultAuth, client = config.client;
2698
- var hasApiKeyDefault = defaultAuth != null && isCalcomApiKeyCredential(defaultAuth) && !!defaultAuth.apiKey;
2699
- // an API key IS the token; every other credential is an exchange the token endpoint authenticates
2700
- // with the client id and secret. With neither, no token could ever be produced
2701
- if (!hasApiKeyDefault && client == null) {
2702
- throw new Error('CalcomOAuthConfig can authenticate nothing. Provide `defaultAuth: { apiKey }` for ambient calls, `client` (clientId+clientSecret) to exchange any refresh token, or both.');
2703
- }
2704
- var baseFetch = fetchFactory();
2705
- var fetch$1 = handleCalcomOAuthErrorFetch(baseFetch, logCalcomServerErrorFunction);
2706
- var fetchJson = fetch.fetchJsonFunction(fetch$1, {
2707
- handleFetchJsonParseErrorFunction: fetch.returnNullHandleFetchJsonParseErrorFunction
2708
- });
2709
- // MARK: Access Tokens
2710
- var makeAccessTokenFactory = function makeAccessTokenFactory(credential) {
2711
- var result;
2712
- if (isCalcomApiKeyCredential(credential)) {
2713
- var apiKey = credential.apiKey;
2714
- // presence, not truthiness, is what discriminates the union — so without this an empty key
2715
- // would be handed back as a valid static token and every call would send `Bearer `
2716
- if (!apiKey) {
2717
- throw new Error('CalcomApiKeyCredential.apiKey is empty.');
2718
- }
2719
- var apiKeyToken = calcomAccessTokenFromApiKey(apiKey);
2720
- result = function result() {
2721
- return _async_to_generator(function() {
2722
- return _ts_generator(this, function(_state) {
2723
- return [
2724
- 2,
2725
- apiKeyToken
2726
- ];
2727
- });
2728
- })();
2729
- };
2730
- } else {
2731
- // a token for a specific grant can only come from that grant's refresh token, exchanged
2732
- // against the OAuth client. An API key is a different user's identity and cannot stand in
2733
- if (client == null) {
2734
- 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.');
2735
- }
2736
- /**
2737
- * Tracks THIS credential's rotated refresh token, since Cal.com rotates on every use.
2738
- *
2739
- * Declared per invocation, so every credential — the default one as much as any per-user one
2740
- * — rotates in isolation and refreshing one never overwrites another's token.
2741
- */ var latestRefreshToken = credential.refreshToken;
2742
- var tokenRefresher = function tokenRefresher() {
2743
- return _async_to_generator(function() {
2744
- var response, accessToken;
2745
- return _ts_generator(this, function(_state) {
2746
- switch(_state.label){
2747
- case 0:
2748
- return [
2749
- 4,
2750
- refreshAccessToken(oauthContext)({
2751
- refreshToken: latestRefreshToken
2752
- })
2753
- ];
2754
- case 1:
2755
- response = _state.sent();
2756
- accessToken = calcomAccessTokenFromTokenResponse(response);
2757
- latestRefreshToken = accessToken.refreshToken;
2758
- return [
2759
- 2,
2760
- accessToken
2761
- ];
2762
- }
2763
- });
2764
- })();
2765
- };
2766
- result = calcomOAuthAccessTokenFactory({
2767
- tokenRefresher: tokenRefresher,
2768
- accessTokenCache: credential.accessTokenCache
2769
- });
2770
- }
2771
- return result;
2772
- };
2773
- // built once, so the default credential's in-memory tier and its rotation are shared across the
2774
- // whole context instead of restarting on every call
2775
- var loadAccessToken = defaultAuth == null ? function() {
2776
- return _async_to_generator(function() {
2777
- return _ts_generator(this, function(_state) {
2778
- 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.');
2779
- });
2780
- })();
2781
- } : makeAccessTokenFactory(defaultAuth);
2782
- var oauthContext = {
2783
- fetch: fetch$1,
2784
- fetchJson: fetchJson,
2785
- loadAccessToken: loadAccessToken,
2786
- makeAccessTokenFactory: makeAccessTokenFactory,
2787
- config: config
2788
- };
2789
- var calcomOAuth = {
2790
- oauthContext: oauthContext
2791
- };
2792
- return calcomOAuth;
2793
- };
2794
- }
2795
- /**
2796
- * Creates a CalcomAccessTokenFactory with multi-tier caching.
2797
- * Checks the in-memory cache first, then the external cache, and finally refreshes
2798
- * from the token refresher if no valid token is available.
2799
- *
2800
- * @param config - Configuration including the token refresher, optional cache, and expiration buffer.
2801
- * @returns A CalcomAccessTokenFactory that returns a valid access token on each call.
2802
- *
2803
- * @__NO_SIDE_EFFECTS__
2804
- */ function calcomOAuthAccessTokenFactory(config) {
2805
- var tokenRefresher = config.tokenRefresher, accessTokenCache = config.accessTokenCache, inputTokenExpirationBuffer = config.tokenExpirationBuffer;
2806
- var tokenExpirationBuffer = inputTokenExpirationBuffer !== null && inputTokenExpirationBuffer !== void 0 ? inputTokenExpirationBuffer : util.MS_IN_MINUTE;
2807
- /**
2808
- * Caches the token internally here until it expires.
2809
- */ var currentToken = null;
2810
- return function() {
2811
- return _async_to_generator(function() {
2812
- var cachedToken, isExpired, e;
2813
- return _ts_generator(this, function(_state) {
2814
- switch(_state.label){
2815
- case 0:
2816
- if (!!currentToken) return [
2817
- 3,
2818
- 2
2819
- ];
2820
- return [
2821
- 4,
2822
- accessTokenCache === null || accessTokenCache === void 0 ? void 0 : accessTokenCache.loadCachedToken()
2823
- ];
2824
- case 1:
2825
- cachedToken = _state.sent();
2826
- if (cachedToken) {
2827
- currentToken = cachedToken;
2828
- }
2829
- _state.label = 2;
2830
- case 2:
2831
- // check expiration
2832
- if (currentToken != null) {
2833
- isExpired = Date.now() + tokenExpirationBuffer >= currentToken.expiresAt.getTime();
2834
- if (isExpired) {
2835
- currentToken = null;
2836
- }
2837
- }
2838
- if (!!currentToken) return [
2839
- 3,
2840
- 10
2841
- ];
2842
- _state.label = 3;
2843
- case 3:
2844
- _state.trys.push([
2845
- 3,
2846
- 5,
2847
- ,
2848
- 6
2849
- ]);
2850
- return [
2851
- 4,
2852
- tokenRefresher()
2853
- ];
2854
- case 4:
2855
- currentToken = _state.sent();
2856
- return [
2857
- 3,
2858
- 6
2859
- ];
2860
- case 5:
2861
- e = _state.sent();
2862
- console.error("calcomOAuthAccessTokenFactory(): Failed retrieving new token from tokenRefresher: ", e);
2863
- throw new CalcomOAuthAuthFailureError('Token Refresh Failed');
2864
- case 6:
2865
- if (!currentToken) return [
2866
- 3,
2867
- 10
2868
- ];
2869
- _state.label = 7;
2870
- case 7:
2871
- _state.trys.push([
2872
- 7,
2873
- 9,
2874
- ,
2875
- 10
2876
- ]);
2877
- return [
2878
- 4,
2879
- accessTokenCache === null || accessTokenCache === void 0 ? void 0 : accessTokenCache.updateCachedToken(currentToken)
2880
- ];
2881
- case 8:
2882
- _state.sent();
2883
- return [
2884
- 3,
2885
- 10
2886
- ];
2887
- case 9:
2888
- _state.sent();
2889
- return [
2890
- 3,
2891
- 10
2892
- ];
2893
- case 10:
2894
- return [
2895
- 2,
2896
- currentToken
2897
- ];
2898
- }
2899
- });
2900
- })();
2901
- };
2902
- }
2903
-
2904
- exports.ALL_CALCOM_OAUTH_SCOPES = ALL_CALCOM_OAUTH_SCOPES;
2905
- exports.ALL_CALCOM_WEBHOOK_TIME_RELATIVE_TRIGGERS = ALL_CALCOM_WEBHOOK_TIME_RELATIVE_TRIGGERS;
2906
- exports.ALL_CALCOM_WEBHOOK_TIME_UNITS = ALL_CALCOM_WEBHOOK_TIME_UNITS;
2907
- exports.ALL_CALCOM_WEBHOOK_VERSIONS = ALL_CALCOM_WEBHOOK_VERSIONS;
2908
- exports.CALCOM_API_KEY_ACCESS_TOKEN_EXPIRATION = CALCOM_API_KEY_ACCESS_TOKEN_EXPIRATION;
2909
- exports.CALCOM_API_URL = CALCOM_API_URL;
2910
- exports.CALCOM_API_VERSION_BOOKINGS = CALCOM_API_VERSION_BOOKINGS;
2911
- exports.CALCOM_API_VERSION_CALENDARS = CALCOM_API_VERSION_CALENDARS;
2912
- exports.CALCOM_API_VERSION_EVENT_TYPES = CALCOM_API_VERSION_EVENT_TYPES;
2913
- exports.CALCOM_API_VERSION_HEADER = CALCOM_API_VERSION_HEADER;
2914
- exports.CALCOM_API_VERSION_ME = CALCOM_API_VERSION_ME;
2915
- exports.CALCOM_API_VERSION_SCHEDULES = CALCOM_API_VERSION_SCHEDULES;
2916
- exports.CALCOM_API_VERSION_SLOTS = CALCOM_API_VERSION_SLOTS;
2917
- exports.CALCOM_OAUTH_API_URL = CALCOM_OAUTH_API_URL;
2918
- exports.CALCOM_OAUTH_AUTHORIZE_RESPONSE_TYPE = CALCOM_OAUTH_AUTHORIZE_RESPONSE_TYPE;
2919
- exports.CALCOM_OAUTH_AUTHORIZE_URL = CALCOM_OAUTH_AUTHORIZE_URL;
2920
- exports.CALCOM_OAUTH_INVALID_GRANT_ERROR_CODE = CALCOM_OAUTH_INVALID_GRANT_ERROR_CODE;
2921
- exports.CALCOM_OAUTH_SCOPE_DELIMITER = CALCOM_OAUTH_SCOPE_DELIMITER;
2922
- exports.CALCOM_OAUTH_TOKEN_PATH = CALCOM_OAUTH_TOKEN_PATH;
2923
- exports.CALCOM_OAUTH_TOKEN_URL = CALCOM_OAUTH_TOKEN_URL;
2924
- exports.CALCOM_RATE_LIMIT_LIMIT_HEADER = CALCOM_RATE_LIMIT_LIMIT_HEADER;
2925
- exports.CALCOM_RATE_LIMIT_REMAINING_HEADER = CALCOM_RATE_LIMIT_REMAINING_HEADER;
2926
- exports.CALCOM_RATE_LIMIT_RESET_HEADER = CALCOM_RATE_LIMIT_RESET_HEADER;
2927
- exports.CALCOM_TOO_MANY_REQUESTS_HTTP_STATUS_CODE = CALCOM_TOO_MANY_REQUESTS_HTTP_STATUS_CODE;
2928
- exports.CALCOM_WEBHOOK_TIME_UNIT_TIME_UNIT_MAP = CALCOM_WEBHOOK_TIME_UNIT_TIME_UNIT_MAP;
2929
- exports.CalcomOAuthAccessTokenError = CalcomOAuthAccessTokenError;
2930
- exports.CalcomOAuthAuthFailureError = CalcomOAuthAuthFailureError;
2931
- exports.CalcomServerError = CalcomServerError;
2932
- exports.CalcomServerFetchResponseError = CalcomServerFetchResponseError;
2933
- exports.CalcomTooManyRequestsError = CalcomTooManyRequestsError;
2934
- exports.DEFAULT_CALCOM_API_RATE_LIMIT = DEFAULT_CALCOM_API_RATE_LIMIT;
2935
- exports.DEFAULT_CALCOM_API_RATE_LIMIT_RESET_PERIOD = DEFAULT_CALCOM_API_RATE_LIMIT_RESET_PERIOD;
2936
- exports.DEFAULT_CALCOM_RATE_LIMITED_TOO_MANY_REQUESTS_LOG_FUNCTION = DEFAULT_CALCOM_RATE_LIMITED_TOO_MANY_REQUESTS_LOG_FUNCTION;
2937
- exports.calcomAccessTokenFromApiKey = calcomAccessTokenFromApiKey;
2938
- exports.calcomAccessTokenFromTokenResponse = calcomAccessTokenFromTokenResponse;
2939
- exports.calcomAccessTokenStringFactory = calcomAccessTokenStringFactory;
2940
- exports.calcomApiVersionHeaders = calcomApiVersionHeaders;
2941
- exports.calcomAuthCredentialFromValues = calcomAuthCredentialFromValues;
2942
- exports.calcomCalendarsToLoadFromConnectedCalendars = calcomCalendarsToLoadFromConnectedCalendars;
2943
- exports.calcomFactory = calcomFactory;
2944
- exports.calcomOAuthAccessTokenFactory = calcomOAuthAccessTokenFactory;
2945
- exports.calcomOAuthAuthorizeUrlFactory = calcomOAuthAuthorizeUrlFactory;
2946
- exports.calcomOAuthFactory = calcomOAuthFactory;
2947
- exports.calcomRateLimitHeaderDetails = calcomRateLimitHeaderDetails;
2948
- exports.calcomRateLimitedFetchHandler = calcomRateLimitedFetchHandler;
2949
- exports.calcomServerErrorDataFromApiErrorResponseBody = calcomServerErrorDataFromApiErrorResponseBody;
2950
- exports.calcomWebhookTimeOffsetFromWebhook = calcomWebhookTimeOffsetFromWebhook;
2951
- exports.calcomWebhookTimeOffsetToTimeDuration = calcomWebhookTimeOffsetToTimeDuration;
2952
- exports.cancelBooking = cancelBooking;
2953
- exports.createBooking = createBooking;
2954
- exports.createEventType = createEventType;
2955
- exports.createSchedule = createSchedule;
2956
- exports.createWebhook = createWebhook;
2957
- exports.deleteEventType = deleteEventType;
2958
- exports.deleteSchedule = deleteSchedule;
2959
- exports.deleteWebhook = deleteWebhook;
2960
- exports.exchangeAuthorizationCode = exchangeAuthorizationCode;
2961
- exports.getAvailableSlots = getAvailableSlots;
2962
- exports.getBooking = getBooking;
2963
- exports.getBookings = getBookings;
2964
- exports.getBusyTimes = getBusyTimes;
2965
- exports.getBusyTimesForConnectedCalendars = getBusyTimesForConnectedCalendars;
2966
- exports.getCalendars = getCalendars;
2967
- exports.getDefaultSchedule = getDefaultSchedule;
2968
- exports.getEventTypes = getEventTypes;
2969
- exports.getMe = getMe;
2970
- exports.getSchedule = getSchedule;
2971
- exports.getSchedules = getSchedules;
2972
- exports.getWebhook = getWebhook;
2973
- exports.getWebhooks = getWebhooks;
2974
- exports.handleCalcomErrorFetch = handleCalcomErrorFetch;
2975
- exports.handleCalcomErrorFetchFactory = handleCalcomErrorFetchFactory;
2976
- exports.handleCalcomOAuthErrorFetch = handleCalcomOAuthErrorFetch;
2977
- exports.isCalcomApiKeyCredential = isCalcomApiKeyCredential;
2978
- exports.isCalcomOAuthScope = isCalcomOAuthScope;
2979
- exports.logCalcomErrorToConsole = logCalcomErrorToConsole;
2980
- exports.logCalcomOAuthErrorToConsole = logCalcomOAuthErrorToConsole;
2981
- exports.logCalcomServerErrorFunction = logCalcomServerErrorFunction;
2982
- exports.parseCalcomApiError = parseCalcomApiError;
2983
- exports.parseCalcomApiServerErrorResponseData = parseCalcomApiServerErrorResponseData;
2984
- exports.parseCalcomOAuthError = parseCalcomOAuthError;
2985
- exports.parseCalcomOAuthServerErrorResponseData = parseCalcomOAuthServerErrorResponseData;
2986
- exports.parseCalcomServerErrorData = parseCalcomServerErrorData;
2987
- exports.refreshAccessToken = refreshAccessToken;
2988
- exports.updateEventType = updateEventType;
2989
- exports.updateSchedule = updateSchedule;
2990
- exports.updateWebhook = updateWebhook;