@ordinatio/scheduling-api 0.6.0 → 0.8.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/dist/index.js CHANGED
@@ -31,6 +31,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
33
  ALL_REFUND_STATUSES: () => ALL_REFUND_STATUSES,
34
+ ApiKeySchema: () => ApiKeySchema,
34
35
  BALANCE_APPOINTMENT_SELECT: () => BALANCE_APPOINTMENT_SELECT,
35
36
  BALANCE_BLOCKED_APPOINTMENT_STATUS: () => BALANCE_BLOCKED_APPOINTMENT_STATUS,
36
37
  BALANCE_REQUIRED_PAYMENT_STATUS: () => BALANCE_REQUIRED_PAYMENT_STATUS,
@@ -67,9 +68,12 @@ __export(index_exports, {
67
68
  RouteClientSchema: () => RouteClientSchema,
68
69
  SLOT_GRANULARITY_DEFAULT: () => SLOT_GRANULARITY_DEFAULT,
69
70
  SLOT_GRANULARITY_OPTIONS: () => SLOT_GRANULARITY_OPTIONS,
71
+ SmsSendError: () => SmsSendError,
70
72
  TERMINAL_SUCCESS_STATUSES: () => TERMINAL_SUCCESS_STATUSES,
71
73
  TOKEN_TTL_DAYS: () => TOKEN_TTL_DAYS,
74
+ TelnyxSendError: () => SmsSendError,
72
75
  TestRoutingFormSchema: () => TestRoutingFormSchema,
76
+ TextSettingsSchema: () => TextSettingsSchema,
73
77
  UnverifiedPaymentError: () => UnverifiedPaymentError,
74
78
  UpdateAppointmentCategorySchema: () => UpdateAppointmentCategorySchema,
75
79
  UpdateAppointmentTypeSchema: () => UpdateAppointmentTypeSchema,
@@ -82,9 +86,12 @@ __export(index_exports, {
82
86
  UpdateServicePackageSchema: () => UpdateServicePackageSchema,
83
87
  assertStripeTestKey: () => assertStripeTestKey,
84
88
  attemptLegRefund: () => attemptLegRefund,
89
+ bearerKeyOf: () => bearerKeyOf,
85
90
  calendarVisibilityFilter: () => calendarVisibilityFilter,
86
91
  canSeeAppointmentInScope: () => canSeeAppointmentInScope,
87
92
  canSeeCalendarInScope: () => canSeeCalendarInScope,
93
+ checkSendingDomain: () => checkSendingDomain,
94
+ classifyReply: () => classifyReply,
88
95
  createBalanceIntent: () => createBalanceIntent,
89
96
  createBearerStaffResolver: () => createBearerStaffResolver,
90
97
  createMemoryAvailabilityCache: () => createMemoryAvailabilityCache,
@@ -93,26 +100,38 @@ __export(index_exports, {
93
100
  createNoBalancePaymentControl: () => createNoBalancePaymentControl,
94
101
  createNoPaymentAdapter: () => createNoPaymentAdapter,
95
102
  createNodeListener: () => createNodeListener,
103
+ createOutlookCalendarSync: () => createOutlookCalendarSync,
104
+ createPerBusinessSmsAdapter: () => createPerBusinessSmsAdapter,
96
105
  createSchedulingApi: () => createSchedulingApi,
97
106
  createScopedVisibility: () => createScopedVisibility,
107
+ createSendingDomainVerifier: () => createSendingDomainVerifier,
98
108
  createSingleOrganizationDirectory: () => createSingleOrganizationDirectory,
99
109
  createSingleOrganizationResolver: () => createSingleOrganizationResolver,
100
110
  createStaffContext: () => createStaffContext,
101
111
  createStripePaymentAdapter: () => createStripePaymentAdapter,
112
+ createTelnyxSmsAdapter: () => createTelnyxSmsAdapter,
113
+ createTextSettingsResolver: () => createTextSettingsResolver,
114
+ createTwilioSmsAdapter: () => createTwilioSmsAdapter,
102
115
  decimalToCents: () => decimalToCents,
103
116
  defaultCorsHeaders: () => defaultCorsHeaders,
104
117
  getErrorCode: () => getErrorCode,
105
118
  getErrorMessage: () => getErrorMessage,
106
119
  getErrorRef: () => getErrorRef,
120
+ handleTelnyxWebhook: () => handleTelnyxWebhook,
121
+ handleTwilioWebhook: () => handleTwilioWebhook,
107
122
  isCalendarVisibleInScope: () => isCalendarVisibleInScope,
108
123
  isSchedulingServiceError: () => isSchedulingServiceError,
109
124
  isSupportedCurrency: () => isSupportedCurrency,
110
125
  isTokenExpired: () => isTokenExpired,
126
+ normalizePhoneNumber: () => normalizePhoneNumber,
127
+ normalizeSendingDomain: () => normalizeSendingDomain,
111
128
  parsePagination: () => parsePagination,
112
129
  persistRefundOutcome: () => persistRefundOutcome,
113
130
  recordBalanceIntent: () => recordBalanceIntent,
114
131
  runCalendarRemoveWithoutBlocking: () => runCalendarRemoveWithoutBlocking,
115
132
  runCalendarSyncWithoutBlocking: () => runCalendarSyncWithoutBlocking,
133
+ verifyTelnyxSignature: () => verifyTelnyxSignature,
134
+ verifyTwilioSignature: () => verifyTwilioSignature,
116
135
  visibleCalendarIdsInScope: () => visibleCalendarIdsInScope
117
136
  });
118
137
  module.exports = __toCommonJS(index_exports);
@@ -131,6 +150,82 @@ function defaultCorsHeaders() {
131
150
  };
132
151
  }
133
152
 
153
+ // src/api-keys/api-key-host.ts
154
+ var import_scheduling = require("@ordinatio/scheduling");
155
+
156
+ // src/staff/simple-staff.ts
157
+ var DEFAULT_ADMIN_ROLES = ["OWNER", "ADMIN", "MANAGER"];
158
+ function createStaffContext(input) {
159
+ const adminRoles = (input.adminRoles ?? DEFAULT_ADMIN_ROLES).map((role) => role.toUpperCase());
160
+ const { db, organizationId } = input;
161
+ return {
162
+ userId: input.userId,
163
+ organizationId,
164
+ role: input.role,
165
+ isAdmin: adminRoles.includes(input.role.toUpperCase()),
166
+ schedulingEnabled: input.schedulingEnabled ?? true,
167
+ db,
168
+ visibleCalendars: async () => null,
169
+ visibleCalendarIds: async () => void 0,
170
+ canSeeCalendar: async (calendarId) => Boolean(await db.schedulingCalendar.findFirst({ where: { id: calendarId, organizationId }, select: { id: true } })),
171
+ canSeeAppointment: async (appointmentId) => Boolean(await db.appointment.findFirst({ where: { id: appointmentId, calendar: { organizationId } }, select: { id: true } })),
172
+ // The package has no client table, so there is no preference to read.
173
+ preferredLocationOf: async () => null
174
+ };
175
+ }
176
+ var BEARER = /^bearer\s+(\S+)$/i;
177
+ function createBearerStaffResolver(input) {
178
+ return {
179
+ async resolve(request) {
180
+ const token = BEARER.exec(request.headers.get("authorization") ?? "")?.[1];
181
+ if (!token) return null;
182
+ const person = await input.authenticate(token, request);
183
+ if (!person) return null;
184
+ return createStaffContext({
185
+ ...person,
186
+ db: await input.db(person),
187
+ adminRoles: input.adminRoles,
188
+ schedulingEnabled: input.schedulingEnabled ? await input.schedulingEnabled(person) : void 0
189
+ });
190
+ }
191
+ };
192
+ }
193
+
194
+ // src/api-keys/api-key-host.ts
195
+ var API_KEY_ROLE_PREFIX = "API_KEY_";
196
+ var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
197
+ function bearerKeyOf(request) {
198
+ const header = request.headers.get("authorization");
199
+ if (!header) return null;
200
+ const match = /^[Bb][Ee][Aa][Rr][Ee][Rr]\s+(osk_\S+)$/.exec(header.trim());
201
+ return match ? match[1] : null;
202
+ }
203
+ function contextOf(key, db, schedulingEnabled) {
204
+ return createStaffContext({
205
+ // The key, not the person who made it, is what the rate limit counts.
206
+ userId: `api-key:${key.id}`,
207
+ organizationId: key.organizationId,
208
+ role: `${API_KEY_ROLE_PREFIX}${key.access}`,
209
+ adminRoles: [`${API_KEY_ROLE_PREFIX}READ`, `${API_KEY_ROLE_PREFIX}FULL`],
210
+ schedulingEnabled,
211
+ db
212
+ });
213
+ }
214
+ async function hostForRequest(host, request, route) {
215
+ if (route.public || !host.apiKeys) return host;
216
+ const secret = bearerKeyOf(request);
217
+ if (secret === null) return host;
218
+ const db = await host.apiKeys.db();
219
+ const key = await (0, import_scheduling.verifyApiKey)(db, secret);
220
+ if (!key) return Response.json({ error: "Unauthorized" }, { status: 401 });
221
+ if (route.personOnly) return Response.json({ error: "This needs a person signed in at a browser, not an API key" }, { status: 403 });
222
+ if (key.access === "READ" && !SAFE_METHODS.has(request.method.toUpperCase())) {
223
+ return Response.json({ error: "This API key is read-only" }, { status: 403 });
224
+ }
225
+ const context = contextOf(key, db, await host.schedulingEnabledFor(key.organizationId));
226
+ return { ...host, staff: { resolve: async () => context } };
227
+ }
228
+
134
229
  // src/availability/memory-availability-cache.ts
135
230
  var TTL_MS = 6e4;
136
231
  var DEFAULT_MAX_ENTRIES = 2e3;
@@ -314,7 +409,7 @@ function createUnconfiguredConnector(provider) {
314
409
  }
315
410
 
316
411
  // src/webhooks/webhook-events.ts
317
- var import_scheduling = require("@ordinatio/scheduling");
412
+ var import_scheduling2 = require("@ordinatio/scheduling");
318
413
  var WEBHOOK_EVENT_FOR = {
319
414
  "appointment.created": "appointment.booked",
320
415
  "appointment.updated": "appointment.rescheduled",
@@ -331,7 +426,7 @@ function withWebhooks(inner, host) {
331
426
  if (host.webhooks && webhookType && typeof appointmentId === "string") {
332
427
  try {
333
428
  const db = await host.tenantDb(organizationId, "webhooks");
334
- if (db) await (0, import_scheduling.enqueueAppointmentWebhook)(db, { organizationId, type: webhookType, appointmentId });
429
+ if (db) await (0, import_scheduling2.enqueueAppointmentWebhook)(db, { organizationId, type: webhookType, appointmentId });
335
430
  } catch (error) {
336
431
  console.error("[scheduling-api] could not reach the database to queue a webhook:", error);
337
432
  }
@@ -342,9 +437,9 @@ function withWebhooks(inner, host) {
342
437
  }
343
438
 
344
439
  // src/waitlist/announce-offer.ts
345
- var import_scheduling2 = require("@ordinatio/scheduling");
440
+ var import_scheduling3 = require("@ordinatio/scheduling");
346
441
  async function offerAndAnnounce(host, settings, db, slot) {
347
- const offer = await (0, import_scheduling2.tryOfferFreedSlot)(db, { ...slot, offerMinutes: settings.offerMinutes });
442
+ const offer = await (0, import_scheduling3.tryOfferFreedSlot)(db, { ...slot, offerMinutes: settings.offerMinutes });
348
443
  if (!offer) return false;
349
444
  const details = {
350
445
  organizationId: slot.organizationId,
@@ -367,7 +462,7 @@ async function offerAndAnnounce(host, settings, db, slot) {
367
462
  }
368
463
  if (host.webhooks) {
369
464
  try {
370
- await (0, import_scheduling2.enqueueWebhookEvent)(db, {
465
+ await (0, import_scheduling3.enqueueWebhookEvent)(db, {
371
466
  organizationId: slot.organizationId,
372
467
  type: "waitlist.offered",
373
468
  // Each offering has its own id, so offering the same slot to the same person again still reaches subscribers.
@@ -421,7 +516,7 @@ function withWaitlist(inner, host) {
421
516
  }
422
517
 
423
518
  // src/handlers/manage-cancel.ts
424
- var import_scheduling6 = require("@ordinatio/scheduling");
519
+ var import_scheduling7 = require("@ordinatio/scheduling");
425
520
 
426
521
  // src/client-address.ts
427
522
  function forwardedAddress(request) {
@@ -432,7 +527,7 @@ function clientAddress(request) {
432
527
  }
433
528
 
434
529
  // src/error-guards.ts
435
- var import_scheduling3 = require("@ordinatio/scheduling");
530
+ var import_scheduling4 = require("@ordinatio/scheduling");
436
531
  function getErrorCode(error) {
437
532
  if (typeof error === "object" && error !== null && "code" in error) {
438
533
  const code = error.code;
@@ -459,20 +554,20 @@ function getErrorMessage(error, fallback) {
459
554
  return fallback;
460
555
  }
461
556
  function schedErrorStatus(code) {
462
- return import_scheduling3.SCHEDULING_ERRORS[code]?.httpStatus ?? 400;
557
+ return import_scheduling4.SCHEDULING_ERRORS[code]?.httpStatus ?? 400;
463
558
  }
464
559
 
465
560
  // src/manage/cancel-via-token.ts
466
- var import_scheduling5 = require("@ordinatio/scheduling");
561
+ var import_scheduling6 = require("@ordinatio/scheduling");
467
562
 
468
563
  // src/calendar-sync.ts
469
- var import_scheduling4 = require("@ordinatio/scheduling");
564
+ var import_scheduling5 = require("@ordinatio/scheduling");
470
565
  async function runWithoutBlocking(code, appointmentId, step, recordFailure) {
471
566
  try {
472
567
  await step();
473
568
  return { queued: true };
474
569
  } catch (error) {
475
- const diagnostic = (0, import_scheduling4.schedError)(code, { error, appointmentId });
570
+ const diagnostic = (0, import_scheduling5.schedError)(code, { error, appointmentId });
476
571
  console.error("[calendar-sync]", diagnostic.ref, error instanceof Error ? error.message : error);
477
572
  try {
478
573
  await recordFailure?.(diagnostic.ref);
@@ -492,7 +587,7 @@ function runCalendarRemoveWithoutBlocking(sync, ref, recordFailure) {
492
587
  // src/manage/cancel-via-token.ts
493
588
  async function cancelViaToken(host, db, organizationId, appointment) {
494
589
  const hasPayment = !!(appointment.paymentId && (appointment.paymentStatus === "PAID" || appointment.paymentStatus === "DEPOSIT_PAID"));
495
- await (0, import_scheduling5.cancelAppointment)(db, {
590
+ await (0, import_scheduling6.cancelAppointment)(db, {
496
591
  appointmentId: appointment.id,
497
592
  cancelledBy: "client",
498
593
  reason: "Cancelled via self-service link"
@@ -503,7 +598,7 @@ async function cancelViaToken(host, db, organizationId, appointment) {
503
598
  data: { refundStatus: hasPayment ? "PENDING_REVIEW" : "NO_PAYMENT" }
504
599
  });
505
600
  } catch (refundStatusError) {
506
- const diagnostic = (0, import_scheduling5.schedError)("SCHED_602", {
601
+ const diagnostic = (0, import_scheduling6.schedError)("SCHED_602", {
507
602
  error: refundStatusError,
508
603
  appointmentId: appointment.id,
509
604
  context: "refundStatus write failed after cancellation already committed",
@@ -548,9 +643,9 @@ async function cancelViaToken(host, db, organizationId, appointment) {
548
643
  const baseUrl = host.appUrl();
549
644
  if (baseUrl) {
550
645
  try {
551
- await (0, import_scheduling5.queueStaffNotification)(db, appointment.id, "CANCELLATION", baseUrl, { brand: Boolean(host.brand) });
646
+ await (0, import_scheduling6.queueStaffNotification)(db, appointment.id, "CANCELLATION", baseUrl, { brand: Boolean(host.brand) });
552
647
  } catch (staffError) {
553
- const diagnostic = (0, import_scheduling5.schedError)("SCHED_607", { error: staffError, appointmentId: appointment.id });
648
+ const diagnostic = (0, import_scheduling6.schedError)("SCHED_607", { error: staffError, appointmentId: appointment.id });
554
649
  console.error("[DELETE /manage]", diagnostic.ref, staffError instanceof Error ? staffError.message : staffError);
555
650
  }
556
651
  }
@@ -624,14 +719,14 @@ async function cancelManagedAppointment(request, { host }) {
624
719
  { status: 409 }
625
720
  );
626
721
  }
627
- const diagnostic = (0, import_scheduling6.schedError)("SCHED_602", { error, token: token ?? "unknown", appointmentId });
722
+ const diagnostic = (0, import_scheduling7.schedError)("SCHED_602", { error, token: token ?? "unknown", appointmentId });
628
723
  console.error("[DELETE /manage]", diagnostic.ref, error instanceof Error ? error.message : error);
629
724
  return Response.json({ error: "Failed to cancel", ref: diagnostic.ref }, { status: 500 });
630
725
  }
631
726
  }
632
727
 
633
728
  // src/handlers/manage-get.ts
634
- var import_scheduling7 = require("@ordinatio/scheduling");
729
+ var import_scheduling8 = require("@ordinatio/scheduling");
635
730
  async function getManagedAppointment(request, { host }) {
636
731
  let token = null;
637
732
  try {
@@ -665,24 +760,24 @@ async function getManagedAppointment(request, { host }) {
665
760
  staffName: appointment.calendar.staffName,
666
761
  calendarId: appointment.calendarId,
667
762
  allowReschedule: appointment.type.allowReschedule,
668
- location: (0, import_scheduling7.resolveLocation)(appointment),
763
+ location: (0, import_scheduling8.resolveLocation)(appointment),
669
764
  meetingUrl: appointment.meetingUrl ?? null,
670
765
  theme: appointment.calendar.theme ?? null
671
766
  });
672
767
  } catch (error) {
673
- const diagnostic = (0, import_scheduling7.schedError)("SCHED_601", { error, token: token ?? "unknown" });
768
+ const diagnostic = (0, import_scheduling8.schedError)("SCHED_601", { error, token: token ?? "unknown" });
674
769
  console.error("[GET /manage]", diagnostic.ref, error instanceof Error ? error.message : error);
675
770
  return Response.json({ error: "Failed to fetch appointment", ref: diagnostic.ref }, { status: 500 });
676
771
  }
677
772
  }
678
773
 
679
774
  // src/handlers/manage-reschedule.ts
680
- var import_scheduling9 = require("@ordinatio/scheduling");
775
+ var import_scheduling10 = require("@ordinatio/scheduling");
681
776
 
682
777
  // src/manage/reschedule-via-token.ts
683
- var import_scheduling8 = require("@ordinatio/scheduling");
778
+ var import_scheduling9 = require("@ordinatio/scheduling");
684
779
  async function rescheduleViaToken(host, db, organizationId, appointment, newTime) {
685
- const result = await (0, import_scheduling8.rescheduleAppointment)(db, {
780
+ const result = await (0, import_scheduling9.rescheduleAppointment)(db, {
686
781
  appointmentId: appointment.id,
687
782
  newStartTime: newTime,
688
783
  reason: "Rescheduled via self-service link"
@@ -707,21 +802,21 @@ async function rescheduleViaToken(host, db, organizationId, appointment, newTime
707
802
  );
708
803
  const baseUrl = host.appUrl() ?? void 0;
709
804
  if (baseUrl) {
710
- await (0, import_scheduling8.queueImmediateNotification)(db, appointment.id, "RESCHEDULE", baseUrl, { brand: Boolean(host.brand) });
805
+ await (0, import_scheduling9.queueImmediateNotification)(db, appointment.id, "RESCHEDULE", baseUrl, { brand: Boolean(host.brand) });
711
806
  } else {
712
807
  console.warn("[manage] no appUrl \u2014 RESCHEDULE notification skipped");
713
808
  }
714
809
  try {
715
- await (0, import_scheduling8.scheduleNotifications)(db, appointment.id, baseUrl, { excludeTriggers: ["CONFIRMATION"], brand: Boolean(host.brand) });
810
+ await (0, import_scheduling9.scheduleNotifications)(db, appointment.id, baseUrl, { excludeTriggers: ["CONFIRMATION"], brand: Boolean(host.brand) });
716
811
  } catch (error) {
717
- const diagnostic = (0, import_scheduling8.schedError)("SCHED_604", { error, appointmentId: appointment.id });
812
+ const diagnostic = (0, import_scheduling9.schedError)("SCHED_604", { error, appointmentId: appointment.id });
718
813
  console.error("[PATCH /manage] scheduleNotifications failed (non-blocking):", diagnostic.ref, error instanceof Error ? error.message : error);
719
814
  }
720
815
  if (baseUrl) {
721
816
  try {
722
- await (0, import_scheduling8.queueStaffNotification)(db, appointment.id, "RESCHEDULE", baseUrl, { brand: Boolean(host.brand) });
817
+ await (0, import_scheduling9.queueStaffNotification)(db, appointment.id, "RESCHEDULE", baseUrl, { brand: Boolean(host.brand) });
723
818
  } catch (staffError) {
724
- const diagnostic = (0, import_scheduling8.schedError)("SCHED_607", { error: staffError, appointmentId: appointment.id });
819
+ const diagnostic = (0, import_scheduling9.schedError)("SCHED_607", { error: staffError, appointmentId: appointment.id });
725
820
  console.error("[PATCH /manage]", diagnostic.ref, staffError instanceof Error ? staffError.message : staffError);
726
821
  }
727
822
  }
@@ -780,7 +875,7 @@ async function rescheduleManagedAppointment(request, { host }) {
780
875
  if (target instanceof Response) return target;
781
876
  return await rescheduleViaToken(host, target.db, target.organizationId, appointment, newTime);
782
877
  } catch (error) {
783
- if (error instanceof import_scheduling9.SchedulingValidationError) {
878
+ if (error instanceof import_scheduling10.SchedulingValidationError) {
784
879
  return Response.json({ error: error.message, ref: error.ref }, { status: 400 });
785
880
  }
786
881
  const code = getErrorCode(error);
@@ -799,14 +894,14 @@ async function rescheduleManagedAppointment(request, { host }) {
799
894
  console.error("[PATCH /manage]", ref, "SCHED_306", error);
800
895
  return Response.json({ error: "Appointment status prevents rescheduling", ...ref && { ref } }, { status: 400 });
801
896
  }
802
- const diagnostic = (0, import_scheduling9.schedError)("SCHED_603", { error, token: token ?? "unknown", appointmentId });
897
+ const diagnostic = (0, import_scheduling10.schedError)("SCHED_603", { error, token: token ?? "unknown", appointmentId });
803
898
  console.error("[PATCH /manage]", diagnostic.ref, error instanceof Error ? error.message : error);
804
899
  return Response.json({ error: "Failed to reschedule", ref: diagnostic.ref }, { status: 500 });
805
900
  }
806
901
  }
807
902
 
808
903
  // src/handlers/capacity.ts
809
- var import_scheduling10 = require("@ordinatio/scheduling");
904
+ var import_scheduling11 = require("@ordinatio/scheduling");
810
905
 
811
906
  // src/respond.ts
812
907
  var WIDGET_CACHE_HEADERS = {
@@ -853,7 +948,7 @@ async function getCapacity(request, { host }) {
853
948
  select: { isGroup: true }
854
949
  });
855
950
  if (!type || !type.isGroup) return corsJson(cors, NOT_FOUND, { status: 404 });
856
- return corsJson(cors, await (0, import_scheduling10.getGroupCapacity)(db, { typeId, calendarId, startTime }));
951
+ return corsJson(cors, await (0, import_scheduling11.getGroupCapacity)(db, { typeId, calendarId, startTime }));
857
952
  } catch (error) {
858
953
  console.error("[group-capacity] unexpected error:", error instanceof Error ? error.message : error);
859
954
  return corsJson(cors, { error: "Failed to fetch capacity" }, { status: 500 });
@@ -861,7 +956,7 @@ async function getCapacity(request, { host }) {
861
956
  }
862
957
 
863
958
  // src/handlers/payment-intent.ts
864
- var import_scheduling11 = require("@ordinatio/scheduling");
959
+ var import_scheduling12 = require("@ordinatio/scheduling");
865
960
  var import_zod = require("zod");
866
961
 
867
962
  // src/payments/create-payment-intent.ts
@@ -977,7 +1072,7 @@ async function createPaymentIntentRoute(request, { host }) {
977
1072
  if (!result.ok) return corsJson(cors, { error: result.error }, { status: result.status });
978
1073
  return corsJson(cors, result.body, { status: result.status });
979
1074
  } catch (error) {
980
- const err = (0, import_scheduling11.schedError)("SCHED_407", {
1075
+ const err = (0, import_scheduling12.schedError)("SCHED_407", {
981
1076
  typeId,
982
1077
  calendarId,
983
1078
  error: error instanceof Error ? error.message : String(error)
@@ -988,7 +1083,7 @@ async function createPaymentIntentRoute(request, { host }) {
988
1083
  }
989
1084
 
990
1085
  // src/handlers/appointment-cancel.ts
991
- var import_scheduling13 = require("@ordinatio/scheduling");
1086
+ var import_scheduling14 = require("@ordinatio/scheduling");
992
1087
 
993
1088
  // src/appointments/owned-appointment.ts
994
1089
  async function verifyAppointmentOwnership(db, appointmentId, organizationId) {
@@ -1041,7 +1136,7 @@ async function writeRefundStatusAfterCancel(host, db, input) {
1041
1136
  }
1042
1137
 
1043
1138
  // src/staff/require-staff.ts
1044
- var import_scheduling12 = require("@ordinatio/scheduling");
1139
+ var import_scheduling13 = require("@ordinatio/scheduling");
1045
1140
  async function requireAdminStaff(host, request, options) {
1046
1141
  const staff = await host.staff.resolve(request);
1047
1142
  if (!staff) return Response.json({ error: "Unauthorized" }, { status: 401 });
@@ -1050,7 +1145,7 @@ async function requireAdminStaff(host, request, options) {
1050
1145
  if (limited) return limited;
1051
1146
  }
1052
1147
  if (!staff.isAdmin && !options.allowAnyRole) {
1053
- const err = (0, import_scheduling12.schedError)("SCHED_900", { userId: staff.userId, role: staff.role });
1148
+ const err = (0, import_scheduling13.schedError)("SCHED_900", { userId: staff.userId, role: staff.role });
1054
1149
  return Response.json({ error: "Forbidden", ref: err.ref }, { status: 403 });
1055
1150
  }
1056
1151
  if (!staff.schedulingEnabled && !options.ignoreSchedulingSwitch) {
@@ -1093,7 +1188,7 @@ async function cancelByStaff(request, { host, params }) {
1093
1188
  const appointment = await verifyAppointmentOwnership(db, id, organizationId);
1094
1189
  if (!appointment) return Response.json({ error: "Appointment not found" }, { status: 404 });
1095
1190
  const hasPayment = hasPendingPayment(appointment.paymentId, appointment.paymentStatus);
1096
- const result = await (0, import_scheduling13.cancelAppointment)(db, { appointmentId: id, cancelledBy: "staff", reason });
1191
+ const result = await (0, import_scheduling14.cancelAppointment)(db, { appointmentId: id, cancelledBy: "staff", reason });
1097
1192
  await writeRefundStatusAfterCancel(host, db, { appointmentId: id, hasPayment, clientName: appointment.clientName });
1098
1193
  if (hasPayment) {
1099
1194
  await host.activity.log(db, {
@@ -1113,7 +1208,7 @@ async function cancelByStaff(request, { host, params }) {
1113
1208
  const baseUrl = host.appUrl();
1114
1209
  if (baseUrl) {
1115
1210
  try {
1116
- await (0, import_scheduling13.queueStaffNotification)(db, id, "CANCELLATION", baseUrl, { brand: Boolean(host.brand) });
1211
+ await (0, import_scheduling14.queueStaffNotification)(db, id, "CANCELLATION", baseUrl, { brand: Boolean(host.brand) });
1117
1212
  } catch (error) {
1118
1213
  await host.activity.log(db, {
1119
1214
  action: "scheduling.staff_notification_failed",
@@ -1140,7 +1235,7 @@ async function cancelByStaff(request, { host, params }) {
1140
1235
  });
1141
1236
  return Response.json(withoutManageToken(result));
1142
1237
  } catch (error) {
1143
- if (error instanceof import_scheduling13.SchedulingNotFoundError) {
1238
+ if (error instanceof import_scheduling14.SchedulingNotFoundError) {
1144
1239
  return Response.json({ error: error.message, ref: error.ref }, { status: 404 });
1145
1240
  }
1146
1241
  const ref = getErrorRef(error);
@@ -1345,7 +1440,7 @@ function finishOutlookConnection(request, { host }) {
1345
1440
  }
1346
1441
 
1347
1442
  // src/handlers/appointment-cancel-sync.ts
1348
- var import_scheduling14 = require("@ordinatio/scheduling");
1443
+ var import_scheduling15 = require("@ordinatio/scheduling");
1349
1444
  var import_zod2 = require("zod");
1350
1445
  var Schema2 = import_zod2.z.object({
1351
1446
  source: import_zod2.z.enum(["google", "outlook"]),
@@ -1388,13 +1483,13 @@ async function cancelFromCalendarSync(request, { host, params }) {
1388
1483
  return Response.json({ error: "Appointment not available for sync" }, { status: 503 });
1389
1484
  }
1390
1485
  try {
1391
- await (0, import_scheduling14.cancelAppointment)(db, {
1486
+ await (0, import_scheduling15.cancelAppointment)(db, {
1392
1487
  appointmentId: id,
1393
1488
  cancelledBy: "system",
1394
1489
  reason: reason ?? `Cancelled via ${source === "google" ? "Google" : "Outlook"} Calendar`
1395
1490
  });
1396
1491
  } catch (error) {
1397
- if (error instanceof import_scheduling14.SchedulingNotFoundError) {
1492
+ if (error instanceof import_scheduling15.SchedulingNotFoundError) {
1398
1493
  return Response.json({ error: "Appointment not found", ref: error.ref }, { status: 404 });
1399
1494
  }
1400
1495
  const ref = getErrorRef(error);
@@ -1428,7 +1523,7 @@ async function cancelFromCalendarSync(request, { host, params }) {
1428
1523
  await host.workerCommands.queue(source === "google" ? "delete-from-outlook" : "delete-from-google", { appointmentId: id });
1429
1524
  const baseUrl = host.appUrl();
1430
1525
  if (baseUrl) {
1431
- await (0, import_scheduling14.queueImmediateNotification)(db, id, "CANCELLATION", baseUrl, { brand: Boolean(host.brand) }).catch(
1526
+ await (0, import_scheduling15.queueImmediateNotification)(db, id, "CANCELLATION", baseUrl, { brand: Boolean(host.brand) }).catch(
1432
1527
  (err) => console.warn("[cancel-sync] Failed to queue cancellation notification:", id, err instanceof Error ? err.message : err)
1433
1528
  );
1434
1529
  }
@@ -1441,10 +1536,10 @@ async function cancelFromCalendarSync(request, { host, params }) {
1441
1536
  }
1442
1537
 
1443
1538
  // src/handlers/appointment-approve.ts
1444
- var import_scheduling15 = require("@ordinatio/scheduling");
1539
+ var import_scheduling16 = require("@ordinatio/scheduling");
1445
1540
  async function rejectAppointment(host, db, organizationId, appointment, reason) {
1446
1541
  const { id } = appointment;
1447
- const result = await (0, import_scheduling15.cancelAppointment)(db, {
1542
+ const result = await (0, import_scheduling16.cancelAppointment)(db, {
1448
1543
  appointmentId: id,
1449
1544
  cancelledBy: "staff",
1450
1545
  reason: reason || "Appointment request rejected"
@@ -1526,10 +1621,10 @@ async function approveOrReject(request, { host, params }) {
1526
1621
  if (confirmed.count === 0) {
1527
1622
  return Response.json({ error: "Appointment was already processed by a concurrent request" }, { status: 409 });
1528
1623
  }
1529
- await (0, import_scheduling15.cancelPendingNotifications)(db, id);
1624
+ await (0, import_scheduling16.cancelPendingNotifications)(db, id);
1530
1625
  const baseUrl = host.appUrl();
1531
1626
  if (!baseUrl) throw new Error("NEXT_PUBLIC_APP_URL is required");
1532
- await (0, import_scheduling15.scheduleNotifications)(db, id, baseUrl, { brand: Boolean(host.brand) });
1627
+ await (0, import_scheduling16.scheduleNotifications)(db, id, baseUrl, { brand: Boolean(host.brand) });
1533
1628
  await host.availabilityCache.invalidate(appointment.calendarId);
1534
1629
  await host.events.emit(organizationId, "appointment.confirmed", { appointmentId: id });
1535
1630
  await host.activity.log(db, {
@@ -1537,7 +1632,7 @@ async function approveOrReject(request, { host, params }) {
1537
1632
  description: `approved ${appointment.clientName}'s appointment`,
1538
1633
  metadata: { appointmentId: id, clientName: appointment.clientName }
1539
1634
  });
1540
- const confirmedAppointment = await (0, import_scheduling15.getAppointment)(db, id);
1635
+ const confirmedAppointment = await (0, import_scheduling16.getAppointment)(db, id);
1541
1636
  return Response.json({ success: true, status: "CONFIRMED", appointment: withoutManageToken(confirmedAppointment) });
1542
1637
  } catch (error) {
1543
1638
  if (getErrorCode(error) === "SCHED_306") {
@@ -1550,7 +1645,7 @@ async function approveOrReject(request, { host, params }) {
1550
1645
  }
1551
1646
 
1552
1647
  // src/handlers/appointment-reschedule.ts
1553
- var import_scheduling16 = require("@ordinatio/scheduling");
1648
+ var import_scheduling17 = require("@ordinatio/scheduling");
1554
1649
  var RESCHEDULE_BLOCKER_CODES = ["SCHED_301", "SCHED_307", "SCHED_309", "SCHED_802"];
1555
1650
  async function rescheduleByStaff(request, { host, params }) {
1556
1651
  try {
@@ -1578,21 +1673,21 @@ async function rescheduleByStaff(request, { host, params }) {
1578
1673
  if (newTime < /* @__PURE__ */ new Date()) {
1579
1674
  return Response.json({ error: "Cannot reschedule to a past time" }, { status: 400 });
1580
1675
  }
1581
- const result = await (0, import_scheduling16.rescheduleAppointment)(db, {
1676
+ const result = await (0, import_scheduling17.rescheduleAppointment)(db, {
1582
1677
  appointmentId: id,
1583
1678
  newStartTime: newTime,
1584
1679
  reason: "Rescheduled via calendar drag"
1585
1680
  });
1586
1681
  const baseUrl = host.appUrl();
1587
1682
  if (!baseUrl) throw new Error("NEXT_PUBLIC_APP_URL is required");
1588
- await (0, import_scheduling16.queueImmediateNotification)(db, id, "RESCHEDULE", baseUrl, { brand: Boolean(host.brand) });
1683
+ await (0, import_scheduling17.queueImmediateNotification)(db, id, "RESCHEDULE", baseUrl, { brand: Boolean(host.brand) });
1589
1684
  try {
1590
- await (0, import_scheduling16.scheduleNotifications)(db, id, baseUrl, { excludeTriggers: ["CONFIRMATION"], brand: Boolean(host.brand) });
1685
+ await (0, import_scheduling17.scheduleNotifications)(db, id, baseUrl, { excludeTriggers: ["CONFIRMATION"], brand: Boolean(host.brand) });
1591
1686
  } catch (error) {
1592
1687
  console.warn("[reschedule] scheduleNotifications failed:", error instanceof Error ? error.message : error);
1593
1688
  }
1594
1689
  try {
1595
- await (0, import_scheduling16.queueStaffNotification)(db, id, "RESCHEDULE", baseUrl, { brand: Boolean(host.brand) });
1690
+ await (0, import_scheduling17.queueStaffNotification)(db, id, "RESCHEDULE", baseUrl, { brand: Boolean(host.brand) });
1596
1691
  } catch (error) {
1597
1692
  await host.activity.log(db, {
1598
1693
  action: "scheduling.staff_notification_failed",
@@ -1630,8 +1725,8 @@ async function rescheduleByStaff(request, { host, params }) {
1630
1725
  });
1631
1726
  return Response.json(withoutManageToken(result));
1632
1727
  } catch (error) {
1633
- if (error instanceof import_scheduling16.SchedulingValidationError) return Response.json({ error: error.message }, { status: 400 });
1634
- if (error instanceof import_scheduling16.SchedulingNotFoundError) return Response.json({ error: error.message }, { status: 404 });
1728
+ if (error instanceof import_scheduling17.SchedulingValidationError) return Response.json({ error: error.message }, { status: 400 });
1729
+ if (error instanceof import_scheduling17.SchedulingNotFoundError) return Response.json({ error: error.message }, { status: 404 });
1635
1730
  const errorCode = getErrorCode(error) ?? "";
1636
1731
  const status = errorCode === "SCHED_306" ? 400 : RESCHEDULE_BLOCKER_CODES.includes(errorCode) ? 409 : 500;
1637
1732
  return Response.json({ error: getErrorMessage(error, "Failed to reschedule") }, { status });
@@ -1639,7 +1734,7 @@ async function rescheduleByStaff(request, { host, params }) {
1639
1734
  }
1640
1735
 
1641
1736
  // src/handlers/appointment-reassign.ts
1642
- var import_scheduling17 = require("@ordinatio/scheduling");
1737
+ var import_scheduling18 = require("@ordinatio/scheduling");
1643
1738
  var import_zod3 = require("zod");
1644
1739
  var REASSIGNABLE_STATUSES = ["PENDING", "CONFIRMED"];
1645
1740
  var REASSIGN_MAX_ATTEMPTS = 2;
@@ -1690,7 +1785,7 @@ async function reassignAppointment(request, { host, params }) {
1690
1785
  if (!current || !REASSIGNABLE_STATUSES.includes(current.status)) {
1691
1786
  return { outcome: "statusChanged", currentStatus: current?.status ?? "unknown" };
1692
1787
  }
1693
- const available = await (0, import_scheduling17.isSlotAvailable)(txDb, calendarId, current.startTime, current.duration, id);
1788
+ const available = await (0, import_scheduling18.isSlotAvailable)(txDb, calendarId, current.startTime, current.duration, id);
1694
1789
  if (!available) return { outcome: "conflict" };
1695
1790
  const updated2 = await tx.appointment.update({
1696
1791
  where: { id, status: { in: [...REASSIGNABLE_STATUSES] } },
@@ -1716,14 +1811,14 @@ async function reassignAppointment(request, { host, params }) {
1716
1811
  };
1717
1812
  const result = await attemptReassign();
1718
1813
  if (result.outcome === "statusChanged") {
1719
- const diagnostic = (0, import_scheduling17.schedError)("SCHED_309", { appointmentId: id, calendarId, currentStatus: result.currentStatus });
1814
+ const diagnostic = (0, import_scheduling18.schedError)("SCHED_309", { appointmentId: id, calendarId, currentStatus: result.currentStatus });
1720
1815
  return Response.json(
1721
1816
  { error: "Appointment status changed before the reassignment could commit", ref: diagnostic.ref },
1722
1817
  { status: 409 }
1723
1818
  );
1724
1819
  }
1725
1820
  if (result.outcome === "conflict") {
1726
- const diagnostic = (0, import_scheduling17.schedError)("SCHED_301", { appointmentId: id, calendarId });
1821
+ const diagnostic = (0, import_scheduling18.schedError)("SCHED_301", { appointmentId: id, calendarId });
1727
1822
  return Response.json(
1728
1823
  { error: "Target calendar is not available at this appointment's time", ref: diagnostic.ref },
1729
1824
  { status: 409 }
@@ -1774,9 +1869,9 @@ function invalid(error) {
1774
1869
  details: error.issues.map((e) => ({ field: e.path.join("."), message: e.message }))
1775
1870
  }, { status: 400 });
1776
1871
  }
1777
- function failure(label, error, fallback) {
1872
+ function failure(label2, error, fallback) {
1778
1873
  const ref = getErrorRef(error);
1779
- console.error(`[${label}]`, ref, error instanceof Error ? error.message : error);
1874
+ console.error(`[${label2}]`, ref, error instanceof Error ? error.message : error);
1780
1875
  return Response.json({ error: getErrorMessage(error, fallback), ...ref && { ref } }, { status: 500 });
1781
1876
  }
1782
1877
  async function updateLocation(request, { host, params }) {
@@ -1886,7 +1981,7 @@ async function listNotifications(request, { host, params }) {
1886
1981
  }
1887
1982
 
1888
1983
  // src/handlers/appointment-no-show.ts
1889
- var import_scheduling18 = require("@ordinatio/scheduling");
1984
+ var import_scheduling19 = require("@ordinatio/scheduling");
1890
1985
  async function markAppointmentNoShow(request, { host, params }) {
1891
1986
  try {
1892
1987
  const staff = await requireAdminStaff(host, request, {
@@ -1903,7 +1998,7 @@ async function markAppointmentNoShow(request, { host, params }) {
1903
1998
  }
1904
1999
  const appointment = await verifyAppointmentOwnership(db, id, organizationId);
1905
2000
  if (!appointment) return Response.json({ error: "Appointment not found" }, { status: 404 });
1906
- const result = await (0, import_scheduling18.markNoShow)(db, { appointmentId: id });
2001
+ const result = await (0, import_scheduling19.markNoShow)(db, { appointmentId: id });
1907
2002
  await host.events.emit(organizationId, "appointment.no_show", { appointmentId: id });
1908
2003
  await host.activity.log(db, {
1909
2004
  action: "scheduling.appointment_no_show",
@@ -1912,7 +2007,7 @@ async function markAppointmentNoShow(request, { host, params }) {
1912
2007
  });
1913
2008
  return Response.json(withoutManageToken(result));
1914
2009
  } catch (error) {
1915
- if (error instanceof import_scheduling18.SchedulingNotFoundError) {
2010
+ if (error instanceof import_scheduling19.SchedulingNotFoundError) {
1916
2011
  return Response.json({ error: error.message, ref: error.ref }, { status: 404 });
1917
2012
  }
1918
2013
  const ref = getErrorRef(error);
@@ -1922,7 +2017,7 @@ async function markAppointmentNoShow(request, { host, params }) {
1922
2017
  }
1923
2018
 
1924
2019
  // src/handlers/appointment-collect-balance.ts
1925
- var import_scheduling21 = require("@ordinatio/scheduling");
2020
+ var import_scheduling22 = require("@ordinatio/scheduling");
1926
2021
 
1927
2022
  // src/payments/balance/eligibility.ts
1928
2023
  var BALANCE_BLOCKED_APPOINTMENT_STATUS = "CANCELLED";
@@ -2018,7 +2113,7 @@ function resolveBalanceEligibility(appointment, organizationId) {
2018
2113
  }
2019
2114
 
2020
2115
  // src/payments/balance/record-intent.ts
2021
- var import_scheduling19 = require("@ordinatio/scheduling");
2116
+ var import_scheduling20 = require("@ordinatio/scheduling");
2022
2117
  var BALANCE_OUTCOME_TRACE = {
2023
2118
  cancelled: {
2024
2119
  action: "scheduling.balance_intent_cancelled",
@@ -2061,7 +2156,7 @@ async function recordBalanceIntent(db, payments, target) {
2061
2156
  data: { balancePaymentId: intentId }
2062
2157
  });
2063
2158
  } catch (writeError) {
2064
- const diagnostic = (0, import_scheduling19.schedError)("SCHED_605", {
2159
+ const diagnostic = (0, import_scheduling20.schedError)("SCHED_605", {
2065
2160
  error: writeError,
2066
2161
  appointmentId,
2067
2162
  paymentIntentId: intentId,
@@ -2083,7 +2178,7 @@ async function recordBalanceIntent(db, payments, target) {
2083
2178
  select: { balancePaymentId: true, status: true, refundStatus: true, paymentStatus: true }
2084
2179
  });
2085
2180
  } catch (rereadError) {
2086
- const diagnostic = (0, import_scheduling19.schedError)("SCHED_605", {
2181
+ const diagnostic = (0, import_scheduling20.schedError)("SCHED_605", {
2087
2182
  error: rereadError,
2088
2183
  appointmentId,
2089
2184
  paymentIntentId: intentId,
@@ -2100,7 +2195,7 @@ async function recordBalanceIntent(db, payments, target) {
2100
2195
  const stillEligible = current !== null && !isBalanceBlockedByStatus(current.status) && !hasBalanceRefundStarted(current.refundStatus);
2101
2196
  if (current?.balancePaymentId === intentId) {
2102
2197
  if (stillEligible) return { ok: true };
2103
- const diagnostic = (0, import_scheduling19.schedError)("SCHED_605", {
2198
+ const diagnostic = (0, import_scheduling20.schedError)("SCHED_605", {
2104
2199
  appointmentId,
2105
2200
  paymentIntentId: intentId,
2106
2201
  status: current.status,
@@ -2142,7 +2237,7 @@ async function recordBalanceIntent(db, payments, target) {
2142
2237
  outcome = "cancel-failed";
2143
2238
  }
2144
2239
  if (outcome !== cancelledOutcome) {
2145
- const diagnostic = (0, import_scheduling19.schedError)("SCHED_605", {
2240
+ const diagnostic = (0, import_scheduling20.schedError)("SCHED_605", {
2146
2241
  error: cancelError,
2147
2242
  appointmentId,
2148
2243
  paymentIntentId: intentId,
@@ -2190,7 +2285,7 @@ async function recordBalanceIntent(db, payments, target) {
2190
2285
  }
2191
2286
 
2192
2287
  // src/payments/balance/create-intent.ts
2193
- var import_scheduling20 = require("@ordinatio/scheduling");
2288
+ var import_scheduling21 = require("@ordinatio/scheduling");
2194
2289
 
2195
2290
  // src/payments/unverified-payment-error.ts
2196
2291
  var UnverifiedPaymentError = class extends Error {
@@ -2236,7 +2331,7 @@ async function createBalanceIntent(payments, input, appointmentId) {
2236
2331
  });
2237
2332
  } catch (error) {
2238
2333
  if (error instanceof UnverifiedPaymentError) {
2239
- const diagnostic2 = (0, import_scheduling20.schedError)("SCHED_605", {
2334
+ const diagnostic2 = (0, import_scheduling21.schedError)("SCHED_605", {
2240
2335
  error,
2241
2336
  appointmentId,
2242
2337
  paymentIntentId: error.paymentId,
@@ -2256,7 +2351,7 @@ async function createBalanceIntent(payments, input, appointmentId) {
2256
2351
  return { paymentId: result.paymentId, clientSecret: result.clientSecret ?? null };
2257
2352
  }
2258
2353
  if (result.code === "IN_PROGRESS") {
2259
- const diagnostic2 = (0, import_scheduling20.schedError)("SCHED_605", {
2354
+ const diagnostic2 = (0, import_scheduling21.schedError)("SCHED_605", {
2260
2355
  error: result.error,
2261
2356
  appointmentId,
2262
2357
  key,
@@ -2266,7 +2361,7 @@ async function createBalanceIntent(payments, input, appointmentId) {
2266
2361
  throw new BalanceRequestInProgressError(diagnostic2.ref);
2267
2362
  }
2268
2363
  if (result.code === "KEY_REUSED") {
2269
- const diagnostic2 = (0, import_scheduling20.schedError)("SCHED_605", {
2364
+ const diagnostic2 = (0, import_scheduling21.schedError)("SCHED_605", {
2270
2365
  error: result.error,
2271
2366
  appointmentId,
2272
2367
  abandonedKey: key,
@@ -2282,7 +2377,7 @@ async function createBalanceIntent(payments, input, appointmentId) {
2282
2377
  if (result.code === "CANCELED") continue;
2283
2378
  throw new Error(result.error ?? "The payment provider did not create the balance payment");
2284
2379
  }
2285
- const diagnostic = (0, import_scheduling20.schedError)("SCHED_605", {
2380
+ const diagnostic = (0, import_scheduling21.schedError)("SCHED_605", {
2286
2381
  appointmentId,
2287
2382
  phase: "balance-key-generations-exhausted",
2288
2383
  generations: MAX_KEY_GENERATIONS2
@@ -2374,7 +2469,7 @@ async function collectAppointmentBalance(request, { host, params }) {
2374
2469
  if (error instanceof BalanceRequestInProgressError || error instanceof BalanceIntentGenerationsExhaustedError) {
2375
2470
  return Response.json({ error: error.message, ref: error.ref }, { status: 409 });
2376
2471
  }
2377
- const diagnostic = (0, import_scheduling21.schedError)("SCHED_605", { error, appointmentId });
2472
+ const diagnostic = (0, import_scheduling22.schedError)("SCHED_605", { error, appointmentId });
2378
2473
  console.error("[POST /collect-balance]", diagnostic.ref, error instanceof Error ? error.message : error);
2379
2474
  return Response.json({ error: "Failed to create balance payment", ref: diagnostic.ref }, { status: 500 });
2380
2475
  }
@@ -2384,7 +2479,7 @@ async function collectAppointmentBalance(request, { host, params }) {
2384
2479
  var import_zod6 = require("zod");
2385
2480
 
2386
2481
  // src/payments/refund/refund-status.ts
2387
- var import_scheduling22 = require("@ordinatio/scheduling");
2482
+ var import_scheduling23 = require("@ordinatio/scheduling");
2388
2483
  var REFUND_STATUS_BUCKET = {
2389
2484
  PENDING_REVIEW: "retryable",
2390
2485
  REFUND_FAILED: "retryable",
@@ -2406,7 +2501,7 @@ var CREDIT_REFUSED_NEXT_STEP = "Retry the refund to resolve the remaining balanc
2406
2501
  var CREDIT_REFUSED_NO_AMOUNT_NEXT_STEP = "Check the refunded amount in Stripe, then retry the refund or resolve this manually before issuing a credit.";
2407
2502
  function checkCreditGuard(action, refundAmount, refundStatus) {
2408
2503
  if (refundStatus == null) {
2409
- const diagnostic = (0, import_scheduling22.schedError)("SCHED_610", {
2504
+ const diagnostic = (0, import_scheduling23.schedError)("SCHED_610", {
2410
2505
  action,
2411
2506
  refundAmount,
2412
2507
  error: "checkCreditGuard was called without a refundStatus"
@@ -2452,10 +2547,10 @@ function checkCreditGuard(action, refundAmount, refundStatus) {
2452
2547
  }
2453
2548
 
2454
2549
  // src/money.ts
2455
- var import_scheduling23 = require("@ordinatio/scheduling");
2550
+ var import_scheduling24 = require("@ordinatio/scheduling");
2456
2551
  function decimalToCents(value, field = "unknown") {
2457
2552
  if (value === null || value === void 0) {
2458
- throw new import_scheduling23.SchedulingValidationError(
2553
+ throw new import_scheduling24.SchedulingValidationError(
2459
2554
  `Could not convert ${field} to cents \u2014 value is ${value}`,
2460
2555
  "SCHED_406",
2461
2556
  { field, value }
@@ -2463,7 +2558,7 @@ function decimalToCents(value, field = "unknown") {
2463
2558
  }
2464
2559
  const cents = Math.round(Number(value) * 100);
2465
2560
  if (!Number.isFinite(cents)) {
2466
- throw new import_scheduling23.SchedulingValidationError(
2561
+ throw new import_scheduling24.SchedulingValidationError(
2467
2562
  `Could not convert ${field} to cents \u2014 value is not numeric`,
2468
2563
  "SCHED_406",
2469
2564
  { field, value }
@@ -2474,7 +2569,7 @@ function decimalToCents(value, field = "unknown") {
2474
2569
 
2475
2570
  // src/payments/refund/refund-leg.ts
2476
2571
  var import_node_crypto2 = require("crypto");
2477
- var import_scheduling24 = require("@ordinatio/scheduling");
2572
+ var import_scheduling25 = require("@ordinatio/scheduling");
2478
2573
  async function attemptLegRefund(payments, paymentIntentId, idempotencyKeySuffix, appointmentId, errorCode, logLabel) {
2479
2574
  const baseKey = `refund:${appointmentId}:${idempotencyKeySuffix}`;
2480
2575
  let idempotencyKey = baseKey;
@@ -2507,7 +2602,7 @@ async function attemptLegRefund(payments, paymentIntentId, idempotencyKeySuffix,
2507
2602
  return { succeeded: true, amountCents: null };
2508
2603
  }
2509
2604
  if (result.code === "IN_PROGRESS") {
2510
- const inFlight = (0, import_scheduling24.schedError)(errorCode, { error: result.error, appointmentId, paymentIntentId, kind: "idempotency_key_in_use" });
2605
+ const inFlight = (0, import_scheduling25.schedError)(errorCode, { error: result.error, appointmentId, paymentIntentId, kind: "idempotency_key_in_use" });
2511
2606
  console.warn(
2512
2607
  `[resolve-refund] ${logLabel} leg is already being refunded by another in-flight request (idempotency key in use) \u2014 its outcome is unknown, so this leg is recorded as retryable:`,
2513
2608
  inFlight.ref,
@@ -2532,22 +2627,22 @@ async function attemptLegRefund(payments, paymentIntentId, idempotencyKeySuffix,
2532
2627
  return failedLeg(errorCode, logLabel, appointmentId, paymentIntentId, idempotencyKey, retriedAfterReplay, { error: result.error, message: result.error ?? result.code ?? "no reason given", requestId: result.requestId });
2533
2628
  }
2534
2629
  }
2535
- function failedLeg(errorCode, logLabel, appointmentId, paymentIntentId, idempotencyKey, retriedAfterReplay, failure3) {
2536
- const diagnostic = (0, import_scheduling24.schedError)(errorCode, { error: failure3.error, appointmentId, paymentIntentId });
2630
+ function failedLeg(errorCode, logLabel, appointmentId, paymentIntentId, idempotencyKey, retriedAfterReplay, failure5) {
2631
+ const diagnostic = (0, import_scheduling25.schedError)(errorCode, { error: failure5.error, appointmentId, paymentIntentId });
2537
2632
  console.error(
2538
2633
  `[resolve-refund] ${logLabel} refund failed${retriedAfterReplay ? " (after a fresh-key re-attempt)" : ""} \u2014 manual refund may be required:`,
2539
2634
  diagnostic.ref,
2540
2635
  appointmentId,
2541
2636
  paymentIntentId,
2542
- `requestId=${failure3.requestId}`,
2637
+ `requestId=${failure5.requestId}`,
2543
2638
  `idempotencyKey=${idempotencyKey}`,
2544
- failure3.message
2639
+ failure5.message
2545
2640
  );
2546
2641
  return { succeeded: false, amountCents: null };
2547
2642
  }
2548
2643
 
2549
2644
  // src/payments/refund/persist-refund-outcome.ts
2550
- var import_scheduling25 = require("@ordinatio/scheduling");
2645
+ var import_scheduling26 = require("@ordinatio/scheduling");
2551
2646
  var WEBHOOK_RACE_OUTCOMES = ["REFUNDED", "PARTIAL_REFUND"];
2552
2647
  var SUCCESS_RANK = {
2553
2648
  REFUND_FAILED: 0,
@@ -2592,7 +2687,7 @@ async function persistRefundOutcome(db, id, refundOutcome, refundAmount, legs) {
2592
2687
  });
2593
2688
  } catch (writeErr) {
2594
2689
  const dbMessage = writeErr instanceof Error ? writeErr.message : String(writeErr);
2595
- const diagnostic = (0, import_scheduling25.schedError)("SCHED_610", {
2690
+ const diagnostic = (0, import_scheduling26.schedError)("SCHED_610", {
2596
2691
  error: writeErr,
2597
2692
  dbMessage,
2598
2693
  appointmentId: id,
@@ -2616,7 +2711,7 @@ async function persistRefundOutcome(db, id, refundOutcome, refundAmount, legs) {
2616
2711
  }
2617
2712
  if (writeResult.count === 0) {
2618
2713
  const buildLostRaceError = () => {
2619
- const diagnostic = (0, import_scheduling25.schedError)("SCHED_610", {
2714
+ const diagnostic = (0, import_scheduling26.schedError)("SCHED_610", {
2620
2715
  appointmentId: id,
2621
2716
  phase: "persist-cas-lost-race",
2622
2717
  refundOutcome,
@@ -2655,7 +2750,7 @@ async function persistRefundOutcome(db, id, refundOutcome, refundAmount, legs) {
2655
2750
  if (reconcileResult.count === 0) {
2656
2751
  throw buildLostRaceError();
2657
2752
  }
2658
- const reconcileDiagnostic = (0, import_scheduling25.schedError)("SCHED_610", {
2753
+ const reconcileDiagnostic = (0, import_scheduling26.schedError)("SCHED_610", {
2659
2754
  appointmentId: id,
2660
2755
  phase: "persist-cas-reconciled",
2661
2756
  refundOutcome,
@@ -2754,7 +2849,7 @@ async function executeRefundLegs(db, id, preClaimSnapshot, payments) {
2754
2849
  }
2755
2850
 
2756
2851
  // src/payments/refund/refund-housekeeping.ts
2757
- var import_scheduling26 = require("@ordinatio/scheduling");
2852
+ var import_scheduling27 = require("@ordinatio/scheduling");
2758
2853
  async function runHousekeeping(db, activity, appointment, id, action, newRefundStatus, userId) {
2759
2854
  const isTerminalSuccess = TERMINAL_SUCCESS_STATUSES.includes(newRefundStatus);
2760
2855
  try {
@@ -2770,7 +2865,7 @@ async function runHousekeeping(db, activity, appointment, id, action, newRefundS
2770
2865
  });
2771
2866
  return void 0;
2772
2867
  } catch (err) {
2773
- const diagnostic = (0, import_scheduling26.schedError)("SCHED_606", { error: err, appointmentId: id, phase: "housekeeping" });
2868
+ const diagnostic = (0, import_scheduling27.schedError)("SCHED_606", { error: err, appointmentId: id, phase: "housekeeping" });
2774
2869
  console.error(
2775
2870
  isTerminalSuccess ? "[resolve-refund] Sticky-activity resolution or audit log failed after a successful refund/credit:" : "[resolve-refund] Sticky-activity resolution or audit log failed after a non-terminal refund outcome (REFUND_FAILED/PARTIAL_REFUND):",
2776
2871
  diagnostic.ref,
@@ -2855,9 +2950,9 @@ async function evaluatePreClaimState(input) {
2855
2950
  }
2856
2951
 
2857
2952
  // src/payments/refund/refund-failure-response.ts
2858
- var import_scheduling27 = require("@ordinatio/scheduling");
2953
+ var import_scheduling28 = require("@ordinatio/scheduling");
2859
2954
  function refundFailureResponse({ error, id, stripeMayHaveMoved }) {
2860
- const diagnostic = (0, import_scheduling27.schedError)("SCHED_610", { error, appointmentId: id, stripeMayHaveMoved });
2955
+ const diagnostic = (0, import_scheduling28.schedError)("SCHED_610", { error, appointmentId: id, stripeMayHaveMoved });
2861
2956
  console.error("[POST /resolve-refund]", diagnostic.ref, error instanceof Error ? error.message : error);
2862
2957
  if (!stripeMayHaveMoved) {
2863
2958
  return Response.json({ error: "Failed to resolve refund", ref: diagnostic.ref }, { status: 500 });
@@ -3387,6 +3482,21 @@ var BrandSchema = import_zod14.z.object({
3387
3482
  fromEmail: optionalText(400)
3388
3483
  }).strict();
3389
3484
 
3485
+ // src/schemas/text-settings.schema.ts
3486
+ var import_zod15 = require("zod");
3487
+ var TextSettingsSchema = import_zod15.z.object({
3488
+ provider: import_zod15.z.string().max(40),
3489
+ fromNumber: import_zod15.z.string().max(40),
3490
+ enabled: import_zod15.z.boolean().optional()
3491
+ }).strict();
3492
+
3493
+ // src/schemas/api-key.schema.ts
3494
+ var import_zod16 = require("zod");
3495
+ var ApiKeySchema = import_zod16.z.object({
3496
+ name: import_zod16.z.string().max(200),
3497
+ access: import_zod16.z.string().max(20)
3498
+ }).strict();
3499
+
3390
3500
  // src/pagination.ts
3391
3501
  var DEFAULT_LIMIT = 50;
3392
3502
  var MAX_LIMIT = 200;
@@ -3408,12 +3518,12 @@ function parsePagination(request, maxLimit = MAX_LIMIT, defaultLimit = DEFAULT_L
3408
3518
  }
3409
3519
 
3410
3520
  // src/validation.ts
3411
- var import_zod15 = require("zod");
3521
+ var import_zod17 = require("zod");
3412
3522
  async function parseBody(request, schema) {
3413
3523
  try {
3414
3524
  return { success: true, data: schema.parse(await request.json()) };
3415
3525
  } catch (error) {
3416
- if (error instanceof import_zod15.ZodError) {
3526
+ if (error instanceof import_zod17.ZodError) {
3417
3527
  const details = error.issues.map((issue) => ({ field: issue.path.join("."), message: issue.message }));
3418
3528
  return { success: false, response: Response.json({ error: "Validation failed", details }, { status: 400 }) };
3419
3529
  }
@@ -3427,7 +3537,7 @@ function validateData(data, schema) {
3427
3537
  try {
3428
3538
  return { success: true, data: schema.parse(data) };
3429
3539
  } catch (error) {
3430
- if (error instanceof import_zod15.ZodError) {
3540
+ if (error instanceof import_zod17.ZodError) {
3431
3541
  return { success: false, errors: error.issues.map((issue) => ({ field: issue.path.join("."), message: issue.message })) };
3432
3542
  }
3433
3543
  return { success: false, errors: [{ field: "", message: "Validation failed" }] };
@@ -3913,7 +4023,7 @@ async function updatePackagePurchase(request, { host, params }) {
3913
4023
  }
3914
4024
 
3915
4025
  // src/handlers/admin-group-sessions.ts
3916
- var import_scheduling28 = require("@ordinatio/scheduling");
4026
+ var import_scheduling29 = require("@ordinatio/scheduling");
3917
4027
  var MAX_RANGE_MS = 366 * 24 * 60 * 60 * 1e3;
3918
4028
  async function listGroupSessions(request, { host }) {
3919
4029
  try {
@@ -3931,51 +4041,51 @@ async function listGroupSessions(request, { host }) {
3931
4041
  return Response.json({ error: "Invalid date format \u2014 use ISO 8601" }, { status: 400 });
3932
4042
  }
3933
4043
  if (startDate >= endDate) {
3934
- const err = (0, import_scheduling28.schedError)("SCHED_310", { startDateStr, endDateStr });
4044
+ const err = (0, import_scheduling29.schedError)("SCHED_310", { startDateStr, endDateStr });
3935
4045
  return Response.json({ error: "startDate must be before endDate", ref: err.ref }, { status: 400 });
3936
4046
  }
3937
4047
  if (endDate.getTime() - startDate.getTime() > MAX_RANGE_MS) {
3938
- const err = (0, import_scheduling28.schedError)("SCHED_312", { startDateStr, endDateStr });
4048
+ const err = (0, import_scheduling29.schedError)("SCHED_312", { startDateStr, endDateStr });
3939
4049
  return Response.json({ error: "Date range exceeds maximum allowed (366 days)", ref: err.ref }, { status: 400 });
3940
4050
  }
3941
4051
  const calendarId = params.get("calendarId") || void 0;
3942
4052
  const visibleCalendarIds = await staff.visibleCalendarIds();
3943
- const { sessions, hasMore } = await (0, import_scheduling28.getGroupSessions)(staff.db, { startDate, endDate, calendarId, visibleCalendarIds, organizationId: staff.organizationId });
4053
+ const { sessions, hasMore } = await (0, import_scheduling29.getGroupSessions)(staff.db, { startDate, endDate, calendarId, visibleCalendarIds, organizationId: staff.organizationId });
3944
4054
  return Response.json({ sessions, total: sessions.length, hasMore });
3945
4055
  } catch (error) {
3946
- const err = (0, import_scheduling28.schedError)("SCHED_311", { error });
4056
+ const err = (0, import_scheduling29.schedError)("SCHED_311", { error });
3947
4057
  console.error("[group-sessions]", err.ref, error);
3948
4058
  return Response.json({ error: "Failed to fetch group sessions", ref: err.ref }, { status: 500 });
3949
4059
  }
3950
4060
  }
3951
4061
 
3952
4062
  // src/handlers/admin-recurring.ts
3953
- var import_scheduling31 = require("@ordinatio/scheduling");
4063
+ var import_scheduling32 = require("@ordinatio/scheduling");
3954
4064
 
3955
4065
  // src/recurring/series-side-effects.ts
3956
- var import_scheduling29 = require("@ordinatio/scheduling");
4066
+ var import_scheduling30 = require("@ordinatio/scheduling");
3957
4067
 
3958
4068
  // src/recurring/failure-collector.ts
3959
4069
  function createFailureCollector() {
3960
4070
  const problems = /* @__PURE__ */ new Map();
3961
- const record = (label, error) => {
4071
+ const record = (label2, error) => {
3962
4072
  const message = error instanceof Error ? error.message : String(error);
3963
- const key = `${label}\0${message}`;
4073
+ const key = `${label2}\0${message}`;
3964
4074
  const known = problems.get(key);
3965
4075
  if (known) known.count += 1;
3966
- else problems.set(key, { label, message, count: 1 });
4076
+ else problems.set(key, { label: label2, message, count: 1 });
3967
4077
  };
3968
- const attempt = async (label, work) => {
4078
+ const attempt = async (label2, work) => {
3969
4079
  try {
3970
4080
  await work();
3971
4081
  return true;
3972
4082
  } catch (error) {
3973
- record(label, error);
4083
+ record(label2, error);
3974
4084
  return false;
3975
4085
  }
3976
4086
  };
3977
4087
  const lines = () => [...problems.values()].map(
3978
- ({ label, message, count }) => count === 1 ? `${label} failed: ${message}` : `${label} failed for ${count} visits: ${message}`
4088
+ ({ label: label2, message, count }) => count === 1 ? `${label2} failed: ${message}` : `${label2} failed for ${count} visits: ${message}`
3979
4089
  );
3980
4090
  return { record, attempt, lines };
3981
4091
  }
@@ -4017,7 +4127,7 @@ async function runSeriesSideEffects(host, db, organizationId, seriesId, client)
4017
4127
  const sendConfirmation = async (url, appointmentId) => {
4018
4128
  for (let tryNumber = 1; tryNumber <= 2; tryNumber += 1) {
4019
4129
  try {
4020
- await (0, import_scheduling29.scheduleNotifications)(db, appointmentId, url, { brand: Boolean(host.brand) });
4130
+ await (0, import_scheduling30.scheduleNotifications)(db, appointmentId, url, { brand: Boolean(host.brand) });
4021
4131
  return;
4022
4132
  } catch (error) {
4023
4133
  if (tryNumber === 2) record("Client confirmation", error);
@@ -4030,7 +4140,7 @@ async function runSeriesSideEffects(host, db, organizationId, seriesId, client)
4030
4140
  await sendConfirmation(baseUrl, visit.id);
4031
4141
  } else {
4032
4142
  await attempt("Client notices", async () => {
4033
- await (0, import_scheduling29.scheduleNotifications)(db, visit.id, baseUrl, { excludeTriggers: ["CONFIRMATION"], brand: Boolean(host.brand) });
4143
+ await (0, import_scheduling30.scheduleNotifications)(db, visit.id, baseUrl, { excludeTriggers: ["CONFIRMATION"], brand: Boolean(host.brand) });
4034
4144
  });
4035
4145
  }
4036
4146
  }
@@ -4050,7 +4160,7 @@ async function runSeriesSideEffects(host, db, organizationId, seriesId, client)
4050
4160
  await Promise.all(visits.slice(from, from + VISITS_PER_GROUP).map(handleVisit));
4051
4161
  }
4052
4162
  if (baseUrl && confirmationVisit) {
4053
- await attempt("Staff alert", () => (0, import_scheduling29.queueStaffNotification)(db, confirmationVisit.id, "CONFIRMATION", baseUrl, { brand: Boolean(host.brand) }));
4163
+ await attempt("Staff alert", () => (0, import_scheduling30.queueStaffNotification)(db, confirmationVisit.id, "CONFIRMATION", baseUrl, { brand: Boolean(host.brand) }));
4054
4164
  }
4055
4165
  await attempt("Availability cache", () => host.availabilityCache.invalidate(first.calendarId));
4056
4166
  await attempt(
@@ -4066,11 +4176,11 @@ async function runSeriesSideEffects(host, db, organizationId, seriesId, client)
4066
4176
  }
4067
4177
 
4068
4178
  // src/recurring/validate-timezone.ts
4069
- var import_scheduling30 = require("@ordinatio/scheduling");
4179
+ var import_scheduling31 = require("@ordinatio/scheduling");
4070
4180
  var SUPPORTED_TIMEZONES = new Set(Intl.supportedValuesOf("timeZone"));
4071
4181
  function validateRecurringTimezone(timezone) {
4072
4182
  if (isValidIanaTimezone(timezone)) return null;
4073
- const err = (0, import_scheduling30.schedError)("SCHED_704", { timezone });
4183
+ const err = (0, import_scheduling31.schedError)("SCHED_704", { timezone });
4074
4184
  return Response.json({ error: err.description, ref: err.ref }, { status: 422 });
4075
4185
  }
4076
4186
  function isValidIanaTimezone(timezone) {
@@ -4123,12 +4233,12 @@ async function createRecurringSeries(request, { host }) {
4123
4233
  const validation = await parseBody(request, CreateRecurringSeriesSchema);
4124
4234
  if (!validation.success) return validation.response;
4125
4235
  const input = validation.data;
4126
- if (input.occurrences < 1 || input.occurrences > import_scheduling31.RECURRING_MAX_OCCURRENCES) {
4127
- const err = (0, import_scheduling31.schedError)("SCHED_701", { occurrences: input.occurrences });
4236
+ if (input.occurrences < 1 || input.occurrences > import_scheduling32.RECURRING_MAX_OCCURRENCES) {
4237
+ const err = (0, import_scheduling32.schedError)("SCHED_701", { occurrences: input.occurrences });
4128
4238
  return Response.json({ error: err.description, ref: err.ref }, { status: 422 });
4129
4239
  }
4130
- if (!(0, import_scheduling31.parseTimeLocal)(input.startTimeLocal)) {
4131
- const err = (0, import_scheduling31.schedError)("SCHED_700", { startTimeLocal: input.startTimeLocal });
4240
+ if (!(0, import_scheduling32.parseTimeLocal)(input.startTimeLocal)) {
4241
+ const err = (0, import_scheduling32.schedError)("SCHED_700", { startTimeLocal: input.startTimeLocal });
4132
4242
  return Response.json({ error: err.description, ref: err.ref }, { status: 422 });
4133
4243
  }
4134
4244
  const tzError = validateRecurringTimezone(input.timezone);
@@ -4157,7 +4267,7 @@ async function createRecurringSeries(request, { host }) {
4157
4267
  });
4158
4268
  const firstDate = new Date(input.firstDate);
4159
4269
  const endsAt = input.endsAt ? new Date(input.endsAt) : void 0;
4160
- const slots = (0, import_scheduling31.buildRecurringSlots)(
4270
+ const slots = (0, import_scheduling32.buildRecurringSlots)(
4161
4271
  firstDate,
4162
4272
  input.frequency,
4163
4273
  input.occurrences,
@@ -4246,17 +4356,17 @@ async function createRecurringSeries(request, { host }) {
4246
4356
  }
4247
4357
 
4248
4358
  // src/handlers/admin-recurring-detail.ts
4249
- var import_scheduling33 = require("@ordinatio/scheduling");
4359
+ var import_scheduling34 = require("@ordinatio/scheduling");
4250
4360
 
4251
4361
  // src/recurring/series-cancel-side-effects.ts
4252
- var import_scheduling32 = require("@ordinatio/scheduling");
4362
+ var import_scheduling33 = require("@ordinatio/scheduling");
4253
4363
  var OCCURRENCES_PER_GROUP = 8;
4254
4364
  async function runSeriesCancelSideEffects(host, db, organizationId, seriesId, seriesCalendarId, occurrences) {
4255
4365
  if (occurrences.length === 0) return { failures: [] };
4256
4366
  const { attempt, record, lines } = createFailureCollector();
4257
4367
  const handle = async (occurrence) => {
4258
4368
  const { id } = occurrence;
4259
- await attempt("Pending reminders", () => (0, import_scheduling32.cancelPendingNotifications)(db, id));
4369
+ await attempt("Pending reminders", () => (0, import_scheduling33.cancelPendingNotifications)(db, id));
4260
4370
  const hasPayment = hasPendingPayment(occurrence.paymentId, occurrence.paymentStatus);
4261
4371
  await attempt("Refund review flag", async () => {
4262
4372
  await writeRefundStatusAfterCancel(host, db, { appointmentId: id, hasPayment, clientName: occurrence.clientName });
@@ -4288,7 +4398,7 @@ async function runSeriesCancelSideEffects(host, db, organizationId, seriesId, se
4288
4398
  }
4289
4399
  const baseUrl = host.appUrl()?.trim();
4290
4400
  if (baseUrl) {
4291
- await attempt("Staff notice", () => (0, import_scheduling32.queueStaffNotification)(db, occurrences[0].id, "CANCELLATION", baseUrl, { brand: Boolean(host.brand) }));
4401
+ await attempt("Staff notice", () => (0, import_scheduling33.queueStaffNotification)(db, occurrences[0].id, "CANCELLATION", baseUrl, { brand: Boolean(host.brand) }));
4292
4402
  } else {
4293
4403
  record("Staff notice", "skipped because the application address is not set");
4294
4404
  }
@@ -4334,7 +4444,7 @@ async function getRecurringSeries(request, { host, params }) {
4334
4444
  }
4335
4445
  });
4336
4446
  if (!series || !await staff.canSeeCalendar(series.calendar.id)) {
4337
- const err = (0, import_scheduling33.schedError)("SCHED_702", { seriesId: id, organizationId });
4447
+ const err = (0, import_scheduling34.schedError)("SCHED_702", { seriesId: id, organizationId });
4338
4448
  return Response.json({ error: err.description, ref: err.ref }, { status: 404 });
4339
4449
  }
4340
4450
  return Response.json({ series });
@@ -4361,14 +4471,14 @@ async function cancelRecurringSeries(request, { host, params }) {
4361
4471
  select: { id: true, status: true, clientName: true, clientEmail: true, frequency: true, occurrences: true, calendarId: true }
4362
4472
  });
4363
4473
  if (!series) {
4364
- const err = (0, import_scheduling33.schedError)("SCHED_702", { seriesId: id, organizationId });
4474
+ const err = (0, import_scheduling34.schedError)("SCHED_702", { seriesId: id, organizationId });
4365
4475
  return Response.json({ error: err.description, ref: err.ref }, { status: 404 });
4366
4476
  }
4367
4477
  if (!await staff.canSeeCalendar(series.calendarId)) {
4368
4478
  return Response.json({ error: "Calendar not found" }, { status: 404 });
4369
4479
  }
4370
4480
  if ((input.scope === "ONE" || input.scope === "THIS_AND_FOLLOWING") && !input.fromAppointmentId) {
4371
- const err = (0, import_scheduling33.schedError)("SCHED_703", { scope: input.scope });
4481
+ const err = (0, import_scheduling34.schedError)("SCHED_703", { scope: input.scope });
4372
4482
  return Response.json({ error: err.description, ref: err.ref }, { status: 422 });
4373
4483
  }
4374
4484
  const NON_CANCELLABLE_STATUSES = ["CANCELLED", "COMPLETED", "NO_SHOW"];
@@ -4396,7 +4506,7 @@ async function cancelRecurringSeries(request, { host, params }) {
4396
4506
  if (hiddenCalendars) {
4397
4507
  const hidden = await db.appointment.count({ where: { ...open, calendar: { organizationId, NOT: hiddenCalendars } } });
4398
4508
  if (hidden > 0) {
4399
- const err = (0, import_scheduling33.schedError)("SCHED_702", { seriesId: id, organizationId, reason: "open occurrence on a calendar outside the viewer scope" });
4509
+ const err = (0, import_scheduling34.schedError)("SCHED_702", { seriesId: id, organizationId, reason: "open occurrence on a calendar outside the viewer scope" });
4400
4510
  return Response.json({ error: err.description, ref: err.ref }, { status: 404 });
4401
4511
  }
4402
4512
  }
@@ -4429,7 +4539,7 @@ async function cancelRecurringSeries(request, { host, params }) {
4429
4539
  return Response.json({ cancelledCount, newSeriesStatus, ...warnings.length > 0 && { warnings } });
4430
4540
  } catch (error) {
4431
4541
  if (error?.code === "P2025") {
4432
- const err = (0, import_scheduling33.schedError)("SCHED_702", { race: "series vanished between org-scoped pre-check and cancellation transaction" });
4542
+ const err = (0, import_scheduling34.schedError)("SCHED_702", { race: "series vanished between org-scoped pre-check and cancellation transaction" });
4433
4543
  return Response.json({ error: err.description, ref: err.ref }, { status: 404 });
4434
4544
  }
4435
4545
  return Response.json({ error: getErrorMessage(error, "Failed to cancel recurring series") }, { status: 500 });
@@ -4437,7 +4547,7 @@ async function cancelRecurringSeries(request, { host, params }) {
4437
4547
  }
4438
4548
 
4439
4549
  // src/handlers/booking-analytics.ts
4440
- var import_scheduling34 = require("@ordinatio/scheduling");
4550
+ var import_scheduling35 = require("@ordinatio/scheduling");
4441
4551
  async function getAnalytics(request, { host }) {
4442
4552
  try {
4443
4553
  const staff = await host.staff.resolve(request);
@@ -4449,7 +4559,7 @@ async function getAnalytics(request, { host }) {
4449
4559
  const limited = await host.rateLimit(`analytics:${ip}`, "GENERAL");
4450
4560
  if (limited) return limited;
4451
4561
  if (!staff.isAdmin) {
4452
- const err = (0, import_scheduling34.schedError)("SCHED_900", { userId: staff.userId, role: staff.role });
4562
+ const err = (0, import_scheduling35.schedError)("SCHED_900", { userId: staff.userId, role: staff.role });
4453
4563
  return Response.json({ error: "Forbidden", ref: err.ref }, { status: 403 });
4454
4564
  }
4455
4565
  const params = new URL(request.url).searchParams;
@@ -4475,7 +4585,7 @@ async function getAnalytics(request, { host }) {
4475
4585
  }
4476
4586
  }
4477
4587
  const visibleCalendarIds = await staff.visibleCalendarIds();
4478
- const analytics = await (0, import_scheduling34.getBookingAnalytics)(staff.db, { days, calendarId, visibleCalendarIds, organizationId: staff.organizationId });
4588
+ const analytics = await (0, import_scheduling35.getBookingAnalytics)(staff.db, { days, calendarId, visibleCalendarIds, organizationId: staff.organizationId });
4479
4589
  return Response.json(analytics);
4480
4590
  } catch (error) {
4481
4591
  const ref = getErrorRef(error);
@@ -4494,11 +4604,11 @@ function escapeHtml(text) {
4494
4604
  }
4495
4605
 
4496
4606
  // src/brand/brand-http.ts
4497
- var import_scheduling35 = require("@ordinatio/scheduling");
4607
+ var import_scheduling36 = require("@ordinatio/scheduling");
4498
4608
  var NOT_ENABLED = { error: "Branding is not enabled on this server" };
4499
4609
  function brandErrorResponse(error, fallback, cors) {
4500
4610
  const send = (payload, status) => cors ? corsJson(cors, payload, { status }) : Response.json(payload, { status });
4501
- if (error instanceof import_scheduling35.SchedulingValidationError) {
4611
+ if (error instanceof import_scheduling36.SchedulingValidationError) {
4502
4612
  const details = error.context.errors;
4503
4613
  return send({ error: error.message, code: error.code, ref: getErrorRef(error), ...details ? { details } : {} }, 400);
4504
4614
  }
@@ -4514,7 +4624,7 @@ async function requireBrandAdmin(host, request, options) {
4514
4624
  async function businessName(host, db, organizationId) {
4515
4625
  if (host.brand) {
4516
4626
  try {
4517
- const brand = await (0, import_scheduling35.getBrand)(db, organizationId);
4627
+ const brand = await (0, import_scheduling36.getBrand)(db, organizationId);
4518
4628
  if (brand) return brand.displayName;
4519
4629
  } catch (error) {
4520
4630
  console.error("[brand] could not read the brand for a message:", error);
@@ -4525,9 +4635,9 @@ async function businessName(host, db, organizationId) {
4525
4635
 
4526
4636
  // src/handlers/appointment-messages.ts
4527
4637
  var NOT_FOUND4 = () => Response.json({ error: "Appointment not found" }, { status: 404 });
4528
- function failure2(label, error, fallback) {
4638
+ function failure2(label2, error, fallback) {
4529
4639
  const ref = getErrorRef(error);
4530
- console.error(`[${label}]`, ref, error instanceof Error ? error.message : error);
4640
+ console.error(`[${label2}]`, ref, error instanceof Error ? error.message : error);
4531
4641
  return Response.json({ error: getErrorMessage(error, fallback), ...ref && { ref } }, { status: 500 });
4532
4642
  }
4533
4643
  async function sendFollowup(request, { host, params }) {
@@ -4682,7 +4792,7 @@ We look forward to seeing you!
4682
4792
  }
4683
4793
 
4684
4794
  // src/handlers/calendar-ownership.ts
4685
- var import_scheduling36 = require("@ordinatio/scheduling");
4795
+ var import_scheduling37 = require("@ordinatio/scheduling");
4686
4796
  var SAFE_CALENDAR_FIELDS = [
4687
4797
  "id",
4688
4798
  "organizationId",
@@ -4749,7 +4859,7 @@ async function getOwnedCalendarForRoute(db, id, organizationId) {
4749
4859
  async function validateStaffLink(host, userId, organizationId) {
4750
4860
  if (!userId) return null;
4751
4861
  if (await host.staffDirectory.isMember(organizationId, userId)) return null;
4752
- const err = (0, import_scheduling36.schedError)("SCHED_104", { userId, organizationId });
4862
+ const err = (0, import_scheduling37.schedError)("SCHED_104", { userId, organizationId });
4753
4863
  return Response.json({ error: "That staff member is not part of this organization", ref: err.ref }, { status: 400 });
4754
4864
  }
4755
4865
  function buildCalendarUpdateData(input) {
@@ -4796,7 +4906,7 @@ async function releaseCalendarSlugIfStillInactive(host, db, calendarId, organiza
4796
4906
  }
4797
4907
  async function undoArchive(host, db, calendarId, organizationId, slug) {
4798
4908
  try {
4799
- await (0, import_scheduling36.updateCalendar)(db, calendarId, organizationId, { isActive: true });
4909
+ await (0, import_scheduling37.updateCalendar)(db, calendarId, organizationId, { isActive: true });
4800
4910
  } catch (restoreError) {
4801
4911
  console.error("[calendar update] could not switch the calendar back on after a failed update", calendarId, restoreError);
4802
4912
  try {
@@ -4895,7 +5005,7 @@ async function createCalendar(request, { host }) {
4895
5005
  }
4896
5006
 
4897
5007
  // src/handlers/admin-calendar-update.ts
4898
- var import_scheduling37 = require("@ordinatio/scheduling");
5008
+ var import_scheduling38 = require("@ordinatio/scheduling");
4899
5009
  var NOT_FOUND5 = () => Response.json({ error: "Calendar not found" }, { status: 404 });
4900
5010
  async function getCalendar(request, { host, params }) {
4901
5011
  try {
@@ -4937,10 +5047,10 @@ async function putCalendar(request, { host, params }) {
4937
5047
  let updated;
4938
5048
  try {
4939
5049
  if (archiving) {
4940
- await (0, import_scheduling37.archiveCalendar)(db, id, organizationId);
5050
+ await (0, import_scheduling38.archiveCalendar)(db, id, organizationId);
4941
5051
  archived = true;
4942
5052
  }
4943
- ({ calendar: updated } = await (0, import_scheduling37.updateCalendar)(db, id, organizationId, buildCalendarUpdateData(input)));
5053
+ ({ calendar: updated } = await (0, import_scheduling38.updateCalendar)(db, id, organizationId, buildCalendarUpdateData(input)));
4944
5054
  } catch (error) {
4945
5055
  if (archived) await undoArchive(host, db, id, organizationId, existing.slug);
4946
5056
  throw error;
@@ -4969,7 +5079,7 @@ async function deleteCalendar(request, { host, params }) {
4969
5079
  if (!await staff.canSeeCalendar(id)) return NOT_FOUND5();
4970
5080
  const existing = await getOwnedCalendarForRoute(db, id, organizationId);
4971
5081
  if (!existing) return NOT_FOUND5();
4972
- await (0, import_scheduling37.archiveCalendar)(db, id, organizationId);
5082
+ await (0, import_scheduling38.archiveCalendar)(db, id, organizationId);
4973
5083
  await releaseCalendarSlugIfStillInactive(host, db, id, organizationId, existing.slug);
4974
5084
  await bustCalendarCachesOnArchive(host, organizationId, existing.slug, id);
4975
5085
  await host.activity.log(db, {
@@ -5120,7 +5230,7 @@ async function disconnectOutlook(request, { host, params }) {
5120
5230
  }
5121
5231
 
5122
5232
  // src/handlers/admin-calendar-location-recents.ts
5123
- var import_scheduling38 = require("@ordinatio/scheduling");
5233
+ var import_scheduling39 = require("@ordinatio/scheduling");
5124
5234
  async function getLocationRecents(request, { host, params }) {
5125
5235
  try {
5126
5236
  const staff = await requireAdminStaff(host, request, {
@@ -5165,14 +5275,14 @@ async function getLocationRecents(request, { host, params }) {
5165
5275
  }
5166
5276
  return Response.json({ locations });
5167
5277
  } catch (error) {
5168
- const diagnostic = (0, import_scheduling38.schedError)("SCHED_207", { error });
5278
+ const diagnostic = (0, import_scheduling39.schedError)("SCHED_207", { error });
5169
5279
  console.error("[location-recents]", diagnostic.ref, error);
5170
5280
  return Response.json({ error: "Failed to fetch location recents", ref: diagnostic.ref }, { status: 500 });
5171
5281
  }
5172
5282
  }
5173
5283
 
5174
5284
  // src/handlers/admin-availability-rules.ts
5175
- var import_scheduling39 = require("@ordinatio/scheduling");
5285
+ var import_scheduling40 = require("@ordinatio/scheduling");
5176
5286
 
5177
5287
  // src/availability/admin-calendar.ts
5178
5288
  async function verifyCalendar(db, calendarId, organizationId) {
@@ -5246,7 +5356,7 @@ async function listRules(request, { host, params }) {
5246
5356
  const calendar = await requireOwnedVisibleCalendar(staff, calendarId);
5247
5357
  if (calendar instanceof Response) return calendar;
5248
5358
  const { limit, offset } = parsePagination(request, 500, 200);
5249
- const { rules, total, hasMore } = await (0, import_scheduling39.listAvailabilityRules)(staff.db, calendarId, { limit, offset });
5359
+ const { rules, total, hasMore } = await (0, import_scheduling40.listAvailabilityRules)(staff.db, calendarId, { limit, offset });
5250
5360
  return Response.json({ rules, total, hasMore });
5251
5361
  } catch (error) {
5252
5362
  return Response.json({ error: getErrorMessage(error, "Failed to fetch availability") }, { status: 500 });
@@ -5265,7 +5375,7 @@ async function setWeeklyRules(request, { host, params }) {
5265
5375
  if (!Array.isArray(rules)) return Response.json({ error: "rules must be an array" }, { status: 400 });
5266
5376
  const validationError = validateWeeklyRules(rules);
5267
5377
  if (validationError) return Response.json({ error: validationError }, { status: 400 });
5268
- const created = await (0, import_scheduling39.setWeeklyAvailability)(db, calendarId, rules);
5378
+ const created = await (0, import_scheduling40.setWeeklyAvailability)(db, calendarId, rules);
5269
5379
  await clearAvailabilityCache(host, calendarId);
5270
5380
  const activeDays = rules.map((r) => ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][r.dayOfWeek]).join(", ");
5271
5381
  await host.activity.log(db, {
@@ -5276,7 +5386,7 @@ async function setWeeklyRules(request, { host, params }) {
5276
5386
  return Response.json(created);
5277
5387
  } catch (error) {
5278
5388
  const msg = getErrorMessage(error, "Failed to update availability");
5279
- if (error instanceof import_scheduling39.SchedulingValidationError) {
5389
+ if (error instanceof import_scheduling40.SchedulingValidationError) {
5280
5390
  console.error("[PUT /admin/availability]", error.ref, error.code, error.context);
5281
5391
  return Response.json({ error: msg, ref: error.ref }, { status: 400 });
5282
5392
  }
@@ -5285,18 +5395,18 @@ async function setWeeklyRules(request, { host, params }) {
5285
5395
  }
5286
5396
 
5287
5397
  // src/handlers/admin-availability-overrides.ts
5288
- var import_scheduling41 = require("@ordinatio/scheduling");
5398
+ var import_scheduling42 = require("@ordinatio/scheduling");
5289
5399
 
5290
5400
  // src/availability/override-helpers.ts
5291
- var import_scheduling40 = require("@ordinatio/scheduling");
5401
+ var import_scheduling41 = require("@ordinatio/scheduling");
5292
5402
  function sanitizeBlockReason(raw) {
5293
5403
  if (!raw) return void 0;
5294
5404
  return String(raw).replace(/<script[^>]*>[\s\S]*?<\/script>/gi, "").replace(/<style[^>]*>[\s\S]*?<\/style>/gi, "").replace(/<[^>]*>/g, "").slice(0, 500).trim() || void 0;
5295
5405
  }
5296
5406
  async function checkOverlappingAppointments(db, calendarId, calendarTimezone, dateStr, startTime, endTime) {
5297
5407
  const tz = calendarTimezone ?? "America/New_York";
5298
- const blockStart = (0, import_scheduling40.localToUTC)(dateStr, startTime, tz);
5299
- const blockEnd = (0, import_scheduling40.localToUTC)(dateStr, endTime, tz);
5408
+ const blockStart = (0, import_scheduling41.localToUTC)(dateStr, startTime, tz);
5409
+ const blockEnd = (0, import_scheduling41.localToUTC)(dateStr, endTime, tz);
5300
5410
  const conflictCount = await db.appointment.count({
5301
5411
  where: {
5302
5412
  calendarId,
@@ -5326,14 +5436,14 @@ async function addOverride(request, { host, params }) {
5326
5436
  const isBlockedFlag = body.isBlocked ?? true;
5327
5437
  let override;
5328
5438
  if (isBlockedFlag && body.startTime && body.endTime) {
5329
- override = await (0, import_scheduling41.addTimeBlock)(db, calendarId, {
5439
+ override = await (0, import_scheduling42.addTimeBlock)(db, calendarId, {
5330
5440
  date,
5331
5441
  startTime: body.startTime,
5332
5442
  endTime: body.endTime,
5333
5443
  reason: blockReason
5334
5444
  });
5335
5445
  } else {
5336
- override = await (0, import_scheduling41.addDateOverride)(db, calendarId, {
5446
+ override = await (0, import_scheduling42.addDateOverride)(db, calendarId, {
5337
5447
  date,
5338
5448
  isBlocked: isBlockedFlag,
5339
5449
  blockReason,
@@ -5370,7 +5480,7 @@ async function addOverride(request, { host, params }) {
5370
5480
  return Response.json({ ...override, ...overlapWarning && { warning: overlapWarning } }, { status: 201 });
5371
5481
  } catch (error) {
5372
5482
  const msg = getErrorMessage(error, "Failed to add override");
5373
- if (error instanceof import_scheduling41.SchedulingValidationError) {
5483
+ if (error instanceof import_scheduling42.SchedulingValidationError) {
5374
5484
  console.error("[POST /admin/availability]", error.ref, error.code, error.context);
5375
5485
  return Response.json({ error: msg, ref: error.ref }, { status: 400 });
5376
5486
  }
@@ -5387,7 +5497,7 @@ async function removeOverride(request, { host, params }) {
5387
5497
  if (calendar instanceof Response) return calendar;
5388
5498
  const { ruleId } = await request.json();
5389
5499
  if (!ruleId) return Response.json({ error: "ruleId is required" }, { status: 400 });
5390
- const deletedRule = await (0, import_scheduling41.removeDateOverride)(db, calendarId, ruleId);
5500
+ const deletedRule = await (0, import_scheduling42.removeDateOverride)(db, calendarId, ruleId);
5391
5501
  await clearAvailabilityCache(host, calendarId);
5392
5502
  const deletedIsTimeBlock = deletedRule?.isBlocked && !(deletedRule.startTime === "00:00" && deletedRule.endTime === "00:00");
5393
5503
  await host.activity.log(db, {
@@ -5398,7 +5508,7 @@ async function removeOverride(request, { host, params }) {
5398
5508
  return Response.json({ success: true });
5399
5509
  } catch (error) {
5400
5510
  const msg = getErrorMessage(error, "Failed to remove override");
5401
- if (error instanceof import_scheduling41.SchedulingNotFoundError) {
5511
+ if (error instanceof import_scheduling42.SchedulingNotFoundError) {
5402
5512
  console.error("[DELETE /admin/availability]", error.ref, error.code, error.context);
5403
5513
  return Response.json({ error: msg, ref: error.ref }, { status: 404 });
5404
5514
  }
@@ -5407,7 +5517,7 @@ async function removeOverride(request, { host, params }) {
5407
5517
  }
5408
5518
 
5409
5519
  // src/handlers/admin-templates.ts
5410
- var import_scheduling42 = require("@ordinatio/scheduling");
5520
+ var import_scheduling43 = require("@ordinatio/scheduling");
5411
5521
 
5412
5522
  // src/sanitize/notification-body.ts
5413
5523
  var import_sanitize_html = __toESM(require("sanitize-html"));
@@ -5431,7 +5541,7 @@ async function listTemplates(request, { host }) {
5431
5541
  try {
5432
5542
  const staff = await requireAdminStaff(host, request, { action: "admin-templates-list", tier: "GENERAL" });
5433
5543
  if (staff instanceof Response) return staff;
5434
- return Response.json(await (0, import_scheduling42.listNotificationTemplates)(staff.db, staff.organizationId));
5544
+ return Response.json(await (0, import_scheduling43.listNotificationTemplates)(staff.db, staff.organizationId));
5435
5545
  } catch (error) {
5436
5546
  return Response.json({ error: getErrorMessage(error, "Failed to fetch templates") }, { status: 500 });
5437
5547
  }
@@ -5456,7 +5566,7 @@ async function createTemplate(request, { host }) {
5456
5566
  if (input.channel === "EMAIL" && !stripHtml(input.subject).trim()) {
5457
5567
  return Response.json({ error: "EMAIL templates require a subject" }, { status: 400 });
5458
5568
  }
5459
- const template = await (0, import_scheduling42.createNotificationTemplate)(db, organizationId, {
5569
+ const template = await (0, import_scheduling43.createNotificationTemplate)(db, organizationId, {
5460
5570
  name: input.name,
5461
5571
  channel: input.channel,
5462
5572
  trigger: input.trigger,
@@ -5482,7 +5592,7 @@ async function createTemplate(request, { host }) {
5482
5592
  }
5483
5593
 
5484
5594
  // src/handlers/admin-template-update.ts
5485
- var import_scheduling43 = require("@ordinatio/scheduling");
5595
+ var import_scheduling44 = require("@ordinatio/scheduling");
5486
5596
  async function updateTemplate(request, { host, params }) {
5487
5597
  try {
5488
5598
  const staff = await requireAdminStaff(host, request, { action: "admin-templates-update", tier: "UPDATE" });
@@ -5514,7 +5624,7 @@ async function updateTemplate(request, { host, params }) {
5514
5624
  return Response.json({ error: "EMAIL templates require a subject" }, { status: 400 });
5515
5625
  }
5516
5626
  }
5517
- const updated = await (0, import_scheduling43.updateNotificationTemplate)(db, organizationId, id, {
5627
+ const updated = await (0, import_scheduling44.updateNotificationTemplate)(db, organizationId, id, {
5518
5628
  name: input.name,
5519
5629
  subject: sanitizedSubject,
5520
5630
  body: input.body !== void 0 ? sanitizeNotificationBody(input.body, existing.channel) : void 0,
@@ -5528,11 +5638,11 @@ async function updateTemplate(request, { host, params }) {
5528
5638
  return Response.json(updated);
5529
5639
  } catch (error) {
5530
5640
  const msg = getErrorMessage(error, "Failed to update template");
5531
- if (error instanceof import_scheduling43.SchedulingValidationError) {
5641
+ if (error instanceof import_scheduling44.SchedulingValidationError) {
5532
5642
  console.error("[PUT /admin/templates]", error.ref, error.code, error.context);
5533
5643
  return Response.json({ error: msg, ref: error.ref }, { status: 400 });
5534
5644
  }
5535
- if (error instanceof import_scheduling43.SchedulingNotFoundError) {
5645
+ if (error instanceof import_scheduling44.SchedulingNotFoundError) {
5536
5646
  console.error("[PUT /admin/templates]", error.ref, error.code, error.context);
5537
5647
  return Response.json({ error: msg, ref: error.ref }, { status: 404 });
5538
5648
  }
@@ -5549,7 +5659,7 @@ async function deleteTemplate(request, { host, params }) {
5549
5659
  where: { id, organizationId },
5550
5660
  select: { name: true }
5551
5661
  });
5552
- await (0, import_scheduling43.deleteNotificationTemplate)(db, organizationId, id);
5662
+ await (0, import_scheduling44.deleteNotificationTemplate)(db, organizationId, id);
5553
5663
  await host.activity.log(db, {
5554
5664
  action: "scheduling.template_deleted",
5555
5665
  description: `deleted notification template "${template?.name || id}"`,
@@ -5558,7 +5668,7 @@ async function deleteTemplate(request, { host, params }) {
5558
5668
  return Response.json({ success: true });
5559
5669
  } catch (error) {
5560
5670
  const msg = getErrorMessage(error, "Failed to delete template");
5561
- if (error instanceof import_scheduling43.SchedulingNotFoundError) {
5671
+ if (error instanceof import_scheduling44.SchedulingNotFoundError) {
5562
5672
  console.error("[DELETE /admin/templates]", error.ref, error.code, error.context);
5563
5673
  return Response.json({ error: msg, ref: error.ref }, { status: 404 });
5564
5674
  }
@@ -5567,7 +5677,7 @@ async function deleteTemplate(request, { host, params }) {
5567
5677
  }
5568
5678
 
5569
5679
  // src/handlers/admin-types.ts
5570
- var import_scheduling44 = require("@ordinatio/scheduling");
5680
+ var import_scheduling45 = require("@ordinatio/scheduling");
5571
5681
  async function listTypes(request, { host }) {
5572
5682
  try {
5573
5683
  const staff = await requireAdminStaff(host, request, { action: "admin-types-list", tier: "GENERAL" });
@@ -5597,7 +5707,7 @@ async function createType(request, { host }) {
5597
5707
  if (!validation.success) return validation.response;
5598
5708
  if (!organizationId) return Response.json({ error: "Organization context required" }, { status: 400 });
5599
5709
  const input = validation.data;
5600
- const type = await (0, import_scheduling44.createAppointmentType)(db, {
5710
+ const type = await (0, import_scheduling45.createAppointmentType)(db, {
5601
5711
  name: input.name,
5602
5712
  slug: input.name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, ""),
5603
5713
  description: input.description || void 0,
@@ -5656,7 +5766,7 @@ async function createType(request, { host }) {
5656
5766
  }
5657
5767
 
5658
5768
  // src/handlers/admin-type-update.ts
5659
- var import_scheduling45 = require("@ordinatio/scheduling");
5769
+ var import_scheduling46 = require("@ordinatio/scheduling");
5660
5770
 
5661
5771
  // src/handlers/type-ownership.ts
5662
5772
  async function getOwnedAppointmentType(db, id, organizationId) {
@@ -5737,7 +5847,7 @@ async function updateType(request, { host, params }) {
5737
5847
  const validation = await parseBody(request, UpdateAppointmentTypeSchema);
5738
5848
  if (!validation.success) return validation.response;
5739
5849
  const input = validation.data;
5740
- const { type: updated, wasActive } = await (0, import_scheduling45.updateAppointmentType)(db, id, organizationId, input);
5850
+ const { type: updated, wasActive } = await (0, import_scheduling46.updateAppointmentType)(db, id, organizationId, input);
5741
5851
  if (input.isActive === false && wasActive && typeToUpdate.organizationId) {
5742
5852
  await releaseTypeSlugIfStillInactive(host, db, id, typeToUpdate.organizationId, typeToUpdate.slug);
5743
5853
  }
@@ -5754,7 +5864,7 @@ async function updateType(request, { host, params }) {
5754
5864
  return Response.json({ error: getErrorMessage(error, "Validation error") }, { status: schedErrorStatus(code) });
5755
5865
  }
5756
5866
  const message = isSchedulingServiceError(error) ? error.description || error.message : getErrorMessage(error, "Failed to update appointment type");
5757
- if (error instanceof import_scheduling45.SchedulingValidationError) return Response.json({ error: message }, { status: 400 });
5867
+ if (error instanceof import_scheduling46.SchedulingValidationError) return Response.json({ error: message }, { status: 400 });
5758
5868
  return Response.json({ error: message }, { status: 500 });
5759
5869
  }
5760
5870
  }
@@ -6006,7 +6116,7 @@ async function getStaffOptions(request, { host }) {
6006
6116
 
6007
6117
  // src/handlers/appointment-ical.ts
6008
6118
  var import_ical_generator = __toESM(require("ical-generator"));
6009
- var import_scheduling46 = require("@ordinatio/scheduling");
6119
+ var import_scheduling47 = require("@ordinatio/scheduling");
6010
6120
  async function getAppointmentIcal(request, { host }) {
6011
6121
  let token = null;
6012
6122
  try {
@@ -6040,7 +6150,7 @@ async function getAppointmentIcal(request, { host }) {
6040
6150
  timezone: appointment.timezone,
6041
6151
  summary,
6042
6152
  description,
6043
- location: (0, import_scheduling46.resolveLocation)(appointment) ?? void 0,
6153
+ location: (0, import_scheduling47.resolveLocation)(appointment) ?? void 0,
6044
6154
  url: manageUrl,
6045
6155
  organizer: staffName && staffEmail ? { name: staffName, email: staffEmail } : void 0
6046
6156
  });
@@ -6052,17 +6162,17 @@ async function getAppointmentIcal(request, { host }) {
6052
6162
  }
6053
6163
  });
6054
6164
  } catch (error) {
6055
- const diagnostic = (0, import_scheduling46.schedError)("SCHED_600", { error, token: token ?? "unknown" });
6165
+ const diagnostic = (0, import_scheduling47.schedError)("SCHED_600", { error, token: token ?? "unknown" });
6056
6166
  console.error("[GET /ical]", diagnostic.ref, error instanceof Error ? error.message : error);
6057
6167
  return Response.json({ error: "Failed to generate calendar file", ref: diagnostic.ref }, { status: 500 });
6058
6168
  }
6059
6169
  }
6060
6170
 
6061
6171
  // src/handlers/admin-webhooks.ts
6062
- var import_scheduling48 = require("@ordinatio/scheduling");
6172
+ var import_scheduling49 = require("@ordinatio/scheduling");
6063
6173
 
6064
6174
  // src/webhooks/require-webhooks.ts
6065
- var import_scheduling47 = require("@ordinatio/scheduling");
6175
+ var import_scheduling48 = require("@ordinatio/scheduling");
6066
6176
  async function requireWebhooksAdmin(host, request, options) {
6067
6177
  const staff = await requireAdminStaff(host, request, options);
6068
6178
  if (staff instanceof Response) return staff;
@@ -6070,10 +6180,10 @@ async function requireWebhooksAdmin(host, request, options) {
6070
6180
  return { staff, settings: host.webhooks };
6071
6181
  }
6072
6182
  function webhookErrorResponse(error, fallback) {
6073
- if (error instanceof import_scheduling47.SchedulingValidationError) {
6183
+ if (error instanceof import_scheduling48.SchedulingValidationError) {
6074
6184
  return Response.json({ error: error.message, ref: getErrorRef(error) }, { status: 400 });
6075
6185
  }
6076
- if (error instanceof import_scheduling47.SchedulingNotFoundError) {
6186
+ if (error instanceof import_scheduling48.SchedulingNotFoundError) {
6077
6187
  return Response.json({ error: error.message, ref: getErrorRef(error) }, { status: 404 });
6078
6188
  }
6079
6189
  return Response.json({ error: getErrorMessage(error, fallback) }, { status: 500 });
@@ -6085,7 +6195,7 @@ async function listWebhooks(request, { host }) {
6085
6195
  const guard = await requireWebhooksAdmin(host, request, { action: "admin-webhooks-list", tier: "GENERAL" });
6086
6196
  if (guard instanceof Response) return guard;
6087
6197
  const { db, organizationId } = guard.staff;
6088
- return Response.json({ endpoints: await (0, import_scheduling48.listWebhookEndpoints)(db, organizationId), eventTypes: import_scheduling48.WEBHOOK_EVENT_TYPES });
6198
+ return Response.json({ endpoints: await (0, import_scheduling49.listWebhookEndpoints)(db, organizationId), eventTypes: import_scheduling49.WEBHOOK_EVENT_TYPES });
6089
6199
  } catch (error) {
6090
6200
  return webhookErrorResponse(error, "Failed to list webhooks");
6091
6201
  }
@@ -6098,7 +6208,7 @@ async function createWebhook(request, { host }) {
6098
6208
  const validation = await parseBody(request, CreateWebhookEndpointSchema);
6099
6209
  if (!validation.success) return validation.response;
6100
6210
  const input = validation.data;
6101
- const { endpoint, secret } = await (0, import_scheduling48.createWebhookEndpoint)(
6211
+ const { endpoint, secret } = await (0, import_scheduling49.createWebhookEndpoint)(
6102
6212
  db,
6103
6213
  { organizationId, url: input.url, eventTypes: input.eventTypes, description: input.description },
6104
6214
  { allowInsecureTargets: guard.settings.allowInsecureTargets }
@@ -6115,14 +6225,14 @@ async function createWebhook(request, { host }) {
6115
6225
  }
6116
6226
 
6117
6227
  // src/handlers/admin-webhook-detail.ts
6118
- var import_scheduling49 = require("@ordinatio/scheduling");
6228
+ var import_scheduling50 = require("@ordinatio/scheduling");
6119
6229
  var STATUSES = /* @__PURE__ */ new Set(["PENDING", "PROCESSING", "SUCCEEDED", "DEAD_LETTER"]);
6120
6230
  async function deleteWebhook(request, { host, params }) {
6121
6231
  try {
6122
6232
  const guard = await requireWebhooksAdmin(host, request, { action: "admin-webhooks-delete", tier: "DELETE" });
6123
6233
  if (guard instanceof Response) return guard;
6124
6234
  const { db, organizationId } = guard.staff;
6125
- await (0, import_scheduling49.deleteWebhookEndpoint)(db, organizationId, params.id);
6235
+ await (0, import_scheduling50.deleteWebhookEndpoint)(db, organizationId, params.id);
6126
6236
  await host.activity.log(db, {
6127
6237
  action: "scheduling.webhook_deleted",
6128
6238
  description: "removed a webhook endpoint",
@@ -6138,7 +6248,7 @@ async function testWebhook(request, { host, params }) {
6138
6248
  const guard = await requireWebhooksAdmin(host, request, { action: "admin-webhooks-test", tier: "CREATE" });
6139
6249
  if (guard instanceof Response) return guard;
6140
6250
  const { db, organizationId } = guard.staff;
6141
- const result = await (0, import_scheduling49.sendTestWebhook)(
6251
+ const result = await (0, import_scheduling50.sendTestWebhook)(
6142
6252
  db,
6143
6253
  { organizationId, endpointId: params.id },
6144
6254
  { transport: guard.settings.transport, allowInsecureTargets: guard.settings.allowInsecureTargets }
@@ -6154,13 +6264,13 @@ async function listWebhookEndpointDeliveries(request, { host, params }) {
6154
6264
  if (guard instanceof Response) return guard;
6155
6265
  const { db, organizationId } = guard.staff;
6156
6266
  const owned = await db.webhookEndpoint.count({ where: { id: params.id, organizationId } });
6157
- if (owned === 0) throw new import_scheduling49.SchedulingNotFoundError("Webhook endpoint not found", "SCHED_1003", { endpointId: params.id });
6267
+ if (owned === 0) throw new import_scheduling50.SchedulingNotFoundError("Webhook endpoint not found", "SCHED_1003", { endpointId: params.id });
6158
6268
  const status = new URL(request.url).searchParams.get("status");
6159
6269
  if (status && !STATUSES.has(status)) {
6160
6270
  return Response.json({ error: `status must be one of ${[...STATUSES].join(", ")}` }, { status: 400 });
6161
6271
  }
6162
6272
  const { limit, offset } = parsePagination(request);
6163
- const { deliveries, total } = await (0, import_scheduling49.listWebhookDeliveries)(db, {
6273
+ const { deliveries, total } = await (0, import_scheduling50.listWebhookDeliveries)(db, {
6164
6274
  organizationId,
6165
6275
  endpointId: params.id,
6166
6276
  status: status ?? void 0,
@@ -6174,13 +6284,13 @@ async function listWebhookEndpointDeliveries(request, { host, params }) {
6174
6284
  }
6175
6285
 
6176
6286
  // src/handlers/admin-webhook-delivery-retry.ts
6177
- var import_scheduling50 = require("@ordinatio/scheduling");
6287
+ var import_scheduling51 = require("@ordinatio/scheduling");
6178
6288
  async function retryWebhook(request, { host, params }) {
6179
6289
  try {
6180
6290
  const guard = await requireWebhooksAdmin(host, request, { action: "admin-webhooks-retry", tier: "UPDATE" });
6181
6291
  if (guard instanceof Response) return guard;
6182
6292
  const { db, organizationId } = guard.staff;
6183
- await (0, import_scheduling50.retryWebhookDelivery)(db, organizationId, params.id);
6293
+ await (0, import_scheduling51.retryWebhookDelivery)(db, organizationId, params.id);
6184
6294
  return Response.json({ success: true });
6185
6295
  } catch (error) {
6186
6296
  return webhookErrorResponse(error, "Failed to retry the delivery");
@@ -6188,7 +6298,7 @@ async function retryWebhook(request, { host, params }) {
6188
6298
  }
6189
6299
 
6190
6300
  // src/handlers/internal-webhooks-deliver.ts
6191
- var import_scheduling51 = require("@ordinatio/scheduling");
6301
+ var import_scheduling52 = require("@ordinatio/scheduling");
6192
6302
  async function deliverWebhooks(request, { host }) {
6193
6303
  if (!await host.internalAccess.isAuthorized(request)) {
6194
6304
  return Response.json({ error: "Unauthorized" }, { status: 401 });
@@ -6197,7 +6307,7 @@ async function deliverWebhooks(request, { host }) {
6197
6307
  const limited = await host.rateLimit(`${request.headers.get("x-forwarded-for") ?? "worker"}:webhooks-deliver`, "INTERNAL");
6198
6308
  if (limited) return limited;
6199
6309
  try {
6200
- const summary = await (0, import_scheduling51.deliverDueWebhooks)(await host.publicDb(), {
6310
+ const summary = await (0, import_scheduling52.deliverDueWebhooks)(await host.publicDb(), {
6201
6311
  transport: host.webhooks.transport,
6202
6312
  allowInsecureTargets: host.webhooks.allowInsecureTargets
6203
6313
  });
@@ -6209,11 +6319,11 @@ async function deliverWebhooks(request, { host }) {
6209
6319
  }
6210
6320
 
6211
6321
  // src/handlers/waitlist-join.ts
6212
- var import_scheduling53 = require("@ordinatio/scheduling");
6213
- var import_zod16 = require("zod");
6322
+ var import_scheduling54 = require("@ordinatio/scheduling");
6323
+ var import_zod18 = require("zod");
6214
6324
 
6215
6325
  // src/waitlist/waitlist-http.ts
6216
- var import_scheduling52 = require("@ordinatio/scheduling");
6326
+ var import_scheduling53 = require("@ordinatio/scheduling");
6217
6327
  var NOT_ENABLED2 = { error: "The waitlist is not enabled on this server" };
6218
6328
  var STATUS_BY_CODE = {
6219
6329
  SCHED_1100: 404,
@@ -6228,8 +6338,8 @@ async function resolveWaitlistDb(host, orgSlug) {
6228
6338
  return host.organizations.resolve({ orgSlug, logPrefix: "[waitlist]" });
6229
6339
  }
6230
6340
  function waitlistErrorResponse(cors, error, fallback) {
6231
- if (error instanceof import_scheduling52.SchedulingValidationError || error instanceof import_scheduling52.SchedulingNotFoundError) {
6232
- const status = STATUS_BY_CODE[error.code] ?? (error instanceof import_scheduling52.SchedulingNotFoundError ? 404 : 400);
6341
+ if (error instanceof import_scheduling53.SchedulingValidationError || error instanceof import_scheduling53.SchedulingNotFoundError) {
6342
+ const status = STATUS_BY_CODE[error.code] ?? (error instanceof import_scheduling53.SchedulingNotFoundError ? 404 : 400);
6233
6343
  return corsJson(cors, { error: error.message, code: error.code, ref: getErrorRef(error) }, { status });
6234
6344
  }
6235
6345
  console.error("[waitlist]", error);
@@ -6243,15 +6353,15 @@ async function requireWaitlistAdmin(host, request, options) {
6243
6353
  }
6244
6354
 
6245
6355
  // src/handlers/waitlist-join.ts
6246
- var JoinWaitlistSchema = import_zod16.z.object({
6247
- orgSlug: import_zod16.z.string().min(1).max(100).optional(),
6248
- typeId: import_zod16.z.string().min(1),
6249
- calendarId: import_zod16.z.string().min(1).optional(),
6250
- day: import_zod16.z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "Day must be YYYY-MM-DD"),
6251
- slotStart: import_zod16.z.string().datetime({ message: "Invalid date/time format" }).optional(),
6252
- clientName: import_zod16.z.string().trim().min(1, "Name is required").max(200),
6253
- clientEmail: import_zod16.z.string().email("Invalid email").max(254),
6254
- clientPhone: import_zod16.z.string().max(30).optional()
6356
+ var JoinWaitlistSchema = import_zod18.z.object({
6357
+ orgSlug: import_zod18.z.string().min(1).max(100).optional(),
6358
+ typeId: import_zod18.z.string().min(1),
6359
+ calendarId: import_zod18.z.string().min(1).optional(),
6360
+ day: import_zod18.z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "Day must be YYYY-MM-DD"),
6361
+ slotStart: import_zod18.z.string().datetime({ message: "Invalid date/time format" }).optional(),
6362
+ clientName: import_zod18.z.string().trim().min(1, "Name is required").max(200),
6363
+ clientEmail: import_zod18.z.string().email("Invalid email").max(254),
6364
+ clientPhone: import_zod18.z.string().max(30).optional()
6255
6365
  });
6256
6366
  async function joinWaitlistRoute(request, { host }) {
6257
6367
  const cors = host.cors(request);
@@ -6273,7 +6383,7 @@ async function joinWaitlistRoute(request, { host }) {
6273
6383
  organizationId = type?.organizationId ?? null;
6274
6384
  }
6275
6385
  if (!organizationId) return corsJson(cors, { error: "Appointment type not found" }, { status: 404 });
6276
- const { entry, token } = await (0, import_scheduling53.joinWaitlist)(context.db, {
6386
+ const { entry, token } = await (0, import_scheduling54.joinWaitlist)(context.db, {
6277
6387
  organizationId,
6278
6388
  typeId: body.typeId,
6279
6389
  calendarId: body.calendarId,
@@ -6299,7 +6409,7 @@ async function leaveWaitlistRoute(request, { host }) {
6299
6409
  if (!token) return corsJson(cors, { error: "token is required" }, { status: 400 });
6300
6410
  const context = await resolveWaitlistDb(host, url.searchParams.get("orgSlug"));
6301
6411
  if (!context) return corsJson(cors, { error: "No waitlist entry for this link", code: "SCHED_1106" }, { status: 404 });
6302
- const freed = await (0, import_scheduling53.leaveWaitlist)(context.db, token);
6412
+ const freed = await (0, import_scheduling54.leaveWaitlist)(context.db, token);
6303
6413
  if (freed) await offerAndAnnounce(host, host.waitlist, context.db, freed);
6304
6414
  return corsJson(cors, { success: true });
6305
6415
  } catch (error) {
@@ -6308,40 +6418,40 @@ async function leaveWaitlistRoute(request, { host }) {
6308
6418
  }
6309
6419
 
6310
6420
  // src/handlers/waitlist-offer.ts
6311
- var import_scheduling58 = require("@ordinatio/scheduling");
6312
- var import_zod18 = require("zod");
6421
+ var import_scheduling59 = require("@ordinatio/scheduling");
6422
+ var import_zod20 = require("zod");
6313
6423
 
6314
6424
  // src/handlers/appointments-book.ts
6315
- var import_scheduling57 = require("@ordinatio/scheduling");
6425
+ var import_scheduling58 = require("@ordinatio/scheduling");
6316
6426
 
6317
6427
  // src/booking/booking-schema.ts
6318
- var import_zod17 = require("zod");
6319
- var BookingSchema = import_zod17.z.object({
6320
- calendarId: import_zod17.z.string().min(1).optional(),
6321
- preferredCalendarId: import_zod17.z.string().min(1).optional(),
6322
- typeId: import_zod17.z.string().min(1),
6323
- startTime: import_zod17.z.string().datetime({ message: "Invalid date/time format" }),
6324
- timezone: import_zod17.z.string().max(50).optional(),
6325
- clientName: import_zod17.z.string().trim().min(1, "Name is required").max(200),
6326
- clientEmail: import_zod17.z.string().email("Invalid email").max(254),
6327
- clientPhone: import_zod17.z.string().max(30).optional(),
6428
+ var import_zod19 = require("zod");
6429
+ var BookingSchema = import_zod19.z.object({
6430
+ calendarId: import_zod19.z.string().min(1).optional(),
6431
+ preferredCalendarId: import_zod19.z.string().min(1).optional(),
6432
+ typeId: import_zod19.z.string().min(1),
6433
+ startTime: import_zod19.z.string().datetime({ message: "Invalid date/time format" }),
6434
+ timezone: import_zod19.z.string().max(50).optional(),
6435
+ clientName: import_zod19.z.string().trim().min(1, "Name is required").max(200),
6436
+ clientEmail: import_zod19.z.string().email("Invalid email").max(254),
6437
+ clientPhone: import_zod19.z.string().max(30).optional(),
6328
6438
  // Untrusted: the host's client resolver decides whether to honor it.
6329
- clientId: import_zod17.z.string().optional(),
6330
- notes: import_zod17.z.string().max(1e3).optional(),
6439
+ clientId: import_zod19.z.string().optional(),
6440
+ notes: import_zod19.z.string().max(1e3).optional(),
6331
6441
  // Only the primitive types a form field produces; z.unknown() would accept anything.
6332
- intakeResponses: import_zod17.z.record(
6333
- import_zod17.z.string(),
6334
- import_zod17.z.union([import_zod17.z.string().max(1e3), import_zod17.z.number(), import_zod17.z.boolean(), import_zod17.z.null()])
6442
+ intakeResponses: import_zod19.z.record(
6443
+ import_zod19.z.string(),
6444
+ import_zod19.z.union([import_zod19.z.string().max(1e3), import_zod19.z.number(), import_zod19.z.boolean(), import_zod19.z.null()])
6335
6445
  ).optional(),
6336
- paymentId: import_zod17.z.string().optional(),
6337
- couponCode: import_zod17.z.string().min(1).max(50).transform((value) => value.trim().toUpperCase()).optional(),
6338
- packagePurchaseId: import_zod17.z.string().optional(),
6446
+ paymentId: import_zod19.z.string().optional(),
6447
+ couponCode: import_zod19.z.string().min(1).max(50).transform((value) => value.trim().toUpperCase()).optional(),
6448
+ packagePurchaseId: import_zod19.z.string().optional(),
6339
6449
  // Names the organization, so the calendar and type lookups can run against its own database.
6340
- orgSlug: import_zod17.z.string().min(1).max(100).optional()
6450
+ orgSlug: import_zod19.z.string().min(1).max(100).optional()
6341
6451
  });
6342
6452
 
6343
6453
  // src/booking/finalize-booking.ts
6344
- var import_scheduling54 = require("@ordinatio/scheduling");
6454
+ var import_scheduling55 = require("@ordinatio/scheduling");
6345
6455
  async function finalizeBooking(host, cors, db, organizationId, body, appointment, appointmentType, discountCents, appliedCouponCode, noShowApprovalOverride, clientId) {
6346
6456
  const logActivity = (action, description, metadata) => host.activity.log(db, { action, description, metadata });
6347
6457
  if (noShowApprovalOverride && appointment.status === "CONFIRMED") {
@@ -6384,7 +6494,7 @@ async function finalizeBooking(host, cors, db, organizationId, body, appointment
6384
6494
  AND ("expiresAt" IS NULL OR "expiresAt" > NOW())
6385
6495
  `;
6386
6496
  if (counted === 0) {
6387
- await (0, import_scheduling54.cancelAppointment)(db, {
6497
+ await (0, import_scheduling55.cancelAppointment)(db, {
6388
6498
  appointmentId: appointment.id,
6389
6499
  cancelledBy: "system",
6390
6500
  reason: "Coupon exhausted by concurrent booking during payment"
@@ -6403,7 +6513,7 @@ async function finalizeBooking(host, cors, db, organizationId, body, appointment
6403
6513
  }
6404
6514
  let meetingUrl = null;
6405
6515
  if (appointmentType.locationType === "VIRTUAL") {
6406
- meetingUrl = (0, import_scheduling54.buildJitsiUrl)(appointment.id);
6516
+ meetingUrl = (0, import_scheduling55.buildJitsiUrl)(appointment.id);
6407
6517
  try {
6408
6518
  await db.appointment.update({ where: { id: appointment.id }, data: { meetingUrl } });
6409
6519
  } catch (meetingError) {
@@ -6428,7 +6538,7 @@ async function finalizeBooking(host, cors, db, organizationId, body, appointment
6428
6538
  const baseUrl = host.appUrl();
6429
6539
  if (!baseUrl) throw new Error("The host must supply appUrl() to book appointments");
6430
6540
  try {
6431
- await (0, import_scheduling54.scheduleNotifications)(db, appointment.id, baseUrl, { brand: Boolean(host.brand) });
6541
+ await (0, import_scheduling55.scheduleNotifications)(db, appointment.id, baseUrl, { brand: Boolean(host.brand) });
6432
6542
  } catch (error) {
6433
6543
  await logActivity(
6434
6544
  "scheduling.notification_schedule_failed",
@@ -6437,7 +6547,7 @@ async function finalizeBooking(host, cors, db, organizationId, body, appointment
6437
6547
  );
6438
6548
  }
6439
6549
  try {
6440
- await (0, import_scheduling54.queueStaffNotification)(db, appointment.id, "CONFIRMATION", baseUrl, { brand: Boolean(host.brand) });
6550
+ await (0, import_scheduling55.queueStaffNotification)(db, appointment.id, "CONFIRMATION", baseUrl, { brand: Boolean(host.brand) });
6441
6551
  } catch (error) {
6442
6552
  await logActivity(
6443
6553
  "scheduling.staff_notification_failed",
@@ -6491,7 +6601,7 @@ async function finalizeBooking(host, cors, db, organizationId, body, appointment
6491
6601
  }
6492
6602
 
6493
6603
  // src/booking/refund-blocked-booking.ts
6494
- var import_scheduling55 = require("@ordinatio/scheduling");
6604
+ var import_scheduling56 = require("@ordinatio/scheduling");
6495
6605
  var REFUND_ON_CODES = ["SCHED_301", "SCHED_307", "SCHED_802", "SCHED_800", "SCHED_801", "SCHED_201", "SCHED_100", "SCHED_200", "SCHED_102"];
6496
6606
  function isBlockedBookingCode(code) {
6497
6607
  return code !== void 0 && REFUND_ON_CODES.includes(code);
@@ -6506,12 +6616,12 @@ async function respondToBlockedPaidBooking(db, payments, cors, paymentId, blocke
6506
6616
  try {
6507
6617
  existingBooking = await db.appointment.findFirst({ where: { paymentId }, select: { id: true } });
6508
6618
  } catch (lookupError) {
6509
- const err = (0, import_scheduling55.schedError)("SCHED_409", { paymentId, blockerCode, error: lookupError });
6619
+ const err = (0, import_scheduling56.schedError)("SCHED_409", { paymentId, blockerCode, error: lookupError });
6510
6620
  console.error("[booking] Could not check for an existing booking before refunding:", err.ref, lookupError);
6511
6621
  return corsJson(cors, { error: "We could not confirm your booking just now. Please try again.", ref: err.ref }, { status: 503 });
6512
6622
  }
6513
6623
  if (existingBooking) {
6514
- const err = (0, import_scheduling55.schedError)("SCHED_404", { paymentId, existingAppointmentId: existingBooking.id });
6624
+ const err = (0, import_scheduling56.schedError)("SCHED_404", { paymentId, existingAppointmentId: existingBooking.id });
6515
6625
  return corsJson(
6516
6626
  cors,
6517
6627
  { error: "This payment has already been used for a booking", ref: err.ref, code: "PAYMENT_ALREADY_USED" },
@@ -6642,7 +6752,7 @@ async function resolveBookingContext(host, cors, body) {
6642
6752
  }
6643
6753
 
6644
6754
  // src/booking/verify-booking-payment.ts
6645
- var import_scheduling56 = require("@ordinatio/scheduling");
6755
+ var import_scheduling57 = require("@ordinatio/scheduling");
6646
6756
  async function verifyBookingPayment(db, payments, cors, organizationId, appointmentType, body) {
6647
6757
  const refuse = (status, payload) => ({
6648
6758
  ok: false,
@@ -6659,7 +6769,7 @@ async function verifyBookingPayment(db, payments, cors, organizationId, appointm
6659
6769
  select: { id: true }
6660
6770
  });
6661
6771
  if (existingBooking) {
6662
- const err = (0, import_scheduling56.schedError)("SCHED_404", { paymentId: body.paymentId, existingAppointmentId: existingBooking.id });
6772
+ const err = (0, import_scheduling57.schedError)("SCHED_404", { paymentId: body.paymentId, existingAppointmentId: existingBooking.id });
6663
6773
  return refuse(409, {
6664
6774
  error: "This payment has already been used for a booking",
6665
6775
  ref: err.ref,
@@ -6669,7 +6779,7 @@ async function verifyBookingPayment(db, payments, cors, organizationId, appointm
6669
6779
  const metaTypeId = payment.metadata?.typeId;
6670
6780
  const metaClientEmail = payment.metadata?.clientEmail;
6671
6781
  if (metaTypeId !== body.typeId || metaClientEmail && metaClientEmail.toLowerCase() !== body.clientEmail.toLowerCase()) {
6672
- const err = (0, import_scheduling56.schedError)("SCHED_405", {
6782
+ const err = (0, import_scheduling57.schedError)("SCHED_405", {
6673
6783
  paymentId: body.paymentId,
6674
6784
  metaTypeId,
6675
6785
  bodyTypeId: body.typeId,
@@ -6699,7 +6809,7 @@ async function verifyBookingPayment(db, payments, cors, organizationId, appointm
6699
6809
  }
6700
6810
  }
6701
6811
  if (payment.amount === void 0) {
6702
- const err = (0, import_scheduling56.schedError)("SCHED_405", { paymentId: body.paymentId, currency: payment.currency });
6812
+ const err = (0, import_scheduling57.schedError)("SCHED_405", { paymentId: body.paymentId, currency: payment.currency });
6703
6813
  return refuse(400, { error: "Payment currency is not supported", ref: err.ref });
6704
6814
  }
6705
6815
  if (Math.round(payment.amount * 100) !== expectedCents) {
@@ -6740,7 +6850,7 @@ async function bookAppointmentRoute(request, { host }) {
6740
6850
  } catch (linkError) {
6741
6851
  console.error("[booking] client link lookup failed \u2014 saving the appointment unlinked:", linkError instanceof Error ? linkError.message : linkError);
6742
6852
  }
6743
- const appointment = await (0, import_scheduling57.bookAppointment)(db, {
6853
+ const appointment = await (0, import_scheduling58.bookAppointment)(db, {
6744
6854
  calendarId: body.calendarId,
6745
6855
  preferredCalendarId: body.preferredCalendarId,
6746
6856
  typeId: body.typeId,
@@ -6814,7 +6924,7 @@ async function getWaitlistOfferRoute(request, { host }) {
6814
6924
  if (!token) return corsJson(cors, { error: "token is required" }, { status: 400 });
6815
6925
  const context = await resolveWaitlistDb(host, url.searchParams.get("orgSlug"));
6816
6926
  if (!context) return corsJson(cors, { error: "No open offer for this link", code: "SCHED_1106" }, { status: 404 });
6817
- const offer = await (0, import_scheduling58.getWaitlistOffer)(context.db, token);
6927
+ const offer = await (0, import_scheduling59.getWaitlistOffer)(context.db, token);
6818
6928
  return corsJson(cors, {
6819
6929
  typeName: offer.typeName,
6820
6930
  calendarName: offer.calendarName,
@@ -6827,7 +6937,7 @@ async function getWaitlistOfferRoute(request, { host }) {
6827
6937
  return waitlistErrorResponse(cors, error, "Failed to read the offer");
6828
6938
  }
6829
6939
  }
6830
- var AcceptSchema = import_zod18.z.object({ token: import_zod18.z.string().min(1).max(200), orgSlug: import_zod18.z.string().min(1).max(100).optional() });
6940
+ var AcceptSchema = import_zod20.z.object({ token: import_zod20.z.string().min(1).max(200), orgSlug: import_zod20.z.string().min(1).max(100).optional() });
6831
6941
  async function acceptWaitlistOfferRoute(request, context) {
6832
6942
  const { host } = context;
6833
6943
  const cors = host.cors(request);
@@ -6843,7 +6953,7 @@ async function acceptWaitlistOfferRoute(request, context) {
6843
6953
  if (!parsed.success) return corsJson(cors, { error: "token is required" }, { status: 400 });
6844
6954
  db = await resolveWaitlistDb(host, parsed.data.orgSlug);
6845
6955
  if (!db) return corsJson(cors, { error: "No open offer for this link", code: "SCHED_1106" }, { status: 404 });
6846
- const offer = await (0, import_scheduling58.beginWaitlistAccept)(db.db, parsed.data.token);
6956
+ const offer = await (0, import_scheduling59.beginWaitlistAccept)(db.db, parsed.data.token);
6847
6957
  entryId = offer.entryId;
6848
6958
  const headers = new Headers(request.headers);
6849
6959
  headers.set("content-type", "application/json");
@@ -6868,20 +6978,20 @@ async function acceptWaitlistOfferRoute(request, context) {
6868
6978
  booked = true;
6869
6979
  const appointment = await response.clone().json().catch(() => null);
6870
6980
  try {
6871
- await (0, import_scheduling58.completeWaitlistAccept)(db.db, entryId, appointment?.id ?? "");
6981
+ await (0, import_scheduling59.completeWaitlistAccept)(db.db, entryId, appointment?.id ?? "");
6872
6982
  } catch (completeError) {
6873
6983
  console.error("[waitlist] the booking was saved but its waitlist entry could not be marked booked:", completeError);
6874
6984
  }
6875
6985
  return response;
6876
6986
  }
6877
- const saved = await (0, import_scheduling58.settleBookedAccept)(db.db, entryId);
6987
+ const saved = await (0, import_scheduling59.settleBookedAccept)(db.db, entryId);
6878
6988
  if (saved) return corsJson(cors, saved, { status: 201 });
6879
6989
  await endFailedAccept(host, settings, db.db, entryId, releaseFor(response.status));
6880
6990
  return response;
6881
6991
  } catch (error) {
6882
6992
  if (entryId && db && !booked) {
6883
6993
  try {
6884
- const saved = await (0, import_scheduling58.settleBookedAccept)(db.db, entryId);
6994
+ const saved = await (0, import_scheduling59.settleBookedAccept)(db.db, entryId);
6885
6995
  if (saved) return corsJson(cors, saved, { status: 201 });
6886
6996
  await endFailedAccept(host, settings, db.db, entryId, "KEEP_OFFER");
6887
6997
  } catch (releaseError) {
@@ -6897,12 +7007,12 @@ function releaseFor(status) {
6897
7007
  return "DROP";
6898
7008
  }
6899
7009
  async function endFailedAccept(host, settings, db, entryId, outcome) {
6900
- const freed = await (0, import_scheduling58.releaseWaitlistAccept)(db, entryId, outcome);
7010
+ const freed = await (0, import_scheduling59.releaseWaitlistAccept)(db, entryId, outcome);
6901
7011
  if (freed) await offerAndAnnounce(host, settings, db, freed);
6902
7012
  }
6903
7013
 
6904
7014
  // src/handlers/admin-waitlist.ts
6905
- var import_scheduling59 = require("@ordinatio/scheduling");
7015
+ var import_scheduling60 = require("@ordinatio/scheduling");
6906
7016
  var STATUSES2 = /* @__PURE__ */ new Set(["WAITING", "OFFERED", "ACCEPTING", "BOOKED", "EXPIRED"]);
6907
7017
  async function listWaitlistEntries(request, { host }) {
6908
7018
  try {
@@ -6913,7 +7023,7 @@ async function listWaitlistEntries(request, { host }) {
6913
7023
  return Response.json({ error: `status must be one of ${[...STATUSES2].join(", ")}` }, { status: 400 });
6914
7024
  }
6915
7025
  const { limit, offset } = parsePagination(request);
6916
- const { entries, total } = await (0, import_scheduling59.listWaitlist)(guard.staff.db, {
7026
+ const { entries, total } = await (0, import_scheduling60.listWaitlist)(guard.staff.db, {
6917
7027
  organizationId: guard.staff.organizationId,
6918
7028
  status: status ?? void 0,
6919
7029
  limit,
@@ -6929,7 +7039,7 @@ async function removeWaitlistEntryRoute(request, { host, params }) {
6929
7039
  const guard = await requireWaitlistAdmin(host, request, { action: "admin-waitlist-remove", tier: "DELETE" });
6930
7040
  if (guard instanceof Response) return guard;
6931
7041
  const { db, organizationId } = guard.staff;
6932
- const freed = await (0, import_scheduling59.removeWaitlistEntry)(db, organizationId, params.id);
7042
+ const freed = await (0, import_scheduling60.removeWaitlistEntry)(db, organizationId, params.id);
6933
7043
  await host.activity.log(db, {
6934
7044
  action: "scheduling.waitlist_entry_removed",
6935
7045
  description: "removed someone from the waitlist",
@@ -6943,7 +7053,7 @@ async function removeWaitlistEntryRoute(request, { host, params }) {
6943
7053
  }
6944
7054
 
6945
7055
  // src/handlers/internal-waitlist-sweep.ts
6946
- var import_scheduling60 = require("@ordinatio/scheduling");
7056
+ var import_scheduling61 = require("@ordinatio/scheduling");
6947
7057
  async function sweepWaitlist(request, { host }) {
6948
7058
  if (!await host.internalAccess.isAuthorized(request)) return Response.json({ error: "Unauthorized" }, { status: 401 });
6949
7059
  if (!host.waitlist) return Response.json(NOT_ENABLED2, { status: 501 });
@@ -6951,7 +7061,7 @@ async function sweepWaitlist(request, { host }) {
6951
7061
  if (limited) return limited;
6952
7062
  try {
6953
7063
  const db = await host.publicDb();
6954
- const { lapsed, released, booked } = await (0, import_scheduling60.expireWaitlistOffers)(db);
7064
+ const { lapsed, released, booked } = await (0, import_scheduling61.expireWaitlistOffers)(db);
6955
7065
  let reoffered = 0;
6956
7066
  for (const slot of lapsed) {
6957
7067
  if (await offerAndAnnounce(host, host.waitlist, db, slot)) reoffered++;
@@ -6964,15 +7074,15 @@ async function sweepWaitlist(request, { host }) {
6964
7074
  }
6965
7075
 
6966
7076
  // src/handlers/routing-forms-public.ts
6967
- var import_scheduling62 = require("@ordinatio/scheduling");
7077
+ var import_scheduling63 = require("@ordinatio/scheduling");
6968
7078
 
6969
7079
  // src/routing/routing-http.ts
6970
- var import_scheduling61 = require("@ordinatio/scheduling");
7080
+ var import_scheduling62 = require("@ordinatio/scheduling");
6971
7081
  var NOT_ENABLED3 = { error: "Routing forms are not enabled on this server" };
6972
7082
  var STATUS_BY_CODE2 = { SCHED_1201: 404, SCHED_1202: 409, SCHED_1204: 409 };
6973
7083
  function routingErrorResponse(error, fallback, cors) {
6974
7084
  const send = (payload, status) => cors ? corsJson(cors, payload, { status }) : Response.json(payload, { status });
6975
- if (error instanceof import_scheduling61.SchedulingValidationError || error instanceof import_scheduling61.SchedulingNotFoundError) {
7085
+ if (error instanceof import_scheduling62.SchedulingValidationError || error instanceof import_scheduling62.SchedulingNotFoundError) {
6976
7086
  const details = error.context.errors;
6977
7087
  const status = STATUS_BY_CODE2[error.code] ?? 400;
6978
7088
  return send({ error: error.message, code: error.code, ref: getErrorRef(error), ...details ? { details } : {} }, status);
@@ -7003,7 +7113,7 @@ async function getRoutingFormRoute(request, { host }) {
7003
7113
  if (!slug) return corsJson(cors, { error: "slug is required" }, { status: 400 });
7004
7114
  const context = await resolveOrganization(host, url.searchParams.get("orgSlug"));
7005
7115
  if (!context) return corsJson(cors, { error: "Routing form not found", code: "SCHED_1201" }, { status: 404 });
7006
- return corsJson(cors, await (0, import_scheduling62.getPublicRoutingForm)(context.db, { organizationId: context.organizationId, slug }));
7116
+ return corsJson(cors, await (0, import_scheduling63.getPublicRoutingForm)(context.db, { organizationId: context.organizationId, slug }));
7007
7117
  } catch (error) {
7008
7118
  return routingErrorResponse(error, "Failed to read the form", cors);
7009
7119
  }
@@ -7021,7 +7131,7 @@ async function routeClientRoute(request, { host }) {
7021
7131
  }
7022
7132
  const context = await resolveOrganization(host, parsed.data.orgSlug);
7023
7133
  if (!context) return corsJson(cors, { error: "Routing form not found", code: "SCHED_1201" }, { status: 404 });
7024
- const outcome = await (0, import_scheduling62.routeClient)(context.db, { organizationId: context.organizationId, slug: parsed.data.slug, answers: parsed.data.answers });
7134
+ const outcome = await (0, import_scheduling63.routeClient)(context.db, { organizationId: context.organizationId, slug: parsed.data.slug, answers: parsed.data.answers });
7025
7135
  return corsJson(cors, outcome);
7026
7136
  } catch (error) {
7027
7137
  return routingErrorResponse(error, "Failed to route the answers", cors);
@@ -7029,12 +7139,12 @@ async function routeClientRoute(request, { host }) {
7029
7139
  }
7030
7140
 
7031
7141
  // src/handlers/admin-routing-forms.ts
7032
- var import_scheduling63 = require("@ordinatio/scheduling");
7142
+ var import_scheduling64 = require("@ordinatio/scheduling");
7033
7143
  async function listRoutingFormsRoute(request, { host }) {
7034
7144
  try {
7035
7145
  const staff = await requireRoutingAdmin(host, request, { action: "admin-routing-forms-list", tier: "GENERAL" });
7036
7146
  if (staff instanceof Response) return staff;
7037
- return Response.json({ forms: await (0, import_scheduling63.listRoutingForms)(staff.db, staff.organizationId) });
7147
+ return Response.json({ forms: await (0, import_scheduling64.listRoutingForms)(staff.db, staff.organizationId) });
7038
7148
  } catch (error) {
7039
7149
  return routingErrorResponse(error, "Failed to list the forms");
7040
7150
  }
@@ -7045,7 +7155,7 @@ async function createRoutingFormRoute(request, { host }) {
7045
7155
  if (staff instanceof Response) return staff;
7046
7156
  const validation = await parseBody(request, CreateRoutingFormSchema);
7047
7157
  if (!validation.success) return validation.response;
7048
- const form = await (0, import_scheduling63.createRoutingForm)(staff.db, staff.organizationId, validation.data);
7158
+ const form = await (0, import_scheduling64.createRoutingForm)(staff.db, staff.organizationId, validation.data);
7049
7159
  await host.activity.log(staff.db, {
7050
7160
  action: "scheduling.routing_form_created",
7051
7161
  description: `created routing form "${form.name}"`,
@@ -7058,7 +7168,7 @@ async function createRoutingFormRoute(request, { host }) {
7058
7168
  }
7059
7169
 
7060
7170
  // src/handlers/brand-public.ts
7061
- var import_scheduling64 = require("@ordinatio/scheduling");
7171
+ var import_scheduling65 = require("@ordinatio/scheduling");
7062
7172
  async function getBrandRoute(request, { host }) {
7063
7173
  const cors = host.cors(request);
7064
7174
  if (!host.brand) return corsJson(cors, NOT_ENABLED, { status: 501 });
@@ -7067,7 +7177,7 @@ async function getBrandRoute(request, { host }) {
7067
7177
  if (limited) return limited;
7068
7178
  const orgSlug = new URL(request.url).searchParams.get("orgSlug");
7069
7179
  const context = orgSlug ? await host.organizations.resolve({ orgSlug, logPrefix: "[brand]" }) : { db: await host.publicDb(), organizationId: null };
7070
- const brand = context ? await (0, import_scheduling64.getPublicBrand)(context.db, context.organizationId) : null;
7180
+ const brand = context ? await (0, import_scheduling65.getPublicBrand)(context.db, context.organizationId) : null;
7071
7181
  if (!brand) return corsJson(cors, { error: "No brand set" }, { status: 404 });
7072
7182
  return corsJson(cors, { brand }, { headers: WIDGET_CACHE_HEADERS });
7073
7183
  } catch (error) {
@@ -7076,12 +7186,12 @@ async function getBrandRoute(request, { host }) {
7076
7186
  }
7077
7187
 
7078
7188
  // src/handlers/admin-brand.ts
7079
- var import_scheduling65 = require("@ordinatio/scheduling");
7189
+ var import_scheduling66 = require("@ordinatio/scheduling");
7080
7190
  async function getBrandAdminRoute(request, { host }) {
7081
7191
  try {
7082
7192
  const staff = await requireBrandAdmin(host, request, { action: "admin-brand-get", tier: "GENERAL" });
7083
7193
  if (staff instanceof Response) return staff;
7084
- return Response.json({ brand: await (0, import_scheduling65.getBrand)(staff.db, staff.organizationId) });
7194
+ return Response.json({ brand: await (0, import_scheduling66.getBrand)(staff.db, staff.organizationId) });
7085
7195
  } catch (error) {
7086
7196
  return brandErrorResponse(error, "Failed to read the brand");
7087
7197
  }
@@ -7093,7 +7203,7 @@ async function saveBrandRoute(request, { host }) {
7093
7203
  const validation = await parseBody(request, BrandSchema);
7094
7204
  if (!validation.success) return validation.response;
7095
7205
  const verifier = host.brand?.isSendingDomainVerified;
7096
- const brand = await (0, import_scheduling65.saveBrand)(staff.db, staff.organizationId, validation.data, {
7206
+ const brand = await (0, import_scheduling66.saveBrand)(staff.db, staff.organizationId, validation.data, {
7097
7207
  isSendingDomainVerified: verifier ? async (domain) => Boolean(await verifier.call(host.brand, domain, staff.organizationId)) : void 0
7098
7208
  });
7099
7209
  await host.activity.log(staff.db, {
@@ -7110,7 +7220,7 @@ async function deleteBrandRoute(request, { host }) {
7110
7220
  try {
7111
7221
  const staff = await requireBrandAdmin(host, request, { action: "admin-brand-delete", tier: "DELETE" });
7112
7222
  if (staff instanceof Response) return staff;
7113
- const removed = await (0, import_scheduling65.deleteBrand)(staff.db, staff.organizationId);
7223
+ const removed = await (0, import_scheduling66.deleteBrand)(staff.db, staff.organizationId);
7114
7224
  if (removed) await host.activity.log(staff.db, { action: "scheduling.brand_removed", description: "removed the brand", metadata: {} });
7115
7225
  return Response.json({ removed });
7116
7226
  } catch (error) {
@@ -7118,15 +7228,192 @@ async function deleteBrandRoute(request, { host }) {
7118
7228
  }
7119
7229
  }
7120
7230
 
7121
- // src/handlers/admin-privacy.ts
7231
+ // src/handlers/admin-api-keys.ts
7122
7232
  var import_scheduling67 = require("@ordinatio/scheduling");
7233
+ var NOT_ENABLED4 = { error: "API keys are not enabled on this server" };
7234
+ function failure3(error, fallback) {
7235
+ if (error instanceof import_scheduling67.SchedulingValidationError) {
7236
+ const details = error.context.errors;
7237
+ return Response.json({ error: error.message, code: error.code, ref: getErrorRef(error), ...details ? { details } : {} }, { status: 400 });
7238
+ }
7239
+ console.error("[api-keys]", error);
7240
+ return Response.json({ error: fallback }, { status: 500 });
7241
+ }
7242
+ async function requireKeyAdmin(host, request, options) {
7243
+ const staff = await requireAdminStaff(host, request, options);
7244
+ if (staff instanceof Response) return staff;
7245
+ if (!host.apiKeys) return Response.json(NOT_ENABLED4, { status: 501 });
7246
+ if (staff.role.startsWith(API_KEY_ROLE_PREFIX)) return Response.json({ error: "API keys are managed by a signed-in person, not with an API key" }, { status: 403 });
7247
+ return staff;
7248
+ }
7249
+ async function listApiKeysRoute(request, { host }) {
7250
+ try {
7251
+ const staff = await requireKeyAdmin(host, request, { action: "admin-api-keys-list", tier: "GENERAL" });
7252
+ if (staff instanceof Response) return staff;
7253
+ return Response.json({ keys: await (0, import_scheduling67.listApiKeys)(staff.db, staff.organizationId) });
7254
+ } catch (error) {
7255
+ return failure3(error, "Failed to list the API keys");
7256
+ }
7257
+ }
7258
+ async function createApiKeyRoute(request, { host }) {
7259
+ try {
7260
+ const staff = await requireKeyAdmin(host, request, { action: "admin-api-keys-create", tier: "SETTINGS" });
7261
+ if (staff instanceof Response) return staff;
7262
+ const validation = await parseBody(request, ApiKeySchema);
7263
+ if (!validation.success) return validation.response;
7264
+ const { key, view } = await (0, import_scheduling67.createApiKey)(staff.db, staff.organizationId, validation.data, staff.userId);
7265
+ await host.activity.log(staff.db, { action: "scheduling.api_key_created", description: `made the API key "${view.name}"`, metadata: { keyId: view.id, access: view.access } }).catch((error) => {
7266
+ console.error("[api-keys] could not record the new key in the activity log", error);
7267
+ });
7268
+ return Response.json({ key, apiKey: view }, { status: 201, headers: { "Cache-Control": "no-store" } });
7269
+ } catch (error) {
7270
+ return failure3(error, "Failed to make the API key");
7271
+ }
7272
+ }
7273
+ async function revokeApiKeyRoute(request, { host, params }) {
7274
+ try {
7275
+ const staff = await requireKeyAdmin(host, request, { action: "admin-api-keys-revoke", tier: "DELETE" });
7276
+ if (staff instanceof Response) return staff;
7277
+ const revoked = await (0, import_scheduling67.revokeApiKey)(staff.db, staff.organizationId, params.id);
7278
+ if (revoked) await host.activity.log(staff.db, { action: "scheduling.api_key_revoked", description: "revoked an API key", metadata: { keyId: params.id } });
7279
+ return Response.json({ revoked });
7280
+ } catch (error) {
7281
+ return failure3(error, "Failed to revoke the API key");
7282
+ }
7283
+ }
7284
+
7285
+ // src/handlers/admin-text-settings.ts
7286
+ var import_scheduling68 = require("@ordinatio/scheduling");
7287
+ var NOT_ENABLED5 = { error: "Text-message settings are not enabled on this server" };
7288
+ function failure4(error, fallback) {
7289
+ if (error instanceof import_scheduling68.SchedulingValidationError) {
7290
+ const details = error.context.errors;
7291
+ return Response.json({ error: error.message, code: error.code, ref: getErrorRef(error), ...details ? { details } : {} }, { status: 400 });
7292
+ }
7293
+ console.error("[text-settings]", error);
7294
+ return Response.json({ error: fallback }, { status: 500 });
7295
+ }
7296
+ async function requireTextAdmin(host, request, options) {
7297
+ const staff = await requireAdminStaff(host, request, options);
7298
+ if (staff instanceof Response) return staff;
7299
+ if (!host.textMessages) return Response.json(NOT_ENABLED5, { status: 501 });
7300
+ return staff;
7301
+ }
7302
+ async function getTextSettingsRoute(request, { host }) {
7303
+ try {
7304
+ const staff = await requireTextAdmin(host, request, { action: "admin-text-settings-get", tier: "GENERAL" });
7305
+ if (staff instanceof Response) return staff;
7306
+ return Response.json({ settings: await (0, import_scheduling68.getTextSettings)(staff.db, staff.organizationId), providers: host.textMessages?.providers ?? ["TELNYX", "TWILIO"] });
7307
+ } catch (error) {
7308
+ return failure4(error, "Failed to read the text-message settings");
7309
+ }
7310
+ }
7311
+ async function saveTextSettingsRoute(request, { host }) {
7312
+ try {
7313
+ const staff = await requireTextAdmin(host, request, { action: "admin-text-settings-save", tier: "UPDATE" });
7314
+ if (staff instanceof Response) return staff;
7315
+ const validation = await parseBody(request, TextSettingsSchema);
7316
+ if (!validation.success) return validation.response;
7317
+ const settings = await (0, import_scheduling68.saveTextSettings)(staff.db, staff.organizationId, validation.data, { providers: host.textMessages?.providers });
7318
+ await host.activity.log(staff.db, {
7319
+ action: "scheduling.text_settings_saved",
7320
+ description: "changed the text-message settings",
7321
+ metadata: { provider: settings.provider, enabled: settings.enabled }
7322
+ });
7323
+ return Response.json({ settings });
7324
+ } catch (error) {
7325
+ return failure4(error, "Failed to save the text-message settings");
7326
+ }
7327
+ }
7328
+ async function deleteTextSettingsRoute(request, { host }) {
7329
+ try {
7330
+ const staff = await requireTextAdmin(host, request, { action: "admin-text-settings-delete", tier: "DELETE" });
7331
+ if (staff instanceof Response) return staff;
7332
+ const removed = await (0, import_scheduling68.deleteTextSettings)(staff.db, staff.organizationId);
7333
+ if (removed) await host.activity.log(staff.db, { action: "scheduling.text_settings_removed", description: "removed the text-message settings", metadata: {} });
7334
+ return Response.json({ removed });
7335
+ } catch (error) {
7336
+ return failure4(error, "Failed to remove the text-message settings");
7337
+ }
7338
+ }
7339
+
7340
+ // src/sending-domain/check-sending-domain.ts
7341
+ function recordsFor(records, domain) {
7342
+ return typeof records === "function" ? records(domain) : records;
7343
+ }
7344
+ var DOMAIN_PATTERN = /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;
7345
+ var NOT_FOUND_CODES = /* @__PURE__ */ new Set(["ENODATA", "ENOTFOUND"]);
7346
+ function normalizeSendingDomain(raw) {
7347
+ const domain = raw.trim().toLowerCase().replace(/\.$/, "");
7348
+ return DOMAIN_PATTERN.test(domain) ? domain : null;
7349
+ }
7350
+ function recordHost(record, domain) {
7351
+ return record.name === "@" ? domain : `${record.name}.${domain}`;
7352
+ }
7353
+ var clean = (value) => value.trim().replace(/\.$/, "").toLowerCase();
7354
+ function matches(record, published) {
7355
+ if (record.type === "CNAME") return clean(published) === clean(record.value);
7356
+ const fold = (value) => record.purpose === "dkim" ? value.trim() : value.trim().toLowerCase();
7357
+ if (record.match !== "contains") return fold(published) === fold(record.value);
7358
+ const terms = fold(published).split(/\s+/);
7359
+ return fold(record.value).split(/\s+/).every((term) => terms.includes(term));
7360
+ }
7361
+ async function lookUp(resolver, record, host) {
7362
+ if (record.type === "CNAME") return await resolver.resolveCname(host);
7363
+ return (await resolver.resolveTxt(host)).map((chunks) => chunks.join(""));
7364
+ }
7365
+ var label = { spf: "SPF", dkim: "DKIM", dmarc: "DMARC", other: "This" };
7366
+ async function checkRecord(resolver, record, domain) {
7367
+ const host = recordHost(record, domain);
7368
+ const who = label[record.purpose];
7369
+ try {
7370
+ const published = await lookUp(resolver, record, host);
7371
+ if (published.some((value) => matches(record, value))) {
7372
+ return { record, host, status: "found", message: `${who} record is in place.` };
7373
+ }
7374
+ const hint = published.length === 0 ? "is empty" : "does not match";
7375
+ return { record, host, status: "wrong", message: `${who} record at ${host} ${hint}. Replace it with the value shown.` };
7376
+ } catch (error) {
7377
+ const code = error?.code;
7378
+ if (code && NOT_FOUND_CODES.has(code)) {
7379
+ return { record, host, status: "missing", message: `${who} record not found at ${host}. Add it at your domain host. New records can take up to a day to appear.` };
7380
+ }
7381
+ return { record, host, status: "unknown", message: `${who} record could not be checked just now. Try again in a few minutes.` };
7382
+ }
7383
+ }
7384
+ async function checkSendingDomain(config, rawDomain) {
7385
+ const domain = normalizeSendingDomain(rawDomain);
7386
+ if (!domain) return { domain: rawDomain, verified: false, records: [] };
7387
+ const records = await Promise.all(recordsFor(config.records, domain).map((record) => checkRecord(config.resolver, record, domain)));
7388
+ const required = records.filter((check) => check.record.required !== false);
7389
+ const verified = required.length > 0 && required.every((check) => check.status === "found");
7390
+ return { domain, verified, records };
7391
+ }
7392
+
7393
+ // src/handlers/admin-brand-domain-check.ts
7394
+ async function checkSendingDomainRoute(request, { host }) {
7395
+ try {
7396
+ const staff = await requireBrandAdmin(host, request, { action: "admin-brand-domain-check", tier: "SETTINGS" });
7397
+ if (staff instanceof Response) return staff;
7398
+ const check = host.brand?.checkSendingDomain;
7399
+ if (!check) return Response.json({ error: "Sending-domain checking is not set up on this server" }, { status: 501 });
7400
+ const domain = normalizeSendingDomain(new URL(request.url).searchParams.get("domain") ?? "");
7401
+ if (!domain) return Response.json({ error: "Enter a domain such as mail.acme.com" }, { status: 400 });
7402
+ return Response.json({ check: await check.call(host.brand, domain, staff.organizationId) });
7403
+ } catch (error) {
7404
+ return brandErrorResponse(error, "Failed to check the sending domain");
7405
+ }
7406
+ }
7407
+
7408
+ // src/handlers/admin-privacy.ts
7409
+ var import_scheduling70 = require("@ordinatio/scheduling");
7123
7410
 
7124
7411
  // src/privacy/privacy-http.ts
7125
- var import_scheduling66 = require("@ordinatio/scheduling");
7126
- var NOT_ENABLED4 = { error: "Data export and erasure are not enabled on this server" };
7412
+ var import_scheduling69 = require("@ordinatio/scheduling");
7413
+ var NOT_ENABLED6 = { error: "Data export and erasure are not enabled on this server" };
7127
7414
  var STATUS_BY_CODE3 = { SCHED_1300: 400, SCHED_1301: 409 };
7128
7415
  function privacyErrorResponse(error, fallback) {
7129
- if (error instanceof import_scheduling66.SchedulingValidationError) {
7416
+ if (error instanceof import_scheduling69.SchedulingValidationError) {
7130
7417
  return Response.json(
7131
7418
  { error: error.message, code: error.code, ref: getErrorRef(error), details: error.context },
7132
7419
  { status: STATUS_BY_CODE3[error.code] ?? 400 }
@@ -7138,7 +7425,7 @@ function privacyErrorResponse(error, fallback) {
7138
7425
  async function requirePrivacyAdmin(host, request, options) {
7139
7426
  const staff = await requireAdminStaff(host, request, options);
7140
7427
  if (staff instanceof Response) return staff;
7141
- if (!host.privacy) return Response.json(NOT_ENABLED4, { status: 501 });
7428
+ if (!host.privacy) return Response.json(NOT_ENABLED6, { status: 501 });
7142
7429
  return staff;
7143
7430
  }
7144
7431
 
@@ -7156,7 +7443,7 @@ async function exportPrivacyRoute(request, { host }) {
7156
7443
  if (staff instanceof Response) return staff;
7157
7444
  const validation = await parseBody(request, PrivacySubjectSchema);
7158
7445
  if (!validation.success) return validation.response;
7159
- const result = await (0, import_scheduling67.exportSubject)(staff.db, { organizationId: staff.organizationId, requestedBy: staff.userId, ...validation.data });
7446
+ const result = await (0, import_scheduling70.exportSubject)(staff.db, { organizationId: staff.organizationId, requestedBy: staff.userId, ...validation.data });
7160
7447
  await logQuietly(host, staff.db, {
7161
7448
  action: "scheduling.privacy_export",
7162
7449
  description: "exported the data held about one person",
@@ -7183,10 +7470,10 @@ async function erasePrivacyRoute(request, { host }) {
7183
7470
  if (!validation.success) return validation.response;
7184
7471
  const { confirm, ...subject2 } = validation.data;
7185
7472
  if (confirm !== true) {
7186
- const preview = await (0, import_scheduling67.previewErase)(staff.db, { organizationId: staff.organizationId, ...subject2 });
7473
+ const preview = await (0, import_scheduling70.previewErase)(staff.db, { organizationId: staff.organizationId, ...subject2 });
7187
7474
  return Response.json({ erased: false, preview }, { headers: { "cache-control": "no-store" } });
7188
7475
  }
7189
- const { counts } = await (0, import_scheduling67.eraseSubject)(staff.db, { organizationId: staff.organizationId, requestedBy: staff.userId, ...subject2 });
7476
+ const { counts } = await (0, import_scheduling70.eraseSubject)(staff.db, { organizationId: staff.organizationId, requestedBy: staff.userId, ...subject2 });
7190
7477
  await logQuietly(host, staff.db, {
7191
7478
  action: "scheduling.privacy_erase",
7192
7479
  description: "erased the data held about one person",
@@ -7202,7 +7489,7 @@ async function listPrivacyRequestsRoute(request, { host }) {
7202
7489
  const staff = await requirePrivacyAdmin(host, request, { action: "admin-privacy-requests", tier: "GENERAL" });
7203
7490
  if (staff instanceof Response) return staff;
7204
7491
  const { limit, offset } = parsePagination(request);
7205
- const { requests, total } = await (0, import_scheduling67.listPrivacyRequests)(staff.db, { organizationId: staff.organizationId, limit, offset });
7492
+ const { requests, total } = await (0, import_scheduling70.listPrivacyRequests)(staff.db, { organizationId: staff.organizationId, limit, offset });
7206
7493
  return Response.json({ requests, total, hasMore: offset + requests.length < total });
7207
7494
  } catch (error) {
7208
7495
  return privacyErrorResponse(error, "Failed to list the requests");
@@ -7210,12 +7497,12 @@ async function listPrivacyRequestsRoute(request, { host }) {
7210
7497
  }
7211
7498
 
7212
7499
  // src/handlers/admin-routing-form-detail.ts
7213
- var import_scheduling68 = require("@ordinatio/scheduling");
7500
+ var import_scheduling71 = require("@ordinatio/scheduling");
7214
7501
  async function getRoutingFormAdminRoute(request, { host, params }) {
7215
7502
  try {
7216
7503
  const staff = await requireRoutingAdmin(host, request, { action: "admin-routing-forms-get", tier: "GENERAL" });
7217
7504
  if (staff instanceof Response) return staff;
7218
- return Response.json({ form: await (0, import_scheduling68.getRoutingForm)(staff.db, staff.organizationId, params.id) });
7505
+ return Response.json({ form: await (0, import_scheduling71.getRoutingForm)(staff.db, staff.organizationId, params.id) });
7219
7506
  } catch (error) {
7220
7507
  return routingErrorResponse(error, "Failed to read the form");
7221
7508
  }
@@ -7226,7 +7513,7 @@ async function updateRoutingFormRoute(request, { host, params }) {
7226
7513
  if (staff instanceof Response) return staff;
7227
7514
  const validation = await parseBody(request, UpdateRoutingFormSchema);
7228
7515
  if (!validation.success) return validation.response;
7229
- const form = await (0, import_scheduling68.updateRoutingForm)(staff.db, staff.organizationId, params.id, validation.data);
7516
+ const form = await (0, import_scheduling71.updateRoutingForm)(staff.db, staff.organizationId, params.id, validation.data);
7230
7517
  await host.activity.log(staff.db, {
7231
7518
  action: "scheduling.routing_form_updated",
7232
7519
  description: `changed routing form "${form.name}"`,
@@ -7241,7 +7528,7 @@ async function deleteRoutingFormRoute(request, { host, params }) {
7241
7528
  try {
7242
7529
  const staff = await requireRoutingAdmin(host, request, { action: "admin-routing-forms-delete", tier: "DELETE" });
7243
7530
  if (staff instanceof Response) return staff;
7244
- await (0, import_scheduling68.deleteRoutingForm)(staff.db, staff.organizationId, params.id);
7531
+ await (0, import_scheduling71.deleteRoutingForm)(staff.db, staff.organizationId, params.id);
7245
7532
  await host.activity.log(staff.db, { action: "scheduling.routing_form_deleted", description: "removed a routing form", metadata: { formId: params.id } });
7246
7533
  return Response.json({ success: true });
7247
7534
  } catch (error) {
@@ -7254,14 +7541,14 @@ async function testRoutingFormRoute(request, { host, params }) {
7254
7541
  if (staff instanceof Response) return staff;
7255
7542
  const validation = await parseBody(request, TestRoutingFormSchema);
7256
7543
  if (!validation.success) return validation.response;
7257
- return Response.json(await (0, import_scheduling68.testRoutingForm)(staff.db, { organizationId: staff.organizationId, id: params.id, answers: validation.data.answers }));
7544
+ return Response.json(await (0, import_scheduling71.testRoutingForm)(staff.db, { organizationId: staff.organizationId, id: params.id, answers: validation.data.answers }));
7258
7545
  } catch (error) {
7259
7546
  return routingErrorResponse(error, "Failed to test the form");
7260
7547
  }
7261
7548
  }
7262
7549
 
7263
7550
  // src/handlers/appointments-list.ts
7264
- var import_scheduling69 = require("@ordinatio/scheduling");
7551
+ var import_scheduling72 = require("@ordinatio/scheduling");
7265
7552
  var DEFAULT_LIMIT2 = 50;
7266
7553
  var MAX_LIMIT2 = 500;
7267
7554
  async function listAppointments(request, { host }) {
@@ -7273,7 +7560,7 @@ async function listAppointments(request, { host }) {
7273
7560
  const clientId = params.get("clientId") || void 0;
7274
7561
  const status = params.get("status") || void 0;
7275
7562
  if (!clientId && !staff.isAdmin) {
7276
- const err = (0, import_scheduling69.schedError)("SCHED_900", { role: staff.role });
7563
+ const err = (0, import_scheduling72.schedError)("SCHED_900", { role: staff.role });
7277
7564
  return Response.json({ error: "Forbidden", ref: err.ref }, { status: 403 });
7278
7565
  }
7279
7566
  const startDate = params.get("startDate");
@@ -7284,7 +7571,7 @@ async function listAppointments(request, { host }) {
7284
7571
  MAX_LIMIT2
7285
7572
  );
7286
7573
  const visibility = await staff.visibleCalendars();
7287
- const where = (0, import_scheduling69.withOrganization)({
7574
+ const where = (0, import_scheduling72.withOrganization)({
7288
7575
  ...visibility ? { calendar: visibility } : {},
7289
7576
  ...calendarId ? { calendarId } : {},
7290
7577
  ...clientId ? { clientId } : {},
@@ -7353,7 +7640,7 @@ async function listAppointments(request, { host }) {
7353
7640
  }
7354
7641
 
7355
7642
  // src/handlers/availability.ts
7356
- var import_scheduling70 = require("@ordinatio/scheduling");
7643
+ var import_scheduling73 = require("@ordinatio/scheduling");
7357
7644
 
7358
7645
  // src/availability/picked-day.ts
7359
7646
  var CALENDAR_DAY_SHAPE = /^\d{4}-\d{2}-\d{2}$/;
@@ -7466,7 +7753,7 @@ async function getAvailability(request, { host }) {
7466
7753
  const cached = await readCache(host.availabilityCache, calendarId, cacheDay, typeDuration);
7467
7754
  if (cached != null) return corsJson(cors, cached);
7468
7755
  }
7469
- const result = await (0, import_scheduling70.getAvailableSlots)(db, {
7756
+ const result = await (0, import_scheduling73.getAvailableSlots)(db, {
7470
7757
  calendarId,
7471
7758
  date: dateObj,
7472
7759
  localDate: pickedDay,
@@ -7487,7 +7774,7 @@ async function getAvailability(request, { host }) {
7487
7774
  }
7488
7775
 
7489
7776
  // src/handlers/availability-team.ts
7490
- var import_scheduling71 = require("@ordinatio/scheduling");
7777
+ var import_scheduling74 = require("@ordinatio/scheduling");
7491
7778
 
7492
7779
  // src/loaders/team-type.ts
7493
7780
  async function loadTeamType(db, typeId, organizationId) {
@@ -7535,7 +7822,7 @@ async function getTeamAvailability(request, { host }) {
7535
7822
  { status: 400 }
7536
7823
  );
7537
7824
  }
7538
- const result = await (0, import_scheduling71.getTeamAvailableSlots)(db, {
7825
+ const result = await (0, import_scheduling74.getTeamAvailableSlots)(db, {
7539
7826
  typeId,
7540
7827
  date: dateObj,
7541
7828
  localDate: pickedCalendarDay(date),
@@ -7558,7 +7845,7 @@ async function getTeamAvailability(request, { host }) {
7558
7845
  }
7559
7846
 
7560
7847
  // src/handlers/appointment-types.ts
7561
- var import_scheduling72 = require("@ordinatio/scheduling");
7848
+ var import_scheduling75 = require("@ordinatio/scheduling");
7562
7849
 
7563
7850
  // src/loaders/types-by-calendar.ts
7564
7851
  function loadTypesByCalendarSlug(cache, db, organizationId, calendarSlug) {
@@ -7632,19 +7919,19 @@ async function getAppointmentTypes(request, { host }) {
7632
7919
  }));
7633
7920
  return corsJson(cors, response, { headers: WIDGET_CACHE_HEADERS });
7634
7921
  } catch (error) {
7635
- const diagnostic = (0, import_scheduling72.schedError)("SCHED_202", { error });
7922
+ const diagnostic = (0, import_scheduling75.schedError)("SCHED_202", { error });
7636
7923
  console.error("[appointment-types]", diagnostic.ref, error);
7637
7924
  return corsJson(cors, { error: "Failed to fetch appointment types", ref: diagnostic.ref }, { status: 500 });
7638
7925
  }
7639
7926
  }
7640
7927
 
7641
7928
  // src/handlers/coupons-validate.ts
7642
- var import_zod19 = require("zod");
7643
- var import_scheduling73 = require("@ordinatio/scheduling");
7644
- var Schema4 = import_zod19.z.object({
7645
- code: import_zod19.z.string().min(1).max(50).transform((v) => v.trim().toUpperCase()),
7646
- calendarId: import_zod19.z.string().min(1),
7647
- price: import_zod19.z.number().positive()
7929
+ var import_zod21 = require("zod");
7930
+ var import_scheduling76 = require("@ordinatio/scheduling");
7931
+ var Schema4 = import_zod21.z.object({
7932
+ code: import_zod21.z.string().min(1).max(50).transform((v) => v.trim().toUpperCase()),
7933
+ calendarId: import_zod21.z.string().min(1),
7934
+ price: import_zod21.z.number().positive()
7648
7935
  });
7649
7936
  function calculateDiscount(price, discountType, discountValue) {
7650
7937
  if (discountType === "PERCENTAGE") {
@@ -7702,7 +7989,7 @@ async function validateCoupon(request, { host }) {
7702
7989
  { headers: host.cors(request) }
7703
7990
  );
7704
7991
  } catch (error) {
7705
- const err = (0, import_scheduling73.schedError)("SCHED_408", {
7992
+ const err = (0, import_scheduling76.schedError)("SCHED_408", {
7706
7993
  calendarId,
7707
7994
  error: error instanceof Error ? error.message : String(error)
7708
7995
  });
@@ -7782,7 +8069,7 @@ async function listActiveCalendars(request, { host }) {
7782
8069
  }
7783
8070
 
7784
8071
  // src/handlers/type.ts
7785
- var import_scheduling74 = require("@ordinatio/scheduling");
8072
+ var import_scheduling77 = require("@ordinatio/scheduling");
7786
8073
 
7787
8074
  // src/loaders/type-by-slug.ts
7788
8075
  function loadTypeBySlug(cache, db, organizationId, slug) {
@@ -7887,14 +8174,14 @@ async function getType(request, { host }) {
7887
8174
  { headers: WIDGET_CACHE_HEADERS }
7888
8175
  );
7889
8176
  } catch (error) {
7890
- const diagnostic = (0, import_scheduling74.schedError)("SCHED_207", { error });
8177
+ const diagnostic = (0, import_scheduling77.schedError)("SCHED_207", { error });
7891
8178
  console.error("[type]", diagnostic.ref, error);
7892
8179
  return corsJson(cors, { error: "Failed to fetch appointment type", ref: diagnostic.ref }, { status: 500 });
7893
8180
  }
7894
8181
  }
7895
8182
 
7896
8183
  // src/handlers/widget-init.ts
7897
- var import_scheduling75 = require("@ordinatio/scheduling");
8184
+ var import_scheduling78 = require("@ordinatio/scheduling");
7898
8185
 
7899
8186
  // src/loaders/widget-data.ts
7900
8187
  function loadWidgetData(cache, db, organizationId, calendarSlug) {
@@ -7983,7 +8270,7 @@ async function getWidgetInit(request, { host }) {
7983
8270
  }));
7984
8271
  return corsJson(cors, { calendar, types: sanitizedTypes }, { headers: WIDGET_CACHE_HEADERS });
7985
8272
  } catch (error) {
7986
- const diagnostic = (0, import_scheduling75.schedError)("SCHED_206", { error });
8273
+ const diagnostic = (0, import_scheduling78.schedError)("SCHED_206", { error });
7987
8274
  console.error("[widget-init]", diagnostic.ref, error);
7988
8275
  return corsJson(cors, { error: "Failed to load widget data", ref: diagnostic.ref }, { status: 500 });
7989
8276
  }
@@ -8058,6 +8345,13 @@ var ROUTES = [
8058
8345
  { method: "GET", path: "/admin/brand", public: false, handler: getBrandAdminRoute },
8059
8346
  { method: "PUT", path: "/admin/brand", public: false, handler: saveBrandRoute },
8060
8347
  { method: "DELETE", path: "/admin/brand", public: false, handler: deleteBrandRoute },
8348
+ { method: "GET", path: "/admin/text-settings", public: false, handler: getTextSettingsRoute },
8349
+ { method: "PUT", path: "/admin/text-settings", public: false, handler: saveTextSettingsRoute },
8350
+ { method: "DELETE", path: "/admin/text-settings", public: false, handler: deleteTextSettingsRoute },
8351
+ { method: "GET", path: "/admin/api-keys", public: false, handler: listApiKeysRoute },
8352
+ { method: "POST", path: "/admin/api-keys", public: false, handler: createApiKeyRoute },
8353
+ { method: "DELETE", path: "/admin/api-keys/[id]", public: false, handler: revokeApiKeyRoute },
8354
+ { method: "GET", path: "/admin/brand/sending-domain", public: false, handler: checkSendingDomainRoute },
8061
8355
  { method: "POST", path: "/admin/privacy/export", public: false, handler: exportPrivacyRoute },
8062
8356
  { method: "POST", path: "/admin/privacy/erase", public: false, handler: erasePrivacyRoute },
8063
8357
  { method: "GET", path: "/admin/privacy/requests", public: false, handler: listPrivacyRequestsRoute },
@@ -8091,11 +8385,11 @@ var ROUTES = [
8091
8385
  { method: "POST", path: "/appointments/[id]/followup", public: false, handler: sendFollowup },
8092
8386
  { method: "POST", path: "/appointments/[id]/remind", public: false, handler: sendReminder },
8093
8387
  { method: "POST", path: "/appointments/[id]/cancel", public: false, handler: cancelByStaff },
8094
- { method: "GET", path: "/calendars/connect-google", public: false, handler: startGoogleConnection },
8095
- { method: "POST", path: "/calendars/connect-google", public: false, handler: setGoogleCalendar },
8096
- { method: "GET", path: "/calendars/connect-google/callback", public: false, handler: finishGoogleConnection },
8097
- { method: "GET", path: "/calendars/connect-outlook", public: false, handler: startOutlookConnection },
8098
- { method: "GET", path: "/calendars/connect-outlook/callback", public: false, handler: finishOutlookConnection },
8388
+ { method: "GET", path: "/calendars/connect-google", public: false, personOnly: true, handler: startGoogleConnection },
8389
+ { method: "POST", path: "/calendars/connect-google", public: false, personOnly: true, handler: setGoogleCalendar },
8390
+ { method: "GET", path: "/calendars/connect-google/callback", public: false, personOnly: true, handler: finishGoogleConnection },
8391
+ { method: "GET", path: "/calendars/connect-outlook", public: false, personOnly: true, handler: startOutlookConnection },
8392
+ { method: "GET", path: "/calendars/connect-outlook/callback", public: false, personOnly: true, handler: finishOutlookConnection },
8099
8393
  { method: "POST", path: "/appointments/[id]/cancel-sync", public: false, handler: cancelFromCalendarSync },
8100
8394
  { method: "POST", path: "/appointments/[id]/approve", public: false, handler: approveOrReject },
8101
8395
  { method: "POST", path: "/appointments/[id]/reschedule", public: false, handler: rescheduleByStaff },
@@ -8152,6 +8446,8 @@ function createSchedulingApi(config) {
8152
8446
  routingForms: config.host.routingForms ?? null,
8153
8447
  privacy: config.host.privacy ?? null,
8154
8448
  brand: config.host.brand ?? null,
8449
+ textMessages: config.host.textMessages ?? null,
8450
+ apiKeys: config.host.apiKeys ?? null,
8155
8451
  icalUidDomain: config.host.icalUidDomain?.bind(config.host) ?? (() => null),
8156
8452
  calendarSync: config.host.calendarSync ?? { upsertEvent: async () => ({}), removeEvent: async () => void 0 },
8157
8453
  activity: config.host.activity ?? { log: async () => void 0, isOpen: async () => false, resolve: async () => void 0 },
@@ -8179,24 +8475,34 @@ function createSchedulingApi(config) {
8179
8475
  cors: config.host.cors?.bind(config.host) ?? defaultCorsHeaders
8180
8476
  };
8181
8477
  host.events = withWebhooks(withWaitlist(config.host.events ?? { emit: async () => void 0 }, host), host);
8478
+ async function hostForRoute(route, request) {
8479
+ try {
8480
+ return await hostForRequest(host, request, route);
8481
+ } catch (error) {
8482
+ console.error("[scheduling-api] could not check the API key:", error);
8483
+ return Response.json({ error: "Internal error" }, { status: 500 });
8484
+ }
8485
+ }
8182
8486
  async function handle(request) {
8183
8487
  const { pathname } = new URL(request.url);
8184
8488
  if (pathname !== basePath && !pathname.startsWith(`${basePath}/`)) return notFound();
8185
8489
  const relative = pathname.slice(basePath.length) || "/";
8186
- const matches = routes.map((route) => ({ route, params: matchPath(route.path, relative) })).filter((match) => match.params !== null);
8187
- if (matches.length === 0) return notFound();
8490
+ const matches2 = routes.map((route) => ({ route, params: matchPath(route.path, relative) })).filter((match) => match.params !== null);
8491
+ if (matches2.length === 0) return notFound();
8188
8492
  const method = request.method.toUpperCase();
8189
- if (method === "OPTIONS" && matches.some((match) => match.route.public)) {
8493
+ if (method === "OPTIONS" && matches2.some((match) => match.route.public)) {
8190
8494
  return new Response(null, { status: 204, headers: host.cors(request) });
8191
8495
  }
8192
- const hit = matches.find((match) => match.route.method === method);
8496
+ const hit = matches2.find((match) => match.route.method === method);
8193
8497
  if (!hit) {
8194
- const allowed = [...new Set(matches.map((match) => match.route.method))];
8195
- if (matches.some((match) => match.route.public)) allowed.push("OPTIONS");
8498
+ const allowed = [...new Set(matches2.map((match) => match.route.method))];
8499
+ if (matches2.some((match) => match.route.public)) allowed.push("OPTIONS");
8196
8500
  return Response.json({ error: "Method not allowed" }, { status: 405, headers: { Allow: allowed.join(", ") } });
8197
8501
  }
8198
8502
  try {
8199
- return await hit.route.handler(request, { host, params: hit.params });
8503
+ const runHost = await hostForRoute(hit.route, request);
8504
+ if (runHost instanceof Response) return runHost;
8505
+ return await hit.route.handler(request, { host: runHost, params: hit.params });
8200
8506
  } catch (error) {
8201
8507
  console.error("[scheduling-api] unhandled error:", error);
8202
8508
  return Response.json({ error: "Internal error" }, { status: 500 });
@@ -8207,7 +8513,9 @@ function createSchedulingApi(config) {
8207
8513
  if (!route) throw new Error(`No route ${method} ${path}`);
8208
8514
  return async (request, context) => {
8209
8515
  const params = await context?.params ?? {};
8210
- return route.handler(request, { host, params });
8516
+ const runHost = await hostForRoute(route, request);
8517
+ if (runHost instanceof Response) return runHost;
8518
+ return route.handler(request, { host: runHost, params });
8211
8519
  };
8212
8520
  }
8213
8521
  return { routes, handle, handler };
@@ -8357,41 +8665,609 @@ function assertStripeTestKey(raw) {
8357
8665
  return key;
8358
8666
  }
8359
8667
 
8360
- // src/staff/simple-staff.ts
8361
- var DEFAULT_ADMIN_ROLES = ["OWNER", "ADMIN", "MANAGER"];
8362
- function createStaffContext(input) {
8363
- const adminRoles = (input.adminRoles ?? DEFAULT_ADMIN_ROLES).map((role) => role.toUpperCase());
8364
- const { db, organizationId } = input;
8668
+ // src/sending-domain/create-sending-domain-verifier.ts
8669
+ function createSendingDomainVerifier(config) {
8670
+ const check = (domain) => checkSendingDomain(config, domain);
8365
8671
  return {
8366
- userId: input.userId,
8367
- organizationId,
8368
- role: input.role,
8369
- isAdmin: adminRoles.includes(input.role.toUpperCase()),
8370
- schedulingEnabled: input.schedulingEnabled ?? true,
8371
- db,
8372
- visibleCalendars: async () => null,
8373
- visibleCalendarIds: async () => void 0,
8374
- canSeeCalendar: async (calendarId) => Boolean(await db.schedulingCalendar.findFirst({ where: { id: calendarId, organizationId }, select: { id: true } })),
8375
- canSeeAppointment: async (appointmentId) => Boolean(await db.appointment.findFirst({ where: { id: appointmentId, calendar: { organizationId } }, select: { id: true } })),
8376
- // The package has no client table, so there is no preference to read.
8377
- preferredLocationOf: async () => null
8672
+ isSendingDomainVerified: async (domain) => (await check(domain)).verified,
8673
+ check,
8674
+ instructions: (rawDomain) => {
8675
+ const domain = normalizeSendingDomain(rawDomain);
8676
+ return domain ? recordsFor(config.records, domain).map((record) => ({ record, host: recordHost(record, domain) })) : [];
8677
+ }
8378
8678
  };
8379
8679
  }
8380
- var BEARER = /^bearer\s+(\S+)$/i;
8381
- function createBearerStaffResolver(input) {
8680
+
8681
+ // src/sms/sms-common.ts
8682
+ var SmsSendError = class extends Error {
8683
+ constructor(message, retryable, outcomeUnknown, status, code) {
8684
+ super(message);
8685
+ this.retryable = retryable;
8686
+ this.outcomeUnknown = outcomeUnknown;
8687
+ this.status = status;
8688
+ this.code = code;
8689
+ this.name = "SmsSendError";
8690
+ }
8691
+ };
8692
+ function normalizePhoneNumber(raw) {
8693
+ const digits = raw.trim().replace(/[\s().-]/g, "");
8694
+ if (/^\+[1-9]\d{7,14}$/.test(digits)) return digits;
8695
+ if (/^\d{10}$/.test(digits)) return `+1${digits}`;
8696
+ if (/^1\d{10}$/.test(digits)) return `+${digits}`;
8697
+ return null;
8698
+ }
8699
+ function readHeader(headers, name) {
8700
+ if (typeof headers.get === "function") return headers.get(name) ?? void 0;
8701
+ const found = Object.entries(headers).find(([key]) => key.toLowerCase() === name);
8702
+ const value = found?.[1];
8703
+ return Array.isArray(value) ? value[0] : value;
8704
+ }
8705
+ var STOP_WORDS = ["STOP", "STOPALL", "UNSUBSCRIBE", "END", "QUIT"];
8706
+ var START_WORDS = ["START", "UNSTOP"];
8707
+ function classifyReply(text) {
8708
+ const word = text.trim().toUpperCase().replace(/[.!?,]+$/, "");
8709
+ return STOP_WORDS.includes(word) ? "opt-out" : START_WORDS.includes(word) ? "opt-in" : "reply";
8710
+ }
8711
+
8712
+ // src/telnyx/telnyx-sms.ts
8713
+ var TELNYX_MESSAGES_URL = "https://api.telnyx.com/v2/messages";
8714
+ var DEFAULT_TIMEOUT_MS = 1e4;
8715
+ var OPTED_OUT_CODE = "40300";
8716
+ function firstError(body) {
8717
+ const error = body?.errors?.[0];
8718
+ if (!error) return { text: "no detail given" };
8719
+ return { code: error.code === void 0 ? void 0 : String(error.code), text: error.detail ?? error.title ?? "no detail given" };
8720
+ }
8721
+ function createTelnyxSmsAdapter(config) {
8722
+ const apiKey = typeof config.apiKey === "string" ? config.apiKey.trim() : "";
8723
+ if (!apiKey) throw new Error("createTelnyxSmsAdapter needs an apiKey");
8724
+ const profileId = config.messagingProfileId?.trim() || void 0;
8725
+ const from = config.from ? normalizePhoneNumber(config.from) : null;
8726
+ if (config.from && !from) throw new Error('createTelnyxSmsAdapter: "from" must be a phone number such as +13135550100');
8727
+ if (!from && !profileId) throw new Error('createTelnyxSmsAdapter needs a sending number ("from"), a messagingProfileId, or both');
8728
+ const doFetch = config.fetch ?? fetch;
8729
+ const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
8382
8730
  return {
8383
- async resolve(request) {
8384
- const token = BEARER.exec(request.headers.get("authorization") ?? "")?.[1];
8385
- if (!token) return null;
8386
- const person = await input.authenticate(token, request);
8387
- if (!person) return null;
8388
- return createStaffContext({
8389
- ...person,
8390
- db: await input.db(person),
8391
- adminRoles: input.adminRoles,
8392
- schedulingEnabled: input.schedulingEnabled ? await input.schedulingEnabled(person) : void 0
8731
+ async send(message) {
8732
+ if (message.channel !== "SMS") return { status: "SKIPPED", reason: "The Telnyx adapter only sends text messages" };
8733
+ const to = normalizePhoneNumber(message.to);
8734
+ if (!to) return { status: "SKIPPED", reason: "The recipient is not a valid phone number" };
8735
+ if (!message.body.trim()) return { status: "SKIPPED", reason: "The message is empty" };
8736
+ const controller = new AbortController();
8737
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
8738
+ let response;
8739
+ let body;
8740
+ try {
8741
+ response = await doFetch(TELNYX_MESSAGES_URL, {
8742
+ method: "POST",
8743
+ headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
8744
+ body: JSON.stringify({
8745
+ to,
8746
+ text: message.body,
8747
+ type: "SMS",
8748
+ ...from ? { from } : {},
8749
+ ...profileId ? { messaging_profile_id: profileId } : {}
8750
+ }),
8751
+ signal: controller.signal
8752
+ });
8753
+ body = await response.json().catch((error) => {
8754
+ if (controller.signal.aborted) throw error;
8755
+ return null;
8756
+ });
8757
+ } catch (error) {
8758
+ const reason = controller.signal.aborted ? `timed out after ${timeoutMs} ms` : error instanceof Error ? error.message : String(error);
8759
+ throw new SmsSendError(`Telnyx could not be reached (${reason}); the message may or may not have been sent`, true, true);
8760
+ } finally {
8761
+ clearTimeout(timer);
8762
+ }
8763
+ if (response.ok) {
8764
+ const id = body?.data?.id;
8765
+ return id ? { status: "SENT", id } : { status: "SENT" };
8766
+ }
8767
+ const { code, text } = firstError(body);
8768
+ if (code === OPTED_OUT_CODE) return { status: "SKIPPED", reason: "The recipient opted out of text messages" };
8769
+ const serverFault = response.status >= 500;
8770
+ const retryable = response.status === 429 || serverFault;
8771
+ throw new SmsSendError(
8772
+ `Telnyx refused the message (HTTP ${response.status}${code ? `, code ${code}` : ""}): ${text}`,
8773
+ retryable,
8774
+ serverFault,
8775
+ response.status,
8776
+ code
8777
+ );
8778
+ }
8779
+ };
8780
+ }
8781
+
8782
+ // src/telnyx/telnyx-inbound.ts
8783
+ var import_node_crypto3 = require("crypto");
8784
+ var ED25519_SPKI_PREFIX = Buffer.from("302a300506032b6570032100", "hex");
8785
+ var DEFAULT_TOLERANCE_SECONDS = 300;
8786
+ function verifyTelnyxSignature(rawBody, headers, options) {
8787
+ const signature = readHeader(headers, "telnyx-signature-ed25519");
8788
+ const timestamp = readHeader(headers, "telnyx-timestamp");
8789
+ if (!signature || !timestamp || !/^\d+$/.test(timestamp)) return false;
8790
+ const nowSeconds = Math.floor((options.now?.() ?? /* @__PURE__ */ new Date()).getTime() / 1e3);
8791
+ if (Math.abs(nowSeconds - Number(timestamp)) > (options.toleranceSeconds ?? DEFAULT_TOLERANCE_SECONDS)) return false;
8792
+ try {
8793
+ const raw = Buffer.from(options.publicKey.trim(), "base64");
8794
+ if (raw.length !== 32) return false;
8795
+ const key = (0, import_node_crypto3.createPublicKey)({ key: Buffer.concat([ED25519_SPKI_PREFIX, raw]), format: "der", type: "spki" });
8796
+ return (0, import_node_crypto3.verify)(null, Buffer.from(`${timestamp}|${rawBody}`), key, Buffer.from(signature, "base64"));
8797
+ } catch {
8798
+ return false;
8799
+ }
8800
+ }
8801
+ function handleTelnyxWebhook(rawBody, headers, options) {
8802
+ if (!verifyTelnyxSignature(rawBody, headers, options)) return { ok: false, status: 401, reason: "The signature is missing, wrong or too old" };
8803
+ let parsed;
8804
+ try {
8805
+ const value = JSON.parse(rawBody);
8806
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return { ok: false, status: 400, reason: "The body is not an event" };
8807
+ parsed = value;
8808
+ } catch {
8809
+ return { ok: false, status: 400, reason: "The body is not JSON" };
8810
+ }
8811
+ const eventType = parsed.data?.event_type ?? "";
8812
+ const payload = parsed.data?.payload;
8813
+ const id = payload?.id;
8814
+ const to = payload?.to?.[0]?.phone_number;
8815
+ if (eventType === "message.received") {
8816
+ const from = payload?.from?.phone_number;
8817
+ if (!id || !from || !to) return { ok: false, status: 400, reason: "The message is missing its id or phone numbers" };
8818
+ const text = typeof payload?.text === "string" ? payload.text : "";
8819
+ const type = classifyReply(text);
8820
+ return { ok: true, event: { type, id, from, to, text } };
8821
+ }
8822
+ if (eventType === "message.finalized" || eventType === "message.sent") {
8823
+ if (!id || !to) return { ok: false, status: 400, reason: "The delivery report is missing its id or number" };
8824
+ const status = payload?.to?.[0]?.status;
8825
+ if (eventType === "message.sent" || status !== "delivered" && status !== "delivery_failed" && status !== "sending_failed") {
8826
+ return { ok: true, event: { type: "ignored", eventType } };
8827
+ }
8828
+ const errorCode = payload?.errors?.[0]?.code;
8829
+ return {
8830
+ ok: true,
8831
+ event: { type: "delivery", id, to, status: status === "delivered" ? "delivered" : "failed", ...errorCode === void 0 ? {} : { errorCode: String(errorCode) } }
8832
+ };
8833
+ }
8834
+ return { ok: true, event: { type: "ignored", eventType } };
8835
+ }
8836
+
8837
+ // src/twilio/twilio-sms.ts
8838
+ var DEFAULT_TIMEOUT_MS2 = 1e4;
8839
+ var OPTED_OUT_CODE2 = "21610";
8840
+ function createTwilioSmsAdapter(config) {
8841
+ const accountSid = typeof config.accountSid === "string" ? config.accountSid.trim() : "";
8842
+ const authToken = typeof config.authToken === "string" ? config.authToken.trim() : "";
8843
+ if (!accountSid || !authToken) throw new Error("createTwilioSmsAdapter needs an accountSid and an authToken");
8844
+ const serviceSid = config.messagingServiceSid?.trim() || void 0;
8845
+ const from = config.from ? normalizePhoneNumber(config.from) : null;
8846
+ if (config.from && !from) throw new Error('createTwilioSmsAdapter: "from" must be a phone number such as +13135550100');
8847
+ if (!from && !serviceSid) throw new Error('createTwilioSmsAdapter needs a sending number ("from") or a messagingServiceSid');
8848
+ const doFetch = config.fetch ?? fetch;
8849
+ const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
8850
+ const url = `https://api.twilio.com/2010-04-01/Accounts/${encodeURIComponent(accountSid)}/Messages.json`;
8851
+ const authorization = `Basic ${Buffer.from(`${accountSid}:${authToken}`).toString("base64")}`;
8852
+ return {
8853
+ async send(message) {
8854
+ if (message.channel !== "SMS") return { status: "SKIPPED", reason: "The Twilio adapter only sends text messages" };
8855
+ const to = normalizePhoneNumber(message.to);
8856
+ if (!to) return { status: "SKIPPED", reason: "The recipient is not a valid phone number" };
8857
+ if (!message.body.trim()) return { status: "SKIPPED", reason: "The message is empty" };
8858
+ const form = new URLSearchParams({ To: to, Body: message.body });
8859
+ if (from) form.set("From", from);
8860
+ else if (serviceSid) form.set("MessagingServiceSid", serviceSid);
8861
+ const controller = new AbortController();
8862
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
8863
+ let response;
8864
+ let body;
8865
+ try {
8866
+ response = await doFetch(url, {
8867
+ method: "POST",
8868
+ headers: { Authorization: authorization, "Content-Type": "application/x-www-form-urlencoded" },
8869
+ body: form.toString(),
8870
+ signal: controller.signal
8871
+ });
8872
+ body = await response.json().catch((error2) => {
8873
+ if (controller.signal.aborted) throw error2;
8874
+ return null;
8875
+ });
8876
+ } catch (error2) {
8877
+ const reason = controller.signal.aborted ? `timed out after ${timeoutMs} ms` : error2 instanceof Error ? error2.message : String(error2);
8878
+ throw new SmsSendError(`Twilio could not be reached (${reason}); the message may or may not have been sent`, true, true);
8879
+ } finally {
8880
+ clearTimeout(timer);
8881
+ }
8882
+ if (response.ok) {
8883
+ const id = body?.sid;
8884
+ return id ? { status: "SENT", id } : { status: "SENT" };
8885
+ }
8886
+ const error = body ?? {};
8887
+ const code = error.code === void 0 ? void 0 : String(error.code);
8888
+ if (code === OPTED_OUT_CODE2) return { status: "SKIPPED", reason: "The recipient opted out of text messages" };
8889
+ const serverFault = response.status >= 500;
8890
+ throw new SmsSendError(
8891
+ `Twilio refused the message (HTTP ${response.status}${code ? `, code ${code}` : ""}): ${error.message ?? "no detail given"}`,
8892
+ response.status === 429 || serverFault,
8893
+ serverFault,
8894
+ response.status,
8895
+ code
8896
+ );
8897
+ }
8898
+ };
8899
+ }
8900
+
8901
+ // src/twilio/twilio-inbound.ts
8902
+ var import_node_crypto4 = require("crypto");
8903
+ function expectedSignature(params, options) {
8904
+ const keys = [...new Set(params.keys())].sort();
8905
+ const signed = keys.reduce((text, key) => text + key + params.getAll(key).join(""), options.url);
8906
+ return (0, import_node_crypto4.createHmac)("sha1", options.authToken.trim()).update(signed).digest("base64");
8907
+ }
8908
+ function verifyTwilioSignature(rawBody, headers, options) {
8909
+ const given = readHeader(headers, "x-twilio-signature");
8910
+ if (!given || !options.authToken.trim()) return false;
8911
+ const expected = Buffer.from(expectedSignature(new URLSearchParams(rawBody), options));
8912
+ const actual = Buffer.from(given);
8913
+ return expected.length === actual.length && (0, import_node_crypto4.timingSafeEqual)(expected, actual);
8914
+ }
8915
+ function handleTwilioWebhook(rawBody, headers, options) {
8916
+ if (!verifyTwilioSignature(rawBody, headers, options)) return { ok: false, status: 401, reason: "The signature is missing or wrong" };
8917
+ const params = new URLSearchParams(rawBody);
8918
+ const id = params.get("MessageSid") ?? params.get("SmsSid");
8919
+ const from = params.get("From");
8920
+ const to = params.get("To");
8921
+ if (params.has("MessageStatus") && !params.has("Body")) {
8922
+ const status = params.get("MessageStatus") ?? "";
8923
+ if (!id || !to) return { ok: false, status: 400, reason: "The status report is missing its id or number" };
8924
+ if (status !== "delivered" && status !== "undelivered" && status !== "failed") return { ok: true, event: { type: "ignored", eventType: `status.${status}` } };
8925
+ const errorCode = params.get("ErrorCode");
8926
+ return { ok: true, event: { type: "delivery", id, to, status: status === "delivered" ? "delivered" : "failed", ...errorCode ? { errorCode } : {} } };
8927
+ }
8928
+ if (params.has("Body")) {
8929
+ if (!id || !from || !to) return { ok: false, status: 400, reason: "The message is missing its id or phone numbers" };
8930
+ const text = params.get("Body") ?? "";
8931
+ return { ok: true, event: { type: classifyReply(text), id, from, to, text } };
8932
+ }
8933
+ return { ok: true, event: { type: "ignored", eventType: "unknown" } };
8934
+ }
8935
+
8936
+ // src/sms/per-business-sms.ts
8937
+ var DEFAULT_ADAPTER_TTL_MS = 5 * 6e4;
8938
+ var DEFAULT_NO_NUMBER_TTL_MS = 6e4;
8939
+ function createPerBusinessSmsAdapter(options) {
8940
+ const adapterTtl = options.adapterTtlMs ?? DEFAULT_ADAPTER_TTL_MS;
8941
+ const noNumberTtl = options.noNumberTtlMs ?? DEFAULT_NO_NUMBER_TTL_MS;
8942
+ const now = options.now ?? Date.now;
8943
+ const kept = /* @__PURE__ */ new Map();
8944
+ function adapterFor(organizationId) {
8945
+ const existing = kept.get(organizationId);
8946
+ if (existing && (existing.expiresAt === null || existing.expiresAt > now())) return existing.lookup;
8947
+ const entry = { lookup: Promise.resolve(options.resolve(organizationId)), expiresAt: null };
8948
+ kept.set(organizationId, entry);
8949
+ entry.lookup.then(
8950
+ (adapter) => {
8951
+ entry.expiresAt = now() + (adapter ? adapterTtl : noNumberTtl);
8952
+ },
8953
+ // A failed lookup is not kept; only this entry is removed, not a newer one.
8954
+ () => {
8955
+ if (kept.get(organizationId) === entry) kept.delete(organizationId);
8956
+ }
8957
+ );
8958
+ return entry.lookup;
8959
+ }
8960
+ return {
8961
+ async send(message) {
8962
+ if (message.channel !== "SMS") return { status: "SKIPPED", reason: "This adapter only sends text messages" };
8963
+ if (!message.organizationId) {
8964
+ return { status: "SKIPPED", reason: "The message names no business, so there is no number to send from (run the sender with organization: true)" };
8965
+ }
8966
+ const adapter = await adapterFor(message.organizationId);
8967
+ if (!adapter) return { status: "SKIPPED", reason: "This business has no text-message number set up" };
8968
+ return adapter.send(message);
8969
+ },
8970
+ forget(organizationId) {
8971
+ kept.delete(organizationId);
8972
+ }
8973
+ };
8974
+ }
8975
+
8976
+ // src/sms/text-settings-resolver.ts
8977
+ var import_scheduling79 = require("@ordinatio/scheduling");
8978
+ function createTextSettingsResolver(options) {
8979
+ return async (organizationId) => {
8980
+ const settings = await (0, import_scheduling79.getTextSettings)(await options.db(organizationId), organizationId);
8981
+ if (!settings || !settings.enabled) return null;
8982
+ try {
8983
+ if (settings.provider === "TELNYX" && options.telnyx?.apiKey?.trim()) {
8984
+ return createTelnyxSmsAdapter({ ...options.telnyx, from: settings.fromNumber, fetch: options.fetch });
8985
+ }
8986
+ if (settings.provider === "TWILIO" && options.twilio?.accountSid?.trim() && options.twilio.authToken?.trim()) {
8987
+ return createTwilioSmsAdapter({ ...options.twilio, from: settings.fromNumber, fetch: options.fetch });
8988
+ }
8989
+ } catch (error) {
8990
+ console.error(`[text-settings] could not build the ${settings.provider} sender for organization ${organizationId}:`, error instanceof Error ? error.message : error);
8991
+ return null;
8992
+ }
8993
+ if (settings.provider === "TELNYX" || settings.provider === "TWILIO") {
8994
+ console.error(`[text-settings] organization ${organizationId} chose ${settings.provider}, but this server has no usable ${settings.provider} account`);
8995
+ }
8996
+ return null;
8997
+ };
8998
+ }
8999
+
9000
+ // src/outlook-sync/outlook-config.ts
9001
+ var BLOCKED_TYPE_SLUG = "blocked";
9002
+ var GRAPH_BASE = "https://graph.microsoft.com/v1.0";
9003
+ var MICROSOFT_TOKEN_ENDPOINT = "https://login.microsoftonline.com/common/oauth2/v2.0/token";
9004
+ var OUTLOOK_CALENDAR_SCOPE = "https://graph.microsoft.com/Calendars.ReadWrite offline_access";
9005
+ function problem(config, message, context) {
9006
+ config.onProblem?.(message, context);
9007
+ }
9008
+
9009
+ // src/outlook-sync/outlook-access-token.ts
9010
+ var REFRESH_MARGIN_MS = 5 * 60 * 1e3;
9011
+ async function getOutlookAccessToken(config, calendarId) {
9012
+ const calendar = await config.db.schedulingCalendar.findUnique({
9013
+ where: { id: calendarId },
9014
+ select: {
9015
+ outlookCalendarId: true,
9016
+ outlookAccessToken: true,
9017
+ outlookRefreshToken: true,
9018
+ outlookTokenExpiresAt: true
9019
+ }
9020
+ });
9021
+ if (!calendar?.outlookCalendarId || !calendar.outlookRefreshToken) return null;
9022
+ const now = (config.now ?? (() => /* @__PURE__ */ new Date()))();
9023
+ const stillValid = calendar.outlookAccessToken && calendar.outlookTokenExpiresAt && calendar.outlookTokenExpiresAt.getTime() - now.getTime() >= REFRESH_MARGIN_MS;
9024
+ if (stillValid) return calendar.outlookAccessToken;
9025
+ try {
9026
+ const response = await (config.fetch ?? fetch)(MICROSOFT_TOKEN_ENDPOINT, {
9027
+ method: "POST",
9028
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
9029
+ body: new URLSearchParams({
9030
+ client_id: config.clientId.trim(),
9031
+ client_secret: config.clientSecret.trim(),
9032
+ refresh_token: calendar.outlookRefreshToken,
9033
+ grant_type: "refresh_token",
9034
+ scope: OUTLOOK_CALENDAR_SCOPE
9035
+ })
9036
+ });
9037
+ if (!response.ok) throw new Error(`Token refresh HTTP ${response.status}`);
9038
+ const data = await response.json();
9039
+ if (!data.access_token || typeof data.expires_in !== "number") throw new Error("Token refresh answered without a token");
9040
+ await config.db.schedulingCalendar.update({
9041
+ where: { id: calendarId },
9042
+ data: {
9043
+ outlookAccessToken: data.access_token,
9044
+ outlookRefreshToken: data.refresh_token ?? calendar.outlookRefreshToken,
9045
+ outlookTokenExpiresAt: new Date(now.getTime() + data.expires_in * 1e3)
9046
+ }
9047
+ });
9048
+ return data.access_token;
9049
+ } catch (error) {
9050
+ problem(config, "Outlook token refresh failed; the calendar must be reconnected", {
9051
+ calendarId,
9052
+ error: error instanceof Error ? error.message : String(error)
9053
+ });
9054
+ return null;
9055
+ }
9056
+ }
9057
+
9058
+ // src/outlook-sync/outlook-push.ts
9059
+ async function pushAppointmentToOutlook(config, appointmentId) {
9060
+ const appointment = await config.db.appointment.findUnique({
9061
+ where: { id: appointmentId },
9062
+ include: {
9063
+ type: { select: { name: true, slug: true } },
9064
+ calendar: { select: { id: true, outlookCalendarId: true } }
9065
+ }
9066
+ });
9067
+ if (!appointment?.calendar.outlookCalendarId) return null;
9068
+ if (appointment.type.slug === BLOCKED_TYPE_SLUG) return null;
9069
+ const accessToken = await getOutlookAccessToken(config, appointment.calendarId);
9070
+ if (!accessToken) return null;
9071
+ const body = {
9072
+ subject: `${appointment.type.name} \u2014 ${appointment.clientName}`,
9073
+ body: {
9074
+ contentType: "text",
9075
+ content: [
9076
+ `Service: ${appointment.type.name}`,
9077
+ `Duration: ${appointment.duration} min`,
9078
+ appointment.clientPhone ? `Phone: ${appointment.clientPhone}` : "",
9079
+ appointment.clientEmail ? `Email: ${appointment.clientEmail}` : ""
9080
+ ].filter(Boolean).join("\n")
9081
+ },
9082
+ // UTC on both sides so the event lands at the stored instant whatever zone the Outlook calendar uses.
9083
+ start: { dateTime: appointment.startTime.toISOString(), timeZone: "UTC" },
9084
+ end: { dateTime: appointment.endTime.toISOString(), timeZone: "UTC" }
9085
+ };
9086
+ const calendarUrl = `${GRAPH_BASE}/me/calendars/${encodeURIComponent(appointment.calendar.outlookCalendarId)}/events`;
9087
+ const isUpdate = Boolean(appointment.outlookEventId);
9088
+ const method = isUpdate ? "PATCH" : "POST";
9089
+ const url = isUpdate ? `${calendarUrl}/${encodeURIComponent(appointment.outlookEventId)}` : calendarUrl;
9090
+ const response = await (config.fetch ?? fetch)(url, {
9091
+ method,
9092
+ headers: { Authorization: `Bearer ${accessToken}`, "Content-Type": "application/json" },
9093
+ body: JSON.stringify(body)
9094
+ });
9095
+ if (!response.ok) throw new Error(`Outlook ${method} event failed with HTTP ${response.status}`);
9096
+ const created = await response.json();
9097
+ if (!isUpdate && created.id) {
9098
+ try {
9099
+ await config.db.appointment.update({ where: { id: appointmentId }, data: { outlookEventId: created.id } });
9100
+ } catch (error) {
9101
+ const removed = await (config.fetch ?? fetch)(`${calendarUrl}/${encodeURIComponent(created.id)}`, {
9102
+ method: "DELETE",
9103
+ headers: { Authorization: `Bearer ${accessToken}` }
9104
+ }).then((r) => r.ok || r.status === 404, () => false);
9105
+ if (!removed) problem(config, "An Outlook event was created but its id could not be saved or the event removed", { appointmentId });
9106
+ throw error;
9107
+ }
9108
+ }
9109
+ return created.id ?? appointment.outlookEventId ?? null;
9110
+ }
9111
+ async function deleteOutlookEvent(config, appointmentId) {
9112
+ const appointment = await config.db.appointment.findUnique({
9113
+ where: { id: appointmentId },
9114
+ select: { outlookEventId: true, calendarId: true, calendar: { select: { outlookCalendarId: true } }, type: { select: { slug: true } } }
9115
+ });
9116
+ if (!appointment?.outlookEventId || !appointment.calendar.outlookCalendarId) return;
9117
+ if (appointment.type.slug === BLOCKED_TYPE_SLUG) return;
9118
+ const accessToken = await getOutlookAccessToken(config, appointment.calendarId);
9119
+ if (!accessToken) return;
9120
+ const response = await (config.fetch ?? fetch)(
9121
+ `${GRAPH_BASE}/me/calendars/${encodeURIComponent(appointment.calendar.outlookCalendarId)}/events/${encodeURIComponent(appointment.outlookEventId)}`,
9122
+ { method: "DELETE", headers: { Authorization: `Bearer ${accessToken}` } }
9123
+ );
9124
+ if (!response.ok && response.status !== 404) throw new Error(`Outlook DELETE event failed with HTTP ${response.status}`);
9125
+ await config.db.appointment.update({ where: { id: appointmentId }, data: { outlookEventId: null } });
9126
+ }
9127
+
9128
+ // src/outlook-sync/outlook-pull.ts
9129
+ var MAX_PAGES = 200;
9130
+ var withZone = (dateTime) => dateTime.endsWith("Z") ? dateTime : `${dateTime}Z`;
9131
+ async function pullChangesFromOutlook(config, hooks, calendarId) {
9132
+ return pullOnce(config, hooks, calendarId, { isRestart: false, skipWindowCheck: false });
9133
+ }
9134
+ async function pullOnce(config, hooks, calendarId, mode) {
9135
+ const { isRestart } = mode;
9136
+ const { db } = config;
9137
+ const calendar = await db.schedulingCalendar.findUnique({ where: { id: calendarId } });
9138
+ if (!calendar?.outlookCalendarId) return { synced: 0 };
9139
+ const now = (config.now ?? (() => /* @__PURE__ */ new Date()))();
9140
+ const windowIsStale = calendar.lastSyncAt != null && calendar.lastSyncAt.getUTCMonth() !== now.getUTCMonth();
9141
+ if (calendar.outlookSyncToken && windowIsStale && !isRestart && !mode.skipWindowCheck) {
9142
+ if (!await getOutlookAccessToken(config, calendarId)) return { synced: 0 };
9143
+ const drained = await pullOnce(config, hooks, calendarId, { isRestart: false, skipWindowCheck: true });
9144
+ const fresh = await pullOnce(config, hooks, calendarId, { isRestart: true, skipWindowCheck: true, ignoreSavedLink: true });
9145
+ return { synced: drained.synced + fresh.synced };
9146
+ }
9147
+ const accessToken = await getOutlookAccessToken(config, calendarId);
9148
+ if (!accessToken) return { synced: 0 };
9149
+ const headers = { Authorization: `Bearer ${accessToken}`, Prefer: 'outlook.timezone="UTC"' };
9150
+ const horizon = new Date(now);
9151
+ horizon.setUTCFullYear(horizon.getUTCFullYear() + 1);
9152
+ const firstUrl = `${GRAPH_BASE}/me/calendars/${encodeURIComponent(calendar.outlookCalendarId)}/calendarView/delta?startDateTime=${now.toISOString()}&endDateTime=${horizon.toISOString()}`;
9153
+ let url = mode.ignoreSavedLink ? firstUrl : calendar.outlookSyncToken ?? firstUrl;
9154
+ let deltaLink = null;
9155
+ let synced = 0;
9156
+ let unhandled = null;
9157
+ let blockedType = null;
9158
+ for (let pageNumber = 0; url; pageNumber++) {
9159
+ if (pageNumber >= MAX_PAGES) throw new Error("Outlook delta query returned more pages than expected");
9160
+ if (!url.startsWith(`${GRAPH_BASE}/`)) throw new Error("Outlook delta link does not point at Microsoft Graph");
9161
+ const response = await (config.fetch ?? fetch)(url, { headers });
9162
+ if (response.status === 410) {
9163
+ if (isRestart) throw new Error("Outlook delta query was refused with HTTP 410 on a fresh start");
9164
+ problem(config, "Outlook delta link expired; starting a full sync", { calendarId });
9165
+ await db.schedulingCalendar.update({ where: { id: calendarId }, data: { outlookSyncToken: null } });
9166
+ return pullOnce(config, hooks, calendarId, { isRestart: true, skipWindowCheck: true });
9167
+ }
9168
+ if (!response.ok) throw new Error(`Outlook delta query failed with HTTP ${response.status}`);
9169
+ const page = await response.json();
9170
+ for (const event of page.value) {
9171
+ if (!event.id) continue;
9172
+ const existing = await db.appointment.findFirst({ where: { outlookEventId: event.id, calendarId } });
9173
+ if (event["@removed"]) {
9174
+ if (existing && existing.status !== "CANCELLED") {
9175
+ try {
9176
+ if (await hooks.cancelAppointment(existing.id)) synced++;
9177
+ else unhandled ??= new Error(`The host did not cancel appointment ${existing.id}`);
9178
+ } catch (error) {
9179
+ unhandled ??= error instanceof Error ? error : new Error(String(error));
9180
+ problem(config, "Cancelling an appointment deleted in Outlook failed", { appointmentId: existing.id, error: unhandled.message });
9181
+ }
9182
+ }
9183
+ continue;
9184
+ }
9185
+ if (!event.start?.dateTime || !event.end?.dateTime) continue;
9186
+ const startTime = new Date(withZone(event.start.dateTime));
9187
+ const endTime = new Date(withZone(event.end.dateTime));
9188
+ if (Number.isNaN(startTime.getTime()) || Number.isNaN(endTime.getTime()) || endTime <= startTime) continue;
9189
+ const duration = Math.round((endTime.getTime() - startTime.getTime()) / 6e4);
9190
+ if (existing) {
9191
+ if (existing.status === "CANCELLED") continue;
9192
+ const moved = existing.startTime.getTime() !== startTime.getTime() || existing.endTime.getTime() !== endTime.getTime();
9193
+ if (!moved) continue;
9194
+ try {
9195
+ await hooks.onAppointmentMoved?.({ appointmentId: existing.id, organizationId: calendar.organizationId, startTime, endTime });
9196
+ await db.appointment.update({ where: { id: existing.id }, data: { startTime, endTime, duration } });
9197
+ } catch (error) {
9198
+ unhandled ??= error instanceof Error ? error : new Error(String(error));
9199
+ problem(config, "Saving a time changed in Outlook failed", { appointmentId: existing.id, error: unhandled.message });
9200
+ continue;
9201
+ }
9202
+ synced++;
9203
+ continue;
9204
+ }
9205
+ blockedType ??= await findOrCreateBlockedType(config, calendar.organizationId);
9206
+ await db.appointment.create({
9207
+ data: {
9208
+ calendarId,
9209
+ typeId: blockedType.id,
9210
+ startTime,
9211
+ endTime,
9212
+ duration,
9213
+ timezone: calendar.timezone,
9214
+ status: "CONFIRMED",
9215
+ clientName: event.subject || "Blocked",
9216
+ clientEmail: "",
9217
+ outlookEventId: event.id
9218
+ }
8393
9219
  });
9220
+ synced++;
8394
9221
  }
9222
+ deltaLink = page["@odata.deltaLink"] ?? null;
9223
+ url = page["@odata.nextLink"] ?? "";
9224
+ }
9225
+ if (unhandled) throw unhandled;
9226
+ if (deltaLink) {
9227
+ const isDrain = mode.skipWindowCheck && !isRestart;
9228
+ await db.schedulingCalendar.update({
9229
+ where: { id: calendarId },
9230
+ data: isDrain ? { outlookSyncToken: deltaLink } : { outlookSyncToken: deltaLink, lastSyncAt: now }
9231
+ });
9232
+ }
9233
+ return { synced };
9234
+ }
9235
+ async function findOrCreateBlockedType(config, organizationId) {
9236
+ const find = () => config.db.appointmentType.findFirst({ where: { slug: BLOCKED_TYPE_SLUG, organizationId } });
9237
+ const found = await find();
9238
+ if (found) return found;
9239
+ try {
9240
+ return await config.db.appointmentType.create({
9241
+ data: {
9242
+ name: "Blocked",
9243
+ slug: BLOCKED_TYPE_SLUG,
9244
+ duration: 60,
9245
+ color: "#6B7280",
9246
+ isActive: false,
9247
+ // never offered for booking
9248
+ organizationId
9249
+ }
9250
+ });
9251
+ } catch (error) {
9252
+ const raced = await find();
9253
+ if (raced) return raced;
9254
+ throw error;
9255
+ }
9256
+ }
9257
+
9258
+ // src/outlook-sync/create-outlook-calendar-sync.ts
9259
+ function createOutlookCalendarSync(config, hooks) {
9260
+ return {
9261
+ adapter: {
9262
+ async upsertEvent(event) {
9263
+ const externalId = await pushAppointmentToOutlook(config, event.appointmentId);
9264
+ return externalId ? { externalId } : {};
9265
+ },
9266
+ async removeEvent(ref) {
9267
+ await deleteOutlookEvent(config, ref.appointmentId);
9268
+ }
9269
+ },
9270
+ pull: async (calendarId) => await pullChangesFromOutlook(config, hooks, calendarId)
8395
9271
  };
8396
9272
  }
8397
9273
 
@@ -8510,6 +9386,7 @@ function createNodeListener(api, options) {
8510
9386
  // Annotate the CommonJS export names for ESM import in node:
8511
9387
  0 && (module.exports = {
8512
9388
  ALL_REFUND_STATUSES,
9389
+ ApiKeySchema,
8513
9390
  BALANCE_APPOINTMENT_SELECT,
8514
9391
  BALANCE_BLOCKED_APPOINTMENT_STATUS,
8515
9392
  BALANCE_REQUIRED_PAYMENT_STATUS,
@@ -8546,9 +9423,12 @@ function createNodeListener(api, options) {
8546
9423
  RouteClientSchema,
8547
9424
  SLOT_GRANULARITY_DEFAULT,
8548
9425
  SLOT_GRANULARITY_OPTIONS,
9426
+ SmsSendError,
8549
9427
  TERMINAL_SUCCESS_STATUSES,
8550
9428
  TOKEN_TTL_DAYS,
9429
+ TelnyxSendError,
8551
9430
  TestRoutingFormSchema,
9431
+ TextSettingsSchema,
8552
9432
  UnverifiedPaymentError,
8553
9433
  UpdateAppointmentCategorySchema,
8554
9434
  UpdateAppointmentTypeSchema,
@@ -8561,9 +9441,12 @@ function createNodeListener(api, options) {
8561
9441
  UpdateServicePackageSchema,
8562
9442
  assertStripeTestKey,
8563
9443
  attemptLegRefund,
9444
+ bearerKeyOf,
8564
9445
  calendarVisibilityFilter,
8565
9446
  canSeeAppointmentInScope,
8566
9447
  canSeeCalendarInScope,
9448
+ checkSendingDomain,
9449
+ classifyReply,
8567
9450
  createBalanceIntent,
8568
9451
  createBearerStaffResolver,
8569
9452
  createMemoryAvailabilityCache,
@@ -8572,25 +9455,37 @@ function createNodeListener(api, options) {
8572
9455
  createNoBalancePaymentControl,
8573
9456
  createNoPaymentAdapter,
8574
9457
  createNodeListener,
9458
+ createOutlookCalendarSync,
9459
+ createPerBusinessSmsAdapter,
8575
9460
  createSchedulingApi,
8576
9461
  createScopedVisibility,
9462
+ createSendingDomainVerifier,
8577
9463
  createSingleOrganizationDirectory,
8578
9464
  createSingleOrganizationResolver,
8579
9465
  createStaffContext,
8580
9466
  createStripePaymentAdapter,
9467
+ createTelnyxSmsAdapter,
9468
+ createTextSettingsResolver,
9469
+ createTwilioSmsAdapter,
8581
9470
  decimalToCents,
8582
9471
  defaultCorsHeaders,
8583
9472
  getErrorCode,
8584
9473
  getErrorMessage,
8585
9474
  getErrorRef,
9475
+ handleTelnyxWebhook,
9476
+ handleTwilioWebhook,
8586
9477
  isCalendarVisibleInScope,
8587
9478
  isSchedulingServiceError,
8588
9479
  isSupportedCurrency,
8589
9480
  isTokenExpired,
9481
+ normalizePhoneNumber,
9482
+ normalizeSendingDomain,
8590
9483
  parsePagination,
8591
9484
  persistRefundOutcome,
8592
9485
  recordBalanceIntent,
8593
9486
  runCalendarRemoveWithoutBlocking,
8594
9487
  runCalendarSyncWithoutBlocking,
9488
+ verifyTelnyxSignature,
9489
+ verifyTwilioSignature,
8595
9490
  visibleCalendarIdsInScope
8596
9491
  });