@ordinatio/scheduling 0.2.1 → 0.4.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
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,21 +17,45 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
 
20
30
  // src/index.ts
21
31
  var index_exports = {};
22
32
  __export(index_exports, {
33
+ BRAND_FIELDS: () => BRAND_FIELDS,
34
+ BlockedTargetError: () => BlockedTargetError,
35
+ DEFAULT_BACKOFF_SECONDS: () => DEFAULT_BACKOFF_SECONDS,
36
+ DEFAULT_OFFER_MINUTES: () => DEFAULT_OFFER_MINUTES,
37
+ ERASED_EMAIL: () => ERASED_EMAIL,
38
+ ERASED_NAME: () => ERASED_NAME,
39
+ MAX_ENDPOINTS_PER_ORGANIZATION: () => MAX_ENDPOINTS_PER_ORGANIZATION,
40
+ MAX_WAITING_PER_TYPE_DAY: () => MAX_WAITING_PER_TYPE_DAY,
41
+ OPERATORS_BY_TYPE: () => OPERATORS_BY_TYPE,
23
42
  RECURRING_MAX_OCCURRENCES: () => RECURRING_MAX_OCCURRENCES,
43
+ ROUTING_LIMITS: () => LIMITS,
24
44
  SCHEDULING_ERRORS: () => SCHEDULING_ERRORS,
45
+ SIGNATURE_HEADER: () => SIGNATURE_HEADER,
25
46
  SchedulingNotFoundError: () => SchedulingNotFoundError,
26
47
  SchedulingValidationError: () => SchedulingValidationError,
27
48
  USER_DAY_LIMIT: () => USER_DAY_LIMIT,
49
+ WEBHOOK_EVENT_TYPES: () => WEBHOOK_EVENT_TYPES,
50
+ WEBHOOK_TEST_EVENT: () => WEBHOOK_TEST_EVENT,
28
51
  adaptersToCallbacks: () => adaptersToCallbacks,
29
52
  addDateOverride: () => addDateOverride,
30
53
  addTimeBlock: () => addTimeBlock,
54
+ appointmentWebhookData: () => appointmentWebhookData,
31
55
  archiveCalendar: () => archiveCalendar,
56
+ beginWaitlistAccept: () => beginWaitlistAccept,
32
57
  bookAppointment: () => bookAppointment,
58
+ brandTemplateFields: () => brandTemplateFields,
33
59
  buildJitsiUrl: () => buildJitsiUrl,
34
60
  buildNotificationContext: () => buildNotificationContext,
35
61
  buildOccurrenceStartTime: () => buildOccurrenceStartTime,
@@ -37,18 +63,35 @@ __export(index_exports, {
37
63
  calculateCancellationFee: () => calculateCancellationFee,
38
64
  cancelAppointment: () => cancelAppointment,
39
65
  cancelPendingNotifications: () => cancelPendingNotifications,
66
+ checkAnswers: () => checkAnswers,
40
67
  checkAuthContract: () => checkAuthContract,
41
68
  checkCalendarSyncContract: () => checkCalendarSyncContract,
42
69
  checkClockContract: () => checkClockContract,
43
70
  checkNotificationContract: () => checkNotificationContract,
44
71
  checkPaymentContract: () => checkPaymentContract,
72
+ checkWebhookUrl: () => checkWebhookUrl,
73
+ completeWaitlistAccept: () => completeWaitlistAccept,
45
74
  createAppointmentType: () => createAppointmentType,
46
75
  createCalendar: () => createCalendar,
47
76
  createInMemoryAdapters: () => createInMemoryAdapters,
77
+ createNodeTransport: () => createNodeTransport,
48
78
  createNotificationTemplate: () => createNotificationTemplate,
79
+ createRoutingForm: () => createRoutingForm,
80
+ createWebhookEndpoint: () => createWebhookEndpoint,
81
+ deleteBrand: () => deleteBrand,
49
82
  deleteCalendar: () => deleteCalendar,
50
83
  deleteNotificationTemplate: () => deleteNotificationTemplate,
84
+ deleteRoutingForm: () => deleteRoutingForm,
85
+ deleteWebhookEndpoint: () => deleteWebhookEndpoint,
86
+ deliverDueWebhooks: () => deliverDueWebhooks,
87
+ enqueueAppointmentWebhook: () => enqueueAppointmentWebhook,
88
+ enqueueReminderSent: () => enqueueReminderSent,
89
+ enqueueWebhookEvent: () => enqueueWebhookEvent,
90
+ eraseSubject: () => eraseSubject,
91
+ expireWaitlistOffers: () => expireWaitlistOffers,
92
+ exportSubject: () => exportSubject,
51
93
  generateOccurrenceDates: () => generateOccurrenceDates,
94
+ generateWebhookSecret: () => generateWebhookSecret,
52
95
  getAppointment: () => getAppointment,
53
96
  getAppointmentDashboard: () => getAppointmentDashboard,
54
97
  getAppointmentType: () => getAppointmentType,
@@ -56,36 +99,74 @@ __export(index_exports, {
56
99
  getAvailableDates: () => getAvailableDates,
57
100
  getAvailableSlots: () => getAvailableSlots,
58
101
  getBookingAnalytics: () => getBookingAnalytics,
102
+ getBrand: () => getBrand,
59
103
  getCalendar: () => getCalendar,
60
104
  getGroupCapacity: () => getGroupCapacity,
61
105
  getGroupSessions: () => getGroupSessions,
62
106
  getNotificationTemplate: () => getNotificationTemplate,
107
+ getPublicBrand: () => getPublicBrand,
108
+ getPublicRoutingForm: () => getPublicRoutingForm,
109
+ getRoutingForm: () => getRoutingForm,
63
110
  getTeamAvailableSlots: () => getTeamAvailableSlots,
64
111
  getUserDayAppointments: () => getUserDayAppointments,
112
+ getWaitlistOffer: () => getWaitlistOffer,
113
+ isPrivateAddress: () => isPrivateAddress,
65
114
  isSlotAvailable: () => isSlotAvailable,
66
115
  isVirtualMeeting: () => isVirtualMeeting,
116
+ joinWaitlist: () => joinWaitlist,
117
+ leaveWaitlist: () => leaveWaitlist,
67
118
  listAppointmentTypes: () => listAppointmentTypes,
68
119
  listAppointments: () => listAppointments,
69
120
  listAvailabilityRules: () => listAvailabilityRules,
70
121
  listCalendars: () => listCalendars,
71
122
  listNotificationTemplates: () => listNotificationTemplates,
123
+ listPrivacyRequests: () => listPrivacyRequests,
124
+ listRoutingForms: () => listRoutingForms,
125
+ listWaitlist: () => listWaitlist,
126
+ listWebhookDeliveries: () => listWebhookDeliveries,
127
+ listWebhookEndpoints: () => listWebhookEndpoints,
128
+ localDay: () => localDay,
72
129
  localToUTC: () => localToUTC,
73
130
  markNoShow: () => markNoShow,
131
+ matchingRules: () => matchingRules,
132
+ offerFreedSlot: () => offerFreedSlot,
133
+ parseSubject: () => parseSubject,
74
134
  parseTimeLocal: () => parseTimeLocal,
135
+ previewErase: () => previewErase,
75
136
  processPendingNotifications: () => processPendingNotifications,
76
137
  queueImmediateNotification: () => queueImmediateNotification,
77
138
  queueStaffNotification: () => queueStaffNotification,
139
+ releaseWaitlistAccept: () => releaseWaitlistAccept,
78
140
  removeDateOverride: () => removeDateOverride,
141
+ removeWaitlistEntry: () => removeWaitlistEntry,
79
142
  renderTemplate: () => renderTemplate,
80
143
  rescheduleAppointment: () => rescheduleAppointment,
144
+ resolveDestination: () => resolveDestination,
81
145
  resolveLocation: () => resolveLocation,
146
+ resolveSubject: () => resolveSubject,
147
+ retryWebhookDelivery: () => retryWebhookDelivery,
148
+ routeClient: () => routeClient,
149
+ saveBrand: () => saveBrand,
82
150
  schedError: () => schedError,
83
151
  scheduleNotifications: () => scheduleNotifications,
84
152
  selectCalendarForBooking: () => selectCalendarForBooking,
153
+ sendTestWebhook: () => sendTestWebhook,
154
+ senderIdentity: () => senderIdentity,
85
155
  setWeeklyAvailability: () => setWeeklyAvailability,
156
+ settleBookedAccept: () => settleBookedAccept,
157
+ signWebhook: () => signWebhook,
158
+ subjectHashes: () => subjectHashes,
159
+ testRoutingForm: () => testRoutingForm,
160
+ toPublicBrand: () => toPublicBrand,
161
+ tryOfferFreedSlot: () => tryOfferFreedSlot,
86
162
  updateAppointmentType: () => updateAppointmentType,
87
163
  updateCalendar: () => updateCalendar,
88
164
  updateNotificationTemplate: () => updateNotificationTemplate,
165
+ updateRoutingForm: () => updateRoutingForm,
166
+ validateBrand: () => validateBrand,
167
+ validateRoutingDestinations: () => validateRoutingDestinations,
168
+ validateRoutingStructure: () => validateRoutingStructure,
169
+ verifyWebhookSignature: () => verifyWebhookSignature,
89
170
  withCalendarVisibility: () => withCalendarVisibility
90
171
  });
91
172
  module.exports = __toCommonJS(index_exports);
@@ -994,6 +1075,239 @@ var GROUP_SCOPE_ERRORS = {
994
1075
  }
995
1076
  };
996
1077
 
1078
+ // src/errors/registry-webhooks.ts
1079
+ var WEBHOOK_ERRORS = {
1080
+ SCHED_1000: {
1081
+ code: "SCHED_1000",
1082
+ file: "webhooks/endpoints.ts",
1083
+ function: "createWebhookEndpoint",
1084
+ severity: "warning",
1085
+ recoverable: true,
1086
+ description: "The webhook address is not allowed",
1087
+ diagnosis: [
1088
+ "The address must be a full https:// address with no user name or password",
1089
+ "Addresses that point at this machine or a private network are refused",
1090
+ "For local development only, the host can allow insecure targets"
1091
+ ]
1092
+ },
1093
+ SCHED_1001: {
1094
+ code: "SCHED_1001",
1095
+ file: "webhooks/endpoints.ts",
1096
+ function: "createWebhookEndpoint",
1097
+ severity: "warning",
1098
+ recoverable: true,
1099
+ description: "The webhook event list is empty or names an event that does not exist",
1100
+ diagnosis: [
1101
+ 'Send at least one event name, or "*" for every event',
1102
+ "Valid names: appointment.booked, appointment.rescheduled, appointment.cancelled, appointment.no_show, reminder.sent, waitlist.offered"
1103
+ ]
1104
+ },
1105
+ SCHED_1002: {
1106
+ code: "SCHED_1002",
1107
+ file: "webhooks/endpoints.ts",
1108
+ function: "createWebhookEndpoint",
1109
+ severity: "warning",
1110
+ recoverable: true,
1111
+ description: "The organization already has the maximum number of webhook endpoints",
1112
+ diagnosis: ["Remove an endpoint that is no longer used, then add the new one"]
1113
+ },
1114
+ SCHED_1003: {
1115
+ code: "SCHED_1003",
1116
+ file: "webhooks/endpoints.ts",
1117
+ function: "webhook endpoint lookup",
1118
+ severity: "warning",
1119
+ recoverable: true,
1120
+ description: "Webhook endpoint not found for this organization",
1121
+ diagnosis: [
1122
+ "Check the endpoint id",
1123
+ "The endpoint may belong to another organization or may have been removed"
1124
+ ]
1125
+ },
1126
+ SCHED_1004: {
1127
+ code: "SCHED_1004",
1128
+ file: "webhooks/deliveries.ts",
1129
+ function: "retryWebhookDelivery",
1130
+ severity: "warning",
1131
+ recoverable: true,
1132
+ description: "Webhook delivery not found, or it is not in the dead-letter list",
1133
+ diagnosis: [
1134
+ "Only a delivery that ran out of tries can be retried by hand",
1135
+ "A delivery still waiting for its next try will be sent on its own"
1136
+ ]
1137
+ },
1138
+ SCHED_1005: {
1139
+ code: "SCHED_1005",
1140
+ file: "webhooks/attempt.ts",
1141
+ function: "attemptDelivery",
1142
+ severity: "warning",
1143
+ recoverable: false,
1144
+ description: "The webhook was not sent because its target is not allowed",
1145
+ diagnosis: [
1146
+ "The address, or the address its name resolves to, is on a private or local network",
1147
+ "Remove the endpoint and add one that points at a public address"
1148
+ ]
1149
+ },
1150
+ SCHED_1006: {
1151
+ code: "SCHED_1006",
1152
+ file: "webhooks/enqueue.ts",
1153
+ function: "enqueueWebhookEvent",
1154
+ severity: "error",
1155
+ recoverable: true,
1156
+ description: "A webhook event could not be queued; the booking itself was saved",
1157
+ diagnosis: [
1158
+ "Check that the webhook tables exist (run the package migrations)",
1159
+ "Check the database connection"
1160
+ ]
1161
+ }
1162
+ };
1163
+
1164
+ // src/errors/registry-waitlist.ts
1165
+ function entry(code, fn, description, diagnosis, severity = "warning", recoverable = true) {
1166
+ return { code, file: "waitlist/", function: fn, severity, recoverable, description, diagnosis };
1167
+ }
1168
+ var WAITLIST_ERRORS = {
1169
+ SCHED_1100: entry(
1170
+ "SCHED_1100",
1171
+ "joinWaitlist",
1172
+ "The appointment type or calendar for this waitlist request was not found",
1173
+ ["Check the type id and, if given, the calendar id", "The calendar must be one that offers the type", "An inactive type has no waitlist"]
1174
+ ),
1175
+ SCHED_1101: entry(
1176
+ "SCHED_1101",
1177
+ "joinWaitlist",
1178
+ "The waitlist day is invalid, in the past, or too far ahead",
1179
+ ["Send the day as YYYY-MM-DD", "The day must be today or later, and within the next 90 days"]
1180
+ ),
1181
+ SCHED_1102: entry(
1182
+ "SCHED_1102",
1183
+ "joinWaitlist",
1184
+ "The waitlist time is invalid or not on the chosen day",
1185
+ ["Send the time as an ISO date-time on the chosen day, in the future"]
1186
+ ),
1187
+ SCHED_1103: entry(
1188
+ "SCHED_1103",
1189
+ "joinWaitlist",
1190
+ "That time or day still has open slots, so the client should book instead of waiting",
1191
+ ["Look up the open slots for the day", "Join the waitlist only for a slot or day that is full"]
1192
+ ),
1193
+ SCHED_1104: entry(
1194
+ "SCHED_1104",
1195
+ "joinWaitlist",
1196
+ "This email is already waiting for that day",
1197
+ ["The client is already on the list for this type and day", "They can leave with their link and join again"]
1198
+ ),
1199
+ SCHED_1105: entry(
1200
+ "SCHED_1105",
1201
+ "joinWaitlist",
1202
+ "A waitlist is not available for a type that needs payment",
1203
+ ["Payment cannot be taken when an offer is accepted", "Use a free type, or let clients book as slots open"]
1204
+ ),
1205
+ SCHED_1106: entry(
1206
+ "SCHED_1106",
1207
+ "getWaitlistOffer",
1208
+ "No open offer for this link",
1209
+ ["The link may be wrong, already used, or the entry may have left the list", "An offer can be accepted once"]
1210
+ ),
1211
+ SCHED_1107: entry(
1212
+ "SCHED_1107",
1213
+ "beginWaitlistAccept",
1214
+ "The offer has expired",
1215
+ ["The time limit ran out; the slot may have gone to the next person", "Join the waitlist again to wait for another slot"]
1216
+ ),
1217
+ SCHED_1108: entry(
1218
+ "SCHED_1108",
1219
+ "joinWaitlist",
1220
+ "The waitlist for that day is full",
1221
+ ["Too many people are already waiting for this type and day"]
1222
+ ),
1223
+ SCHED_1109: entry(
1224
+ "SCHED_1109",
1225
+ "offerFreedSlot",
1226
+ "A waitlist offer could not be made; the cancellation itself was saved",
1227
+ ["Check that the waitlist table exists (run the package migrations)", "Check the database connection"],
1228
+ "error"
1229
+ ),
1230
+ SCHED_1110: entry(
1231
+ "SCHED_1110",
1232
+ "joinWaitlist",
1233
+ "A waitlist is not available for a type with required intake questions",
1234
+ ["An accepted offer books without form answers, so the required questions could not be answered", "Make the questions optional, or let clients book as slots open"]
1235
+ )
1236
+ };
1237
+
1238
+ // src/errors/registry-routing.ts
1239
+ function entry2(code, fn, description, diagnosis, severity = "warning") {
1240
+ return { code, file: "routing/", function: fn, severity, recoverable: true, description, diagnosis };
1241
+ }
1242
+ var ROUTING_ERRORS = {
1243
+ SCHED_1200: entry2(
1244
+ "SCHED_1200",
1245
+ "validateRoutingForm",
1246
+ "The routing form is not valid",
1247
+ ["Read the list of problems in the error context: each names the part of the form and what is wrong", "Every rule must name questions that exist, use an operator that fits the question, and send the client somewhere that is live"]
1248
+ ),
1249
+ SCHED_1201: entry2(
1250
+ "SCHED_1201",
1251
+ "routing form lookup",
1252
+ "The routing form was not found (for the public: no active form with that slug)",
1253
+ ["Check the form address (slug)", "A form that is switched off, or that belongs to another organization, is not found", "With several organizations in one database, name the organization"]
1254
+ ),
1255
+ SCHED_1202: entry2(
1256
+ "SCHED_1202",
1257
+ "createRoutingForm / updateRoutingForm",
1258
+ "Another routing form already uses that slug",
1259
+ ["Choose a different slug", "A slug is unique within the organization and must not be used by another organization in the same database"]
1260
+ ),
1261
+ SCHED_1203: entry2(
1262
+ "SCHED_1203",
1263
+ "routeClient",
1264
+ "The answers do not fit the form",
1265
+ ["Answer every required question", "Pick an offered option for choice questions, and send a list for checkbox questions", "Send only questions the form asks"]
1266
+ ),
1267
+ SCHED_1204: entry2(
1268
+ "SCHED_1204",
1269
+ "createRoutingForm",
1270
+ "The organization already has the maximum number of routing forms",
1271
+ ["Remove a form that is no longer used, then add the new one"]
1272
+ )
1273
+ };
1274
+
1275
+ // src/errors/registry-privacy.ts
1276
+ function entry3(code, fn, description, diagnosis) {
1277
+ return { code, file: "privacy/", function: fn, severity: "warning", recoverable: true, description, diagnosis };
1278
+ }
1279
+ var PRIVACY_ERRORS = {
1280
+ SCHED_1300: entry3(
1281
+ "SCHED_1300",
1282
+ "parseSubject",
1283
+ "Say whose data this is: a valid email address, a client id, or both",
1284
+ ["Send `email` (one address) and/or `clientId`", "An address must be a single address with no spaces, at most 254 characters"]
1285
+ ),
1286
+ SCHED_1301: entry3(
1287
+ "SCHED_1301",
1288
+ "eraseSubject",
1289
+ "This person still has upcoming bookings or an open waitlist offer, so their data cannot be erased yet",
1290
+ ["Cancel or complete the upcoming bookings, and remove the waitlist entries that hold or are taking an offer", "Run the erase preview to see how many of each remain", "Then ask again"]
1291
+ )
1292
+ };
1293
+
1294
+ // src/errors/registry-brand.ts
1295
+ var BRAND_ERRORS = {
1296
+ SCHED_1400: {
1297
+ code: "SCHED_1400",
1298
+ file: "brand/",
1299
+ function: "validateBrand",
1300
+ severity: "warning",
1301
+ recoverable: true,
1302
+ description: "The brand settings are not valid",
1303
+ diagnosis: [
1304
+ "Read the list of problems in the error context: each names the field and what is wrong",
1305
+ "Colours are hex values such as #1a2b3c; the logo is an https address; email addresses are single plain addresses",
1306
+ "A sending address is accepted only for a domain the host has confirmed it may send from"
1307
+ ]
1308
+ }
1309
+ };
1310
+
997
1311
  // src/errors/registry.ts
998
1312
  var SCHEDULING_ERRORS = {
999
1313
  ...CALENDARS_AVAILABILITY_ERRORS,
@@ -1003,7 +1317,12 @@ var SCHEDULING_ERRORS = {
1003
1317
  ...NOTIFICATION_MANAGE_ERRORS,
1004
1318
  ...RECURRING_MISC_ERRORS,
1005
1319
  ...PUBLIC_DIRECTORY_ERRORS,
1006
- ...GROUP_SCOPE_ERRORS
1320
+ ...GROUP_SCOPE_ERRORS,
1321
+ ...WEBHOOK_ERRORS,
1322
+ ...WAITLIST_ERRORS,
1323
+ ...ROUTING_ERRORS,
1324
+ ...PRIVACY_ERRORS,
1325
+ ...BRAND_ERRORS
1007
1326
  };
1008
1327
 
1009
1328
  // src/errors/diagnostic-error.ts
@@ -2093,9 +2412,7 @@ async function bookAppointment(db, input, callbacks) {
2093
2412
  clientName: input.clientName,
2094
2413
  clientEmail: input.clientEmail,
2095
2414
  clientPhone: input.clientPhone ?? null,
2096
- // ALFRED-246 (system-1701's .autocode/modules/alfred/debt.md): the public booking
2097
- // route passes this through from caller-supplied, unauthenticated input with no
2098
- // existence/ownership check — a real, disclosed, not-yet-fixed gap.
2415
+ // Not verified here: a caller that takes this from unauthenticated input must check it first.
2099
2416
  clientId: input.clientId ?? null,
2100
2417
  intakeResponses: input.intakeResponses,
2101
2418
  staffNotes: input.staffNotes ?? null,
@@ -2198,13 +2515,13 @@ function renderTemplate(template, context, channel = "EMAIL") {
2198
2515
  for (const [key, value] of Object.entries(context)) {
2199
2516
  if (typeof value === "string") {
2200
2517
  const safeValue = channel === "SMS" ? value : escapeHtml(value);
2201
- result = result.replace(new RegExp(`\\{\\{${key}\\}\\}`, "g"), safeValue);
2518
+ result = result.replace(new RegExp(`\\{\\{${key}\\}\\}`, "g"), () => safeValue);
2202
2519
  }
2203
2520
  }
2204
2521
  if (context.customFields) {
2205
2522
  for (const [key, value] of Object.entries(context.customFields)) {
2206
2523
  const safeValue = channel === "SMS" ? value : escapeHtml(value);
2207
- result = result.replace(new RegExp(`\\{\\{${key}\\}\\}`, "g"), safeValue);
2524
+ result = result.replace(new RegExp(`\\{\\{${key}\\}\\}`, "g"), () => safeValue);
2208
2525
  }
2209
2526
  }
2210
2527
  if (channel === "SMS") {
@@ -2257,9 +2574,320 @@ function buildNotificationContext(appointment, baseUrl) {
2257
2574
  };
2258
2575
  }
2259
2576
 
2577
+ // src/brand/sender.ts
2578
+ var NOT_IN_A_SENDER_NAME = /[<>",;@\\]/g;
2579
+ function senderIdentity(brand) {
2580
+ if (!brand) return null;
2581
+ const fallbackName = brand.displayName.replace(/[\u0000-\u001f\u007f]/g, " ").replace(NOT_IN_A_SENDER_NAME, "").replace(/\s+/g, " ").trim();
2582
+ const name = brand.fromName ?? (fallbackName || void 0);
2583
+ return {
2584
+ ...name ? { name } : {},
2585
+ ...brand.fromEmail ? { email: brand.fromEmail } : {},
2586
+ ...brand.replyToEmail ? { replyTo: brand.replyToEmail } : {}
2587
+ };
2588
+ }
2589
+ function brandTemplateFields(brand) {
2590
+ return {
2591
+ brandName: brand?.displayName ?? "",
2592
+ brandLogoUrl: brand?.logoUrl ?? "",
2593
+ brandColor: brand?.primaryColor ?? "",
2594
+ brandFooter: brand?.footerText ?? ""
2595
+ };
2596
+ }
2597
+ function toPublicBrand(brand) {
2598
+ return {
2599
+ displayName: brand.displayName,
2600
+ logoUrl: brand.logoUrl,
2601
+ primaryColor: brand.primaryColor,
2602
+ accentColor: brand.accentColor,
2603
+ backgroundColor: brand.backgroundColor,
2604
+ textColor: brand.textColor,
2605
+ fontFamily: brand.fontFamily,
2606
+ footerText: brand.footerText
2607
+ };
2608
+ }
2609
+
2610
+ // src/brand/types.ts
2611
+ var BRAND_FIELDS = [
2612
+ "displayName",
2613
+ "logoUrl",
2614
+ "primaryColor",
2615
+ "accentColor",
2616
+ "backgroundColor",
2617
+ "textColor",
2618
+ "fontFamily",
2619
+ "footerText",
2620
+ "replyToEmail",
2621
+ "fromName",
2622
+ "fromEmail"
2623
+ ];
2624
+
2625
+ // src/brand/validate.ts
2626
+ var HEX = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;
2627
+ var FONT = /^[A-Za-z0-9 ,-]{1,100}$/;
2628
+ var EMAIL = /^[^\s@<>,;"'()[\]\\]+@[^\s@<>,;"'()[\]\\]+\.[^\s@<>,;"'()[\]\\]+$/;
2629
+ var CONTROL = /[\u0000-\u001f\u007f]/;
2630
+ var COLOR_FIELDS = ["primaryColor", "accentColor", "backgroundColor", "textColor"];
2631
+ function text(value, path, max, problems, required = false) {
2632
+ if (value === void 0 || value === null || value === "") {
2633
+ if (required) problems.push({ path, message: "Required" });
2634
+ return null;
2635
+ }
2636
+ if (typeof value !== "string") {
2637
+ problems.push({ path, message: "Must be text" });
2638
+ return null;
2639
+ }
2640
+ const trimmed = value.trim();
2641
+ if (trimmed.length === 0) {
2642
+ if (required) problems.push({ path, message: "Required" });
2643
+ return null;
2644
+ }
2645
+ if (trimmed.length > max) problems.push({ path, message: `At most ${max} characters` });
2646
+ else if (CONTROL.test(trimmed)) problems.push({ path, message: "Must not contain control characters" });
2647
+ else return trimmed;
2648
+ return null;
2649
+ }
2650
+ function email(value, path, problems) {
2651
+ const raw = text(value, path, 254, problems);
2652
+ if (raw === null) return null;
2653
+ if (!EMAIL.test(raw)) {
2654
+ problems.push({ path, message: "Must be a single email address" });
2655
+ return null;
2656
+ }
2657
+ return raw.toLowerCase();
2658
+ }
2659
+ function logo(value, problems) {
2660
+ const raw = text(value, "logoUrl", 500, problems);
2661
+ if (raw === null) return null;
2662
+ try {
2663
+ const url = new URL(raw);
2664
+ if (url.protocol === "https:" && !url.username && !url.password && url.hostname) return raw;
2665
+ } catch {
2666
+ }
2667
+ problems.push({ path: "logoUrl", message: "Must be an https address without a user name or password" });
2668
+ return null;
2669
+ }
2670
+ async function validateBrand(input, options) {
2671
+ const problems = [];
2672
+ if (typeof input !== "object" || input === null || Array.isArray(input)) {
2673
+ throw new SchedulingValidationError("The brand settings are not valid", "SCHED_1400", { errors: [{ path: "", message: "Must be an object" }] });
2674
+ }
2675
+ const given = input;
2676
+ for (const key of Object.keys(given)) if (!BRAND_FIELDS.includes(key)) problems.push({ path: key, message: "Unknown field" });
2677
+ const out = {
2678
+ displayName: text(given.displayName, "displayName", 100, problems, true) ?? "",
2679
+ logoUrl: logo(given.logoUrl, problems),
2680
+ primaryColor: null,
2681
+ accentColor: null,
2682
+ backgroundColor: null,
2683
+ textColor: null,
2684
+ fontFamily: null,
2685
+ footerText: text(given.footerText, "footerText", 300, problems),
2686
+ replyToEmail: email(given.replyToEmail, "replyToEmail", problems),
2687
+ fromName: text(given.fromName, "fromName", 100, problems),
2688
+ fromEmail: email(given.fromEmail, "fromEmail", problems)
2689
+ };
2690
+ for (const field of COLOR_FIELDS) {
2691
+ const raw = text(given[field], field, 7, problems);
2692
+ if (raw === null) continue;
2693
+ if (HEX.test(raw)) out[field] = raw.toLowerCase();
2694
+ else problems.push({ path: field, message: "Must be a hex colour such as #1a2b3c" });
2695
+ }
2696
+ const font = text(given.fontFamily, "fontFamily", 100, problems);
2697
+ if (font !== null) {
2698
+ if (FONT.test(font)) out.fontFamily = font;
2699
+ else problems.push({ path: "fontFamily", message: "Letters, digits, spaces, commas and dashes only" });
2700
+ }
2701
+ if (out.fromName !== null && /[<>",;@\\]/.test(out.fromName)) {
2702
+ problems.push({ path: "fromName", message: "Must not contain quotes, angle brackets, commas, semicolons, @ or backslashes" });
2703
+ out.fromName = null;
2704
+ }
2705
+ if (out.fromEmail !== null && !problems.some((p) => p.path === "fromEmail")) {
2706
+ const domain = out.fromEmail.slice(out.fromEmail.lastIndexOf("@") + 1);
2707
+ let verified = false;
2708
+ try {
2709
+ verified = options.isSendingDomainVerified ? await options.isSendingDomainVerified(domain) : false;
2710
+ } catch (error) {
2711
+ console.error("[brand] the sending-domain check failed:", error);
2712
+ verified = false;
2713
+ }
2714
+ if (!verified) problems.push({ path: "fromEmail", message: `Sending from ${domain} is not confirmed for this server` });
2715
+ }
2716
+ if (problems.length > 0) throw new SchedulingValidationError("The brand settings are not valid", "SCHED_1400", { errors: problems });
2717
+ return out;
2718
+ }
2719
+
2720
+ // src/brand/crud.ts
2721
+ var SELECT = {
2722
+ displayName: true,
2723
+ logoUrl: true,
2724
+ primaryColor: true,
2725
+ accentColor: true,
2726
+ backgroundColor: true,
2727
+ textColor: true,
2728
+ fontFamily: true,
2729
+ footerText: true,
2730
+ replyToEmail: true,
2731
+ fromName: true,
2732
+ fromEmail: true,
2733
+ updatedAt: true
2734
+ };
2735
+ async function getBrand(db, organizationId) {
2736
+ return db.organizationBrand.findUnique({ where: { organizationId }, select: SELECT });
2737
+ }
2738
+ async function getPublicBrand(db, organizationId) {
2739
+ if (organizationId) {
2740
+ const brand = await getBrand(db, organizationId);
2741
+ return brand ? toPublicBrand(brand) : null;
2742
+ }
2743
+ const all = await db.organizationBrand.findMany({ take: 2, select: SELECT });
2744
+ return all.length === 1 ? toPublicBrand(all[0]) : null;
2745
+ }
2746
+ async function saveBrand(db, organizationId, input, options) {
2747
+ const fields = await validateBrand(input, options);
2748
+ return db.organizationBrand.upsert({
2749
+ where: { organizationId },
2750
+ create: { organizationId, ...fields },
2751
+ update: { ...fields },
2752
+ select: SELECT
2753
+ });
2754
+ }
2755
+ async function deleteBrand(db, organizationId) {
2756
+ const { count } = await db.organizationBrand.deleteMany({ where: { organizationId } });
2757
+ return count > 0;
2758
+ }
2759
+
2760
+ // src/notifications/brand-context.ts
2761
+ async function withBrandFields(db, organizationId, context, enabled) {
2762
+ if (!enabled) return context;
2763
+ const brand = organizationId ? await getBrand(db, organizationId) : null;
2764
+ return { ...context, customFields: { ...context.customFields, ...brandTemplateFields(brand) } };
2765
+ }
2766
+
2260
2767
  // src/notifications/process-pending-notifications.ts
2261
2768
  var import_crypto = require("crypto");
2262
2769
  var import_client6 = require("@prisma/client");
2770
+
2771
+ // src/webhooks/events.ts
2772
+ var import_node_crypto = require("crypto");
2773
+ var WEBHOOK_EVENT_TYPES = [
2774
+ "appointment.booked",
2775
+ "appointment.rescheduled",
2776
+ "appointment.cancelled",
2777
+ "appointment.no_show",
2778
+ "reminder.sent",
2779
+ "waitlist.offered"
2780
+ ];
2781
+ var WEBHOOK_TEST_EVENT = "webhook.test";
2782
+ var ALL_EVENTS = "*";
2783
+ function isWebhookEventType(value) {
2784
+ return typeof value === "string" && WEBHOOK_EVENT_TYPES.includes(value);
2785
+ }
2786
+ function normalizeEventTypes(input) {
2787
+ if (!Array.isArray(input) || input.length === 0) return null;
2788
+ if (input.includes(ALL_EVENTS)) return input.length === 1 ? [ALL_EVENTS] : null;
2789
+ if (!input.every(isWebhookEventType)) return null;
2790
+ return [...new Set(input)];
2791
+ }
2792
+ function buildEnvelope(args) {
2793
+ return {
2794
+ id: args.eventId ?? `evt_${(0, import_node_crypto.randomUUID)()}`,
2795
+ type: args.type,
2796
+ createdAt: args.now.toISOString(),
2797
+ organizationId: args.organizationId,
2798
+ data: args.data
2799
+ };
2800
+ }
2801
+
2802
+ // src/webhooks/enqueue.ts
2803
+ async function appointmentWebhookData(db, organizationId, appointmentId) {
2804
+ const row = await db.appointment.findUnique({
2805
+ where: { id: appointmentId },
2806
+ select: {
2807
+ id: true,
2808
+ status: true,
2809
+ startTime: true,
2810
+ endTime: true,
2811
+ duration: true,
2812
+ timezone: true,
2813
+ clientName: true,
2814
+ clientEmail: true,
2815
+ clientPhone: true,
2816
+ clientId: true,
2817
+ cancelledAt: true,
2818
+ cancelledBy: true,
2819
+ cancelReason: true,
2820
+ rescheduledFrom: true,
2821
+ rescheduleCount: true,
2822
+ calendarId: true,
2823
+ typeId: true,
2824
+ calendar: { select: { name: true, organizationId: true } },
2825
+ type: { select: { name: true } }
2826
+ }
2827
+ });
2828
+ if (!row || row.calendar.organizationId !== null && row.calendar.organizationId !== organizationId) {
2829
+ return { appointment: { id: appointmentId } };
2830
+ }
2831
+ const { calendar, type, ...rest } = row;
2832
+ return { appointment: { ...rest, calendarName: calendar.name, typeName: type.name } };
2833
+ }
2834
+ async function enqueueWebhookEvent(db, input) {
2835
+ const now = input.now ?? /* @__PURE__ */ new Date();
2836
+ const endpoints = await db.webhookEndpoint.findMany({
2837
+ where: {
2838
+ organizationId: input.organizationId,
2839
+ isActive: true,
2840
+ OR: [{ eventTypes: { has: input.type } }, { eventTypes: { has: ALL_EVENTS } }]
2841
+ },
2842
+ select: { id: true }
2843
+ });
2844
+ if (endpoints.length === 0) return { queued: 0 };
2845
+ const envelope = buildEnvelope({ organizationId: input.organizationId, type: input.type, data: input.data, eventId: input.eventId, now });
2846
+ const body = JSON.stringify(envelope);
2847
+ const created = await db.webhookDelivery.createMany({
2848
+ data: endpoints.map((endpoint) => ({
2849
+ organizationId: input.organizationId,
2850
+ endpointId: endpoint.id,
2851
+ eventId: envelope.id,
2852
+ eventType: input.type,
2853
+ body,
2854
+ nextAttemptAt: now
2855
+ })),
2856
+ skipDuplicates: true
2857
+ });
2858
+ return { queued: created.count };
2859
+ }
2860
+ async function enqueueAppointmentWebhook(db, input) {
2861
+ try {
2862
+ const data = { ...await appointmentWebhookData(db, input.organizationId, input.appointmentId), ...input.extra };
2863
+ await enqueueWebhookEvent(db, { organizationId: input.organizationId, type: input.type, data, eventId: input.eventId });
2864
+ } catch (error) {
2865
+ const diagnostic = schedError("SCHED_1006", { organizationId: input.organizationId, type: input.type, appointmentId: input.appointmentId, error });
2866
+ console.error(`[webhooks] ${diagnostic.ref} could not queue ${input.type}:`, error);
2867
+ }
2868
+ }
2869
+ async function enqueueReminderSent(db, notification) {
2870
+ try {
2871
+ const appointment = await db.appointment.findUnique({
2872
+ where: { id: notification.appointmentId },
2873
+ select: { calendar: { select: { organizationId: true } } }
2874
+ });
2875
+ const organizationId = appointment?.calendar.organizationId;
2876
+ if (!organizationId) return;
2877
+ await enqueueAppointmentWebhook(db, {
2878
+ organizationId,
2879
+ type: "reminder.sent",
2880
+ appointmentId: notification.appointmentId,
2881
+ extra: { reminder: { channel: notification.channel, trigger: notification.trigger } },
2882
+ eventId: `reminder_${notification.id}`
2883
+ });
2884
+ } catch (error) {
2885
+ const diagnostic = schedError("SCHED_1006", { appointmentId: notification.appointmentId, error });
2886
+ console.error(`[webhooks] ${diagnostic.ref} could not queue reminder.sent:`, error);
2887
+ }
2888
+ }
2889
+
2890
+ // src/notifications/process-pending-notifications.ts
2263
2891
  async function processPendingNotifications(db, sender, options) {
2264
2892
  const batchSize = options?.batchSize ?? 20;
2265
2893
  const maxRetries = options?.retry?.maxRetries ?? 3;
@@ -2295,8 +2923,10 @@ async function processPendingNotifications(db, sender, options) {
2295
2923
  `;
2296
2924
  if (claimed.length === 0) return { sent: 0, failed: 0, deadLettered: 0, skipped: 0 };
2297
2925
  const pending = await db.scheduledNotification.findMany({
2298
- where: { id: { in: claimed.map((c) => c.id) } }
2926
+ where: { id: { in: claimed.map((c) => c.id) } },
2927
+ ...options?.brand ? { include: { appointment: { select: { calendar: { select: { organizationId: true } } } } } } : {}
2299
2928
  });
2929
+ const senders = options?.brand ? await loadSenders(db, pending) : null;
2300
2930
  let sent = 0;
2301
2931
  let failed = 0;
2302
2932
  let deadLettered = 0;
@@ -2308,7 +2938,10 @@ async function processPendingNotifications(db, sender, options) {
2308
2938
  notification.recipient,
2309
2939
  notification.subject || "",
2310
2940
  notification.body,
2311
- { trigger: notification.trigger }
2941
+ {
2942
+ trigger: notification.trigger,
2943
+ ...senderFor(senders, notification)
2944
+ }
2312
2945
  );
2313
2946
  if (result?.skipped) {
2314
2947
  await db.scheduledNotification.update({
@@ -2326,6 +2959,9 @@ async function processPendingNotifications(db, sender, options) {
2326
2959
  data: { status: "SENT", sentAt: /* @__PURE__ */ new Date() }
2327
2960
  });
2328
2961
  sent++;
2962
+ if (options?.webhooks && notification.trigger.startsWith("REMINDER_")) {
2963
+ await enqueueReminderSent(db, notification);
2964
+ }
2329
2965
  }
2330
2966
  } catch (error) {
2331
2967
  const errorMsg = error instanceof Error ? error.message : "Unknown error";
@@ -2359,6 +2995,22 @@ async function processPendingNotifications(db, sender, options) {
2359
2995
  }
2360
2996
  return { sent, failed, deadLettered, skipped };
2361
2997
  }
2998
+ async function loadSenders(db, rows) {
2999
+ const ids = [...new Set(rows.map((row) => row.appointment?.calendar?.organizationId).filter((id) => Boolean(id)))];
3000
+ const senders = /* @__PURE__ */ new Map();
3001
+ if (ids.length === 0) return senders;
3002
+ const brands = await db.organizationBrand.findMany({ where: { organizationId: { in: ids } } });
3003
+ for (const brand of brands) {
3004
+ const identity = senderIdentity(brand);
3005
+ if (identity) senders.set(brand.organizationId, identity);
3006
+ }
3007
+ return senders;
3008
+ }
3009
+ function senderFor(senders, row) {
3010
+ const organizationId = row.appointment?.calendar?.organizationId;
3011
+ const from = senders && organizationId ? senders.get(organizationId) : void 0;
3012
+ return from ? { from } : {};
3013
+ }
2362
3014
 
2363
3015
  // src/notifications/engine.ts
2364
3016
  async function scheduleNotifications(db, appointmentId, baseUrl, options) {
@@ -2378,10 +3030,10 @@ async function scheduleNotifications(db, appointmentId, baseUrl, options) {
2378
3030
  }
2379
3031
  });
2380
3032
  if (!appointment) return;
2381
- const context = buildNotificationContext({
3033
+ const context = await withBrandFields(db, appointment.calendar.organizationId, buildNotificationContext({
2382
3034
  ...appointment,
2383
3035
  intakeResponses: appointment.intakeResponses
2384
- }, baseUrl);
3036
+ }, baseUrl), options?.brand);
2385
3037
  const now = /* @__PURE__ */ new Date();
2386
3038
  const startTime = new Date(appointment.startTime);
2387
3039
  const templates = await db.notificationTemplate.findMany({
@@ -2454,7 +3106,7 @@ async function cancelPendingNotifications(db, appointmentId) {
2454
3106
  data: { status: "CANCELLED" }
2455
3107
  });
2456
3108
  }
2457
- async function queueImmediateNotification(db, appointmentId, trigger, baseUrl) {
3109
+ async function queueImmediateNotification(db, appointmentId, trigger, baseUrl, options) {
2458
3110
  const appointment = await db.appointment.findUnique({
2459
3111
  where: { id: appointmentId },
2460
3112
  include: {
@@ -2463,10 +3115,10 @@ async function queueImmediateNotification(db, appointmentId, trigger, baseUrl) {
2463
3115
  }
2464
3116
  });
2465
3117
  if (!appointment) return;
2466
- const context = buildNotificationContext({
3118
+ const context = await withBrandFields(db, appointment.calendar.organizationId, buildNotificationContext({
2467
3119
  ...appointment,
2468
3120
  intakeResponses: appointment.intakeResponses
2469
- }, baseUrl);
3121
+ }, baseUrl), options?.brand);
2470
3122
  const templates = await db.notificationTemplate.findMany({
2471
3123
  where: { trigger, isActive: true, recipientType: "CLIENT", organizationId: appointment.calendar.organizationId ?? "" }
2472
3124
  });
@@ -2492,7 +3144,7 @@ async function queueImmediateNotification(db, appointmentId, trigger, baseUrl) {
2492
3144
  await db.scheduledNotification.createMany({ data: notifications });
2493
3145
  }
2494
3146
  }
2495
- async function queueStaffNotification(db, appointmentId, trigger, baseUrl) {
3147
+ async function queueStaffNotification(db, appointmentId, trigger, baseUrl, options) {
2496
3148
  const appointment = await db.appointment.findUnique({
2497
3149
  where: { id: appointmentId },
2498
3150
  include: {
@@ -2507,10 +3159,10 @@ async function queueStaffNotification(db, appointmentId, trigger, baseUrl) {
2507
3159
  where: { trigger, recipientType: "STAFF", isActive: true, organizationId: appointment.calendar.organizationId ?? "" }
2508
3160
  });
2509
3161
  if (staffTemplates.length === 0) return;
2510
- const context = buildNotificationContext({
3162
+ const context = await withBrandFields(db, appointment.calendar.organizationId, buildNotificationContext({
2511
3163
  ...appointment,
2512
3164
  intakeResponses: appointment.intakeResponses
2513
- }, baseUrl);
3165
+ }, baseUrl), options?.brand);
2514
3166
  const now = /* @__PURE__ */ new Date();
2515
3167
  const notifications = staffTemplates.map((template) => ({
2516
3168
  appointmentId: appointment.id,
@@ -3457,7 +4109,7 @@ function adaptersToCallbacks(adapters, passThrough = {}) {
3457
4109
  return {
3458
4110
  ...passThrough,
3459
4111
  sendNotification: async (channel, to, subject, body, context) => {
3460
- const result = await adapters.notifications.send({ channel, to, subject, body, trigger: context?.trigger });
4112
+ const result = await adapters.notifications.send({ channel, to, subject, body, trigger: context?.trigger, ...context?.from ? { from: context.from } : {} });
3461
4113
  if (result.status === "SKIPPED") return { skipped: true, reason: result.reason };
3462
4114
  return void 0;
3463
4115
  },
@@ -3505,10 +4157,10 @@ async function checkNotificationContract(adapter) {
3505
4157
  const result = await adapter.send({ channel: "EMAIL", to: "contract@example.com", subject: "Contract", body: "Body" });
3506
4158
  if (result.status !== "SENT" && result.status !== "SKIPPED") failures.push("send() must return status SENT or SKIPPED");
3507
4159
  });
3508
- for (const blank of ["", " "]) {
3509
- await guarded(`send to an empty recipient (${JSON.stringify(blank)})`, failures, async () => {
3510
- const result = await adapter.send({ channel: "SMS", to: blank, subject: "", body: "Body" }).catch(() => null);
3511
- if (result?.status === "SENT") failures.push(`send() must not report SENT for an empty recipient (${JSON.stringify(blank)})`);
4160
+ for (const blank2 of ["", " "]) {
4161
+ await guarded(`send to an empty recipient (${JSON.stringify(blank2)})`, failures, async () => {
4162
+ const result = await adapter.send({ channel: "SMS", to: blank2, subject: "", body: "Body" }).catch(() => null);
4163
+ if (result?.status === "SENT") failures.push(`send() must not report SENT for an empty recipient (${JSON.stringify(blank2)})`);
3512
4164
  });
3513
4165
  }
3514
4166
  return failures;
@@ -3528,7 +4180,7 @@ async function checkPaymentContract(adapter, options = {}) {
3528
4180
  if (!await refused(() => adapter.charge({ ...request, amount: 0 }))) failures.push("a charge of 0 must not succeed");
3529
4181
  });
3530
4182
  await guarded("verify of an unknown payment", failures, async () => {
3531
- const paid = await adapter.verify("contract-unknown-payment").then((check) => check.paid, () => false);
4183
+ const paid = await adapter.verify("contract-unknown-payment").then((check2) => check2.paid, () => false);
3532
4184
  if (paid) failures.push("verify() must report an unknown payment as not paid");
3533
4185
  });
3534
4186
  await guarded("refund of an unknown payment", failures, async () => {
@@ -3544,10 +4196,10 @@ async function checkPaymentContract(adapter, options = {}) {
3544
4196
  failures.push("a valid charge must succeed and return a paymentId");
3545
4197
  return;
3546
4198
  }
3547
- const check = await adapter.verify(charge.paymentId);
3548
- if (!check.paid) failures.push("verify() must report a charged payment as paid");
3549
- if (check.amount !== void 0 && check.amount !== request.amount) failures.push("verify() must report the amount that was charged");
3550
- if (check.metadata?.contract !== "metadata-round-trip") failures.push("verify() must return the metadata the charge was made with");
4199
+ const check2 = await adapter.verify(charge.paymentId);
4200
+ if (!check2.paid) failures.push("verify() must report a charged payment as paid");
4201
+ if (check2.amount !== void 0 && check2.amount !== request.amount) failures.push("verify() must report the amount that was charged");
4202
+ if (check2.metadata?.contract !== "metadata-round-trip") failures.push("verify() must return the metadata the charge was made with");
3551
4203
  const first = await adapter.refund(charge.paymentId);
3552
4204
  if (!first.success) failures.push("the first refund of a paid payment must succeed");
3553
4205
  if (first.amount !== void 0 && first.amount !== request.amount) failures.push("a full refund must report the amount it refunded");
@@ -3816,7 +4468,7 @@ function buildRecurringSlots(firstDate, frequency, occurrences, startTimeLocal,
3816
4468
 
3817
4469
  // src/appointments/meeting.ts
3818
4470
  function buildJitsiUrl(appointmentId) {
3819
- return `https://meet.jit.si/s1701-${appointmentId}`;
4471
+ return `https://meet.jit.si/ordinatio-${appointmentId}`;
3820
4472
  }
3821
4473
  function isVirtualMeeting(locationType) {
3822
4474
  return locationType === "VIRTUAL";
@@ -3888,18 +4540,1616 @@ async function getTeamAvailableSlots(db, query, _getSlots = getAvailableSlots) {
3888
4540
  timezone: query.timezone ?? firstResult?.timezone ?? "UTC"
3889
4541
  };
3890
4542
  }
4543
+
4544
+ // src/webhooks/signature.ts
4545
+ var import_node_crypto2 = require("crypto");
4546
+ var SIGNATURE_HEADER = "x-scheduling-signature";
4547
+ function generateWebhookSecret() {
4548
+ return `whsec_${(0, import_node_crypto2.randomBytes)(32).toString("base64url")}`;
4549
+ }
4550
+ function mac(secret, timestamp, body) {
4551
+ return (0, import_node_crypto2.createHmac)("sha256", secret).update(`${timestamp}.${body}`).digest("hex");
4552
+ }
4553
+ function signWebhook(args) {
4554
+ const timestamp = Math.floor(args.now.getTime() / 1e3);
4555
+ return `t=${timestamp},v1=${mac(args.secret, timestamp, args.body)}`;
4556
+ }
4557
+ function verifyWebhookSignature(args) {
4558
+ if (!args.header) return false;
4559
+ let timestamp = null;
4560
+ const candidates = [];
4561
+ for (const part of args.header.split(",")) {
4562
+ const [key, value] = part.trim().split("=");
4563
+ if (key === "t" && /^\d{1,12}$/.test(value ?? "")) timestamp = Number(value);
4564
+ if (key === "v1" && value) candidates.push(value);
4565
+ }
4566
+ if (timestamp === null || candidates.length === 0) return false;
4567
+ const tolerance = args.toleranceSeconds ?? 300;
4568
+ const nowSeconds = Math.floor((args.now ?? /* @__PURE__ */ new Date()).getTime() / 1e3);
4569
+ if (Math.abs(nowSeconds - timestamp) > tolerance) return false;
4570
+ const expected = Buffer.from(mac(args.secret, timestamp, args.body), "hex");
4571
+ return candidates.some((candidate) => {
4572
+ const given = Buffer.from(candidate, "hex");
4573
+ return given.length === expected.length && (0, import_node_crypto2.timingSafeEqual)(given, expected);
4574
+ });
4575
+ }
4576
+
4577
+ // src/webhooks/url-policy.ts
4578
+ var import_node_net = require("net");
4579
+ function v4Parts(ip) {
4580
+ return ip.split(".").map(Number);
4581
+ }
4582
+ function isPrivateV4(ip) {
4583
+ const [a, b, c] = v4Parts(ip);
4584
+ return a === 0 || a === 10 || a === 127 || a === 100 && b >= 64 && b <= 127 || a === 169 && b === 254 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 0 && c === 0 || a === 192 && b === 168 || a === 198 && (b === 18 || b === 19) || a >= 224;
4585
+ }
4586
+ function v6Groups(ip) {
4587
+ let text2 = ip.toLowerCase().replace(/^\[|\]$/g, "").split("%")[0];
4588
+ const tail = /(\d+\.\d+\.\d+\.\d+)$/.exec(text2);
4589
+ if (tail) {
4590
+ const [a, b, c, d] = v4Parts(tail[1]);
4591
+ text2 = text2.slice(0, -tail[1].length) + (a << 8 | b).toString(16) + ":" + (c << 8 | d).toString(16);
4592
+ }
4593
+ const halves = text2.split("::");
4594
+ if (halves.length > 2) return null;
4595
+ const head = halves[0] ? halves[0].split(":") : [];
4596
+ const rest = halves.length === 2 && halves[1] ? halves[1].split(":") : [];
4597
+ const missing = 8 - head.length - rest.length;
4598
+ if (halves.length === 1 ? missing !== 0 : missing < 1) return null;
4599
+ const groups = [...head, ...Array(halves.length === 2 ? missing : 0).fill("0"), ...rest].map((g) => parseInt(g, 16));
4600
+ return groups.length === 8 && groups.every((g) => Number.isInteger(g) && g >= 0 && g <= 65535) ? groups : null;
4601
+ }
4602
+ function isPrivateV6(ip) {
4603
+ const g = v6Groups(ip);
4604
+ if (!g) return true;
4605
+ const allZeroUpTo = (n) => g.slice(0, n).every((x) => x === 0);
4606
+ if (allZeroUpTo(7) && g[7] <= 1) return true;
4607
+ if (allZeroUpTo(5) && g[5] === 65535) return isPrivateV4(`${g[6] >> 8}.${g[6] & 255}.${g[7] >> 8}.${g[7] & 255}`);
4608
+ if (allZeroUpTo(6)) return isPrivateV4(`${g[6] >> 8}.${g[6] & 255}.${g[7] >> 8}.${g[7] & 255}`);
4609
+ if (g[0] === 100 && g[1] === 65435) return isPrivateV4(`${g[6] >> 8}.${g[6] & 255}.${g[7] >> 8}.${g[7] & 255}`);
4610
+ return (g[0] & 65024) === 64512 || (g[0] & 65472) === 65152 || (g[0] & 65280) === 65280;
4611
+ }
4612
+ function isPrivateAddress(ip) {
4613
+ const bare = ip.replace(/^\[|\]$/g, "");
4614
+ const kind = (0, import_node_net.isIP)(bare);
4615
+ if (kind === 4) return isPrivateV4(bare);
4616
+ if (kind === 6) return isPrivateV6(bare);
4617
+ return true;
4618
+ }
4619
+ var LOCAL_NAME = /(^|\.)(localhost|local|internal|localdomain|home\.arpa)$/;
4620
+ function checkWebhookUrl(raw, options = {}) {
4621
+ let url;
4622
+ try {
4623
+ url = new URL(raw);
4624
+ } catch {
4625
+ return { ok: false, reason: "The address is not a valid web address" };
4626
+ }
4627
+ const insecure = options.allowInsecureTargets === true;
4628
+ if (url.protocol !== "https:" && !(insecure && url.protocol === "http:")) {
4629
+ return { ok: false, reason: "The address must start with https://" };
4630
+ }
4631
+ if (url.username || url.password) {
4632
+ return { ok: false, reason: "The address must not contain a user name or password" };
4633
+ }
4634
+ if (!insecure) {
4635
+ const host = url.hostname.replace(/^\[|\]$/g, "").replace(/\.$/, "");
4636
+ if (LOCAL_NAME.test(host.toLowerCase()) || (0, import_node_net.isIP)(host) !== 0 && isPrivateAddress(host)) {
4637
+ return { ok: false, reason: "The address points at a private or local network" };
4638
+ }
4639
+ if (!host.includes(".") && (0, import_node_net.isIP)(host) === 0) {
4640
+ return { ok: false, reason: "The address must be a public name with a domain" };
4641
+ }
4642
+ }
4643
+ return { ok: true, url };
4644
+ }
4645
+
4646
+ // src/webhooks/transport.ts
4647
+ var import_node_dns = __toESM(require("dns"));
4648
+ var import_node_http = __toESM(require("http"));
4649
+ var import_node_https = __toESM(require("https"));
4650
+ var BlockedTargetError = class extends Error {
4651
+ constructor(hostname) {
4652
+ super(`Refused to connect to ${hostname}: it resolves to a private or local address`);
4653
+ this.name = "BlockedTargetError";
4654
+ }
4655
+ };
4656
+ function guardedLookup(allowPrivate) {
4657
+ return (hostname, options, callback) => {
4658
+ import_node_dns.default.lookup(hostname, { ...options, all: true }, (error, addresses) => {
4659
+ if (error) return callback(error, "", 0);
4660
+ const list = addresses;
4661
+ if (list.length === 0) return callback(Object.assign(new Error(`No address for ${hostname}`), { code: "ENOTFOUND" }), "", 0);
4662
+ if (!allowPrivate && list.some((a) => isPrivateAddress(a.address))) return callback(new BlockedTargetError(hostname), "", 0);
4663
+ if (options.all) return callback(null, list);
4664
+ callback(null, list[0].address, list[0].family);
4665
+ });
4666
+ };
4667
+ }
4668
+ function createNodeTransport(options = {}) {
4669
+ const allowPrivate = options.allowInsecureTargets === true;
4670
+ return ({ url, headers, body, timeoutMs }) => new Promise((resolve, reject) => {
4671
+ const client = url.protocol === "https:" ? import_node_https.default : import_node_http.default;
4672
+ let settled = false;
4673
+ const finish = (action) => {
4674
+ if (settled) return;
4675
+ settled = true;
4676
+ clearTimeout(timer);
4677
+ action();
4678
+ };
4679
+ const request = client.request(
4680
+ url,
4681
+ {
4682
+ method: "POST",
4683
+ headers: { ...headers, "content-length": String(Buffer.byteLength(body)) },
4684
+ lookup: guardedLookup(allowPrivate),
4685
+ agent: false
4686
+ },
4687
+ (response) => {
4688
+ const status = response.statusCode ?? 0;
4689
+ response.destroy();
4690
+ finish(() => resolve({ status }));
4691
+ }
4692
+ );
4693
+ const timer = setTimeout(() => {
4694
+ request.destroy(new Error(`Timed out after ${timeoutMs} ms`));
4695
+ }, timeoutMs);
4696
+ request.on("error", (error) => finish(() => reject(error)));
4697
+ request.end(body);
4698
+ });
4699
+ }
4700
+
4701
+ // src/webhooks/endpoints.ts
4702
+ var MAX_ENDPOINTS_PER_ORGANIZATION = 20;
4703
+ var VIEW_FIELDS = { id: true, url: true, description: true, eventTypes: true, isActive: true, createdAt: true };
4704
+ async function createWebhookEndpoint(db, input, options = {}) {
4705
+ const checked = checkWebhookUrl(input.url, options);
4706
+ if (!checked.ok) throw new SchedulingValidationError(checked.reason, "SCHED_1000", { url: input.url });
4707
+ const eventTypes = normalizeEventTypes(input.eventTypes);
4708
+ if (!eventTypes) throw new SchedulingValidationError("Choose at least one valid event, or *", "SCHED_1001");
4709
+ const existing = await db.webhookEndpoint.count({ where: { organizationId: input.organizationId } });
4710
+ if (existing >= MAX_ENDPOINTS_PER_ORGANIZATION) {
4711
+ throw new SchedulingValidationError(
4712
+ `An organization can have at most ${MAX_ENDPOINTS_PER_ORGANIZATION} webhook endpoints`,
4713
+ "SCHED_1002",
4714
+ { organizationId: input.organizationId }
4715
+ );
4716
+ }
4717
+ const secret = generateWebhookSecret();
4718
+ const endpoint = await db.webhookEndpoint.create({
4719
+ data: {
4720
+ organizationId: input.organizationId,
4721
+ url: checked.url.toString(),
4722
+ description: input.description?.trim() || null,
4723
+ eventTypes,
4724
+ secret
4725
+ },
4726
+ select: VIEW_FIELDS
4727
+ });
4728
+ return { endpoint, secret };
4729
+ }
4730
+ async function listWebhookEndpoints(db, organizationId) {
4731
+ return db.webhookEndpoint.findMany({ where: { organizationId }, orderBy: { createdAt: "desc" }, select: VIEW_FIELDS });
4732
+ }
4733
+ async function deleteWebhookEndpoint(db, organizationId, endpointId) {
4734
+ const removed = await db.webhookEndpoint.deleteMany({ where: { id: endpointId, organizationId } });
4735
+ if (removed.count === 0) throw new SchedulingNotFoundError("Webhook endpoint not found", "SCHED_1003", { endpointId });
4736
+ }
4737
+
4738
+ // src/webhooks/deliver.ts
4739
+ var import_node_crypto3 = require("crypto");
4740
+ var import_client8 = require("@prisma/client");
4741
+
4742
+ // src/webhooks/attempt.ts
4743
+ var DEFAULT_BACKOFF_SECONDS = [60, 300, 1800, 7200, 21600];
4744
+ var MAX_ERROR_LENGTH = 300;
4745
+ function describe(error) {
4746
+ const code = error.code;
4747
+ const message = error instanceof Error ? error.message : String(error);
4748
+ return (code && !message.includes(code) ? `${code}: ${message}` : message).slice(0, MAX_ERROR_LENGTH);
4749
+ }
4750
+ async function attemptDelivery(db, delivery, workerId, options = {}) {
4751
+ const now = options.now ?? (() => /* @__PURE__ */ new Date());
4752
+ const backoff = options.backoffSeconds ?? DEFAULT_BACKOFF_SECONDS;
4753
+ const maxAttempts = options.maxAttempts ?? backoff.length + 1;
4754
+ const transport = options.transport ?? createNodeTransport({ allowInsecureTargets: options.allowInsecureTargets });
4755
+ const attemptNumber = delivery.attempts + 1;
4756
+ const startedAt = now();
4757
+ let statusCode = null;
4758
+ let error = null;
4759
+ let retryable = true;
4760
+ const target = checkWebhookUrl(delivery.endpoint.url, { allowInsecureTargets: options.allowInsecureTargets });
4761
+ if (!delivery.endpoint.isActive) {
4762
+ error = "The endpoint is switched off";
4763
+ retryable = false;
4764
+ } else if (!target.ok) {
4765
+ error = `${schedError("SCHED_1005", { endpointId: delivery.endpoint.id }).ref}: ${target.reason}`;
4766
+ retryable = false;
4767
+ } else {
4768
+ try {
4769
+ const response = await transport({
4770
+ url: target.url,
4771
+ timeoutMs: options.timeoutMs ?? 1e4,
4772
+ body: delivery.body,
4773
+ headers: {
4774
+ "content-type": "application/json",
4775
+ "user-agent": "scheduling-webhooks/1",
4776
+ "x-scheduling-event": delivery.eventType,
4777
+ "x-scheduling-delivery": delivery.id,
4778
+ [SIGNATURE_HEADER]: signWebhook({ secret: delivery.endpoint.secret, body: delivery.body, now: startedAt })
4779
+ }
4780
+ });
4781
+ statusCode = response.status;
4782
+ if (response.status < 200 || response.status >= 300) error = `The receiver answered HTTP ${response.status}`;
4783
+ } catch (caught) {
4784
+ error = describe(caught);
4785
+ retryable = caught.name !== "BlockedTargetError";
4786
+ }
4787
+ }
4788
+ const finishedAt = now();
4789
+ const succeeded = error === null;
4790
+ const exhausted = !retryable || attemptNumber >= maxAttempts;
4791
+ const outcome = succeeded ? "SUCCEEDED" : exhausted ? "DEAD_LETTER" : "RETRY";
4792
+ const updated = await db.webhookDelivery.updateMany({
4793
+ where: { id: delivery.id, organizationId: delivery.organizationId, status: "PROCESSING", processingId: workerId },
4794
+ data: {
4795
+ status: outcome === "SUCCEEDED" ? "SUCCEEDED" : outcome === "DEAD_LETTER" ? "DEAD_LETTER" : "PENDING",
4796
+ attempts: attemptNumber,
4797
+ lastStatusCode: statusCode,
4798
+ lastError: error,
4799
+ deliveredAt: succeeded ? finishedAt : null,
4800
+ nextAttemptAt: outcome === "RETRY" ? new Date(finishedAt.getTime() + backoff[Math.min(attemptNumber - 1, backoff.length - 1)] * 1e3) : void 0,
4801
+ processingId: null,
4802
+ claimedAt: null
4803
+ }
4804
+ });
4805
+ if (updated.count === 0) return { outcome: "LOST_CLAIM", statusCode, error };
4806
+ await db.webhookAttempt.create({
4807
+ data: { deliveryId: delivery.id, attemptNumber, statusCode, error, durationMs: Math.max(0, finishedAt.getTime() - startedAt.getTime()) }
4808
+ });
4809
+ return { outcome, statusCode, error };
4810
+ }
4811
+
4812
+ // src/webhooks/deliver.ts
4813
+ async function deliverDueWebhooks(db, options = {}) {
4814
+ const now = (options.now ?? (() => /* @__PURE__ */ new Date()))();
4815
+ const batchSize = Math.max(1, Math.min(200, Math.floor(options.batchSize ?? 20)));
4816
+ const concurrency = Math.max(1, Math.floor(options.concurrency ?? 5));
4817
+ const workerId = options.workerId ?? (0, import_node_crypto3.randomUUID)();
4818
+ const staleBefore = new Date(now.getTime() - (options.staleClaimMs ?? 5 * 6e4));
4819
+ const claimed = await db.$queryRaw`
4820
+ WITH candidates AS (
4821
+ SELECT id FROM "WebhookDelivery"
4822
+ WHERE (status = 'PENDING' AND "nextAttemptAt" <= ${now})
4823
+ OR (status = 'PROCESSING' AND "claimedAt" < ${staleBefore})
4824
+ ORDER BY "nextAttemptAt" ASC
4825
+ LIMIT ${import_client8.Prisma.raw(String(batchSize))}
4826
+ FOR UPDATE SKIP LOCKED
4827
+ )
4828
+ UPDATE "WebhookDelivery" d
4829
+ SET status = 'PROCESSING', "processingId" = ${workerId}, "claimedAt" = ${now}
4830
+ FROM candidates
4831
+ WHERE d.id = candidates.id
4832
+ RETURNING d.id
4833
+ `;
4834
+ const summary = { succeeded: 0, retried: 0, deadLettered: 0, lostClaim: 0 };
4835
+ if (claimed.length === 0) return summary;
4836
+ const rows = await db.webhookDelivery.findMany({
4837
+ where: { id: { in: claimed.map((c) => c.id) }, processingId: workerId },
4838
+ select: {
4839
+ id: true,
4840
+ organizationId: true,
4841
+ eventId: true,
4842
+ eventType: true,
4843
+ body: true,
4844
+ attempts: true,
4845
+ endpoint: { select: { id: true, url: true, secret: true, isActive: true } }
4846
+ }
4847
+ });
4848
+ for (let i = 0; i < rows.length; i += concurrency) {
4849
+ const results = await Promise.all(rows.slice(i, i + concurrency).map((row) => attemptDelivery(db, row, workerId, options)));
4850
+ for (const { outcome } of results) {
4851
+ if (outcome === "SUCCEEDED") summary.succeeded++;
4852
+ else if (outcome === "RETRY") summary.retried++;
4853
+ else if (outcome === "DEAD_LETTER") summary.deadLettered++;
4854
+ else summary.lostClaim++;
4855
+ }
4856
+ }
4857
+ return summary;
4858
+ }
4859
+
4860
+ // src/webhooks/test-send.ts
4861
+ var import_node_crypto4 = require("crypto");
4862
+ async function sendTestWebhook(db, input, options = {}) {
4863
+ const endpoint = await db.webhookEndpoint.findFirst({
4864
+ where: { id: input.endpointId, organizationId: input.organizationId },
4865
+ select: { id: true, url: true, secret: true, isActive: true }
4866
+ });
4867
+ if (!endpoint) throw new SchedulingNotFoundError("Webhook endpoint not found", "SCHED_1003", { endpointId: input.endpointId });
4868
+ const now = (options.now ?? (() => /* @__PURE__ */ new Date()))();
4869
+ const workerId = (0, import_node_crypto4.randomUUID)();
4870
+ const envelope = buildEnvelope({
4871
+ organizationId: input.organizationId,
4872
+ type: WEBHOOK_TEST_EVENT,
4873
+ data: { message: "This is a test event from your scheduling system." },
4874
+ now
4875
+ });
4876
+ const created = await db.webhookDelivery.create({
4877
+ data: {
4878
+ organizationId: input.organizationId,
4879
+ endpointId: endpoint.id,
4880
+ eventId: envelope.id,
4881
+ eventType: WEBHOOK_TEST_EVENT,
4882
+ body: JSON.stringify(envelope),
4883
+ status: "PROCESSING",
4884
+ processingId: workerId,
4885
+ claimedAt: now,
4886
+ nextAttemptAt: now
4887
+ },
4888
+ select: { id: true, organizationId: true, eventId: true, eventType: true, body: true, attempts: true }
4889
+ });
4890
+ const result = await attemptDelivery(db, { ...created, endpoint }, workerId, { ...options, maxAttempts: 1 });
4891
+ return { deliveryId: created.id, ok: result.outcome === "SUCCEEDED", statusCode: result.statusCode, error: result.error };
4892
+ }
4893
+
4894
+ // src/webhooks/deliveries.ts
4895
+ async function listWebhookDeliveries(db, input) {
4896
+ const where = {
4897
+ organizationId: input.organizationId,
4898
+ ...input.endpointId ? { endpointId: input.endpointId } : {},
4899
+ ...input.status ? { status: input.status } : {}
4900
+ };
4901
+ const [deliveries, total] = await Promise.all([
4902
+ db.webhookDelivery.findMany({
4903
+ where,
4904
+ orderBy: { createdAt: "desc" },
4905
+ take: Math.min(input.limit ?? 50, 200),
4906
+ skip: input.offset ?? 0,
4907
+ select: {
4908
+ id: true,
4909
+ endpointId: true,
4910
+ eventId: true,
4911
+ eventType: true,
4912
+ status: true,
4913
+ attempts: true,
4914
+ nextAttemptAt: true,
4915
+ lastStatusCode: true,
4916
+ lastError: true,
4917
+ deliveredAt: true,
4918
+ createdAt: true,
4919
+ attemptLog: { orderBy: { attemptNumber: "desc" }, take: 10, select: { attemptNumber: true, statusCode: true, error: true, durationMs: true, createdAt: true } }
4920
+ }
4921
+ }),
4922
+ db.webhookDelivery.count({ where })
4923
+ ]);
4924
+ return { deliveries, total };
4925
+ }
4926
+ async function retryWebhookDelivery(db, organizationId, deliveryId, now = /* @__PURE__ */ new Date()) {
4927
+ const updated = await db.webhookDelivery.updateMany({
4928
+ where: { id: deliveryId, organizationId, status: "DEAD_LETTER" },
4929
+ data: { status: "PENDING", attempts: 0, nextAttemptAt: now, processingId: null, claimedAt: null }
4930
+ });
4931
+ if (updated.count === 0) throw new SchedulingNotFoundError("Delivery not found or not in the dead-letter list", "SCHED_1004", { deliveryId });
4932
+ }
4933
+
4934
+ // src/waitlist/join.ts
4935
+ var import_node_crypto5 = require("crypto");
4936
+
4937
+ // src/waitlist/day.ts
4938
+ var MAX_DAYS_AHEAD = 90;
4939
+ function isDayString(value) {
4940
+ if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
4941
+ const parsed = /* @__PURE__ */ new Date(`${value}T00:00:00Z`);
4942
+ return !Number.isNaN(parsed.getTime()) && parsed.toISOString().slice(0, 10) === value;
4943
+ }
4944
+ function localDay(instant, timeZone) {
4945
+ return new Intl.DateTimeFormat("en-CA", { timeZone, year: "numeric", month: "2-digit", day: "2-digit" }).format(instant);
4946
+ }
4947
+ function daysBetween(from, to) {
4948
+ return Math.round((Date.parse(`${to}T00:00:00Z`) - Date.parse(`${from}T00:00:00Z`)) / 864e5);
4949
+ }
4950
+
4951
+ // src/waitlist/view.ts
4952
+ var VIEW_SELECT = {
4953
+ id: true,
4954
+ typeId: true,
4955
+ calendarId: true,
4956
+ day: true,
4957
+ slotStart: true,
4958
+ clientName: true,
4959
+ clientEmail: true,
4960
+ clientPhone: true,
4961
+ status: true,
4962
+ offerSlotStart: true,
4963
+ offerExpiresAt: true,
4964
+ createdAt: true
4965
+ };
4966
+ var LIVE_STATUSES = ["WAITING", "OFFERED", "ACCEPTING"];
4967
+
4968
+ // src/waitlist/join.ts
4969
+ var MAX_WAITING_PER_TYPE_DAY = 50;
4970
+ async function joinWaitlist(db, input, now = /* @__PURE__ */ new Date()) {
4971
+ const orgScope = [{ organizationId: input.organizationId }, { organizationId: null }];
4972
+ const type = await db.appointmentType.findFirst({
4973
+ where: { id: input.typeId, isActive: true, OR: orgScope },
4974
+ select: { id: true, duration: true, requiresPayment: true, intakeForm: true, calendars: { select: { calendarId: true } } }
4975
+ });
4976
+ if (!type) throw new SchedulingNotFoundError("Appointment type not found", "SCHED_1100", { typeId: input.typeId });
4977
+ if (type.requiresPayment) {
4978
+ throw new SchedulingValidationError("A waitlist is not available for a type that needs payment", "SCHED_1105", { typeId: input.typeId });
4979
+ }
4980
+ const intakeForm = Array.isArray(type.intakeForm) ? type.intakeForm : [];
4981
+ if (intakeForm.some((field) => field.required)) {
4982
+ throw new SchedulingValidationError("A waitlist is not available for a type with required questions", "SCHED_1110", { typeId: input.typeId });
4983
+ }
4984
+ const linked = type.calendars.map((c) => c.calendarId);
4985
+ if (input.calendarId && !linked.includes(input.calendarId)) {
4986
+ throw new SchedulingNotFoundError("Calendar not found for this type", "SCHED_1100", { calendarId: input.calendarId });
4987
+ }
4988
+ const calendars = await db.schedulingCalendar.findMany({
4989
+ where: { id: { in: input.calendarId ? [input.calendarId] : linked }, OR: orgScope },
4990
+ select: { id: true, timezone: true }
4991
+ });
4992
+ if (calendars.length === 0) throw new SchedulingNotFoundError("Calendar not found for this type", "SCHED_1100", { typeId: input.typeId });
4993
+ const timezone = calendars[0].timezone;
4994
+ if (!isDayString(input.day)) throw new SchedulingValidationError("The day must be YYYY-MM-DD", "SCHED_1101", { day: input.day });
4995
+ const ahead = daysBetween(localDay(now, timezone), input.day);
4996
+ if (ahead < 0 || ahead > MAX_DAYS_AHEAD) {
4997
+ throw new SchedulingValidationError(`The day must be within the next ${MAX_DAYS_AHEAD} days`, "SCHED_1101", { day: input.day });
4998
+ }
4999
+ if (input.slotStart) {
5000
+ if (Number.isNaN(input.slotStart.getTime()) || input.slotStart <= now || localDay(input.slotStart, timezone) !== input.day) {
5001
+ throw new SchedulingValidationError("The time must be in the future, on the chosen day", "SCHED_1102", { day: input.day });
5002
+ }
5003
+ }
5004
+ const open = [];
5005
+ for (const calendar of calendars) {
5006
+ const result = await getAvailableSlots(db, {
5007
+ calendarId: calendar.id,
5008
+ date: /* @__PURE__ */ new Date(`${input.day}T12:00:00Z`),
5009
+ localDate: input.day,
5010
+ duration: type.duration,
5011
+ timezone: calendar.timezone
5012
+ });
5013
+ for (const slot of result.slots) if (slot.available) open.push(slot.start);
5014
+ }
5015
+ const stillOpen = input.slotStart ? open.some((start) => start.getTime() === input.slotStart.getTime()) : open.length > 0;
5016
+ if (stillOpen) {
5017
+ throw new SchedulingValidationError("That time is open: book it instead of waiting", "SCHED_1103", { day: input.day });
5018
+ }
5019
+ const email2 = input.clientEmail.trim();
5020
+ const duplicate = await db.waitlistEntry.findFirst({
5021
+ where: {
5022
+ organizationId: input.organizationId,
5023
+ typeId: type.id,
5024
+ day: input.day,
5025
+ slotStart: input.slotStart ?? null,
5026
+ clientEmail: { equals: email2, mode: "insensitive" },
5027
+ status: { in: LIVE_STATUSES }
5028
+ },
5029
+ select: { id: true }
5030
+ });
5031
+ if (duplicate) throw new SchedulingValidationError("This email is already waiting for that day", "SCHED_1104", { day: input.day });
5032
+ const waiting = await db.waitlistEntry.count({ where: { organizationId: input.organizationId, typeId: type.id, day: input.day, status: "WAITING" } });
5033
+ if (waiting >= MAX_WAITING_PER_TYPE_DAY) {
5034
+ throw new SchedulingValidationError("The waitlist for that day is full", "SCHED_1108", { day: input.day });
5035
+ }
5036
+ const token = (0, import_node_crypto5.randomBytes)(24).toString("base64url");
5037
+ const entry4 = await db.waitlistEntry.create({
5038
+ data: {
5039
+ organizationId: input.organizationId,
5040
+ typeId: type.id,
5041
+ calendarId: input.calendarId ?? null,
5042
+ day: input.day,
5043
+ slotStart: input.slotStart ?? null,
5044
+ timezone,
5045
+ clientName: input.clientName.trim(),
5046
+ clientEmail: email2,
5047
+ clientPhone: input.clientPhone?.trim() || null,
5048
+ token
5049
+ },
5050
+ select: VIEW_SELECT
5051
+ });
5052
+ return { entry: entry4, token };
5053
+ }
5054
+
5055
+ // src/waitlist/accept.ts
5056
+ var ENTRY_SELECT = {
5057
+ id: true,
5058
+ organizationId: true,
5059
+ typeId: true,
5060
+ status: true,
5061
+ offerCalendarId: true,
5062
+ offerSlotStart: true,
5063
+ offerExpiresAt: true,
5064
+ clientName: true,
5065
+ clientEmail: true,
5066
+ clientPhone: true,
5067
+ timezone: true,
5068
+ type: { select: { name: true } }
5069
+ };
5070
+ async function loadOffer(db, token) {
5071
+ const entry4 = await db.waitlistEntry.findUnique({ where: { token }, select: ENTRY_SELECT });
5072
+ if (!entry4 || !entry4.offerCalendarId || !entry4.offerSlotStart || !entry4.offerExpiresAt) {
5073
+ throw new SchedulingNotFoundError("No open offer for this link", "SCHED_1106");
5074
+ }
5075
+ const calendar = await db.schedulingCalendar.findUnique({ where: { id: entry4.offerCalendarId }, select: { name: true } });
5076
+ return {
5077
+ status: entry4.status,
5078
+ details: {
5079
+ entryId: entry4.id,
5080
+ organizationId: entry4.organizationId,
5081
+ typeId: entry4.typeId,
5082
+ typeName: entry4.type.name,
5083
+ calendarId: entry4.offerCalendarId,
5084
+ calendarName: calendar?.name ?? "",
5085
+ startTime: entry4.offerSlotStart,
5086
+ timezone: entry4.timezone,
5087
+ expiresAt: entry4.offerExpiresAt,
5088
+ clientName: entry4.clientName,
5089
+ clientEmail: entry4.clientEmail,
5090
+ clientPhone: entry4.clientPhone
5091
+ }
5092
+ };
5093
+ }
5094
+ async function getWaitlistOffer(db, token, now = /* @__PURE__ */ new Date()) {
5095
+ const { details, status } = await loadOffer(db, token);
5096
+ if (status !== "OFFERED") throw new SchedulingNotFoundError("No open offer for this link", "SCHED_1106");
5097
+ if (details.expiresAt <= now) throw new SchedulingValidationError("The offer has expired", "SCHED_1107");
5098
+ return details;
5099
+ }
5100
+ async function beginWaitlistAccept(db, token, now = /* @__PURE__ */ new Date()) {
5101
+ const claimed = await db.waitlistEntry.updateMany({
5102
+ where: { token, status: "OFFERED", offerExpiresAt: { gt: now } },
5103
+ data: { status: "ACCEPTING", acceptingAt: now }
5104
+ });
5105
+ if (claimed.count === 0) {
5106
+ await getWaitlistOffer(db, token, now);
5107
+ throw new SchedulingNotFoundError("No open offer for this link", "SCHED_1106");
5108
+ }
5109
+ return (await loadOffer(db, token)).details;
5110
+ }
5111
+ async function completeWaitlistAccept(db, entryId, appointmentId) {
5112
+ await db.waitlistEntry.updateMany({
5113
+ where: { id: entryId, status: "ACCEPTING" },
5114
+ data: { status: "BOOKED", bookedAppointmentId: appointmentId }
5115
+ });
5116
+ }
5117
+ async function releaseWaitlistAccept(db, entryId, outcome = "BACK_IN_LINE") {
5118
+ const where = { id: entryId, status: "ACCEPTING" };
5119
+ if (outcome === "KEEP_OFFER") {
5120
+ await db.waitlistEntry.updateMany({ where, data: { status: "OFFERED", acceptingAt: null } });
5121
+ return null;
5122
+ }
5123
+ if (outcome === "BACK_IN_LINE") {
5124
+ await db.waitlistEntry.updateMany({
5125
+ where,
5126
+ data: { status: "WAITING", offerCalendarId: null, offerSlotStart: null, offerExpiresAt: null, offeredAt: null, acceptingAt: null }
5127
+ });
5128
+ return null;
5129
+ }
5130
+ const row = await db.waitlistEntry.findFirst({ where, select: { organizationId: true, offerCalendarId: true, offerSlotStart: true } });
5131
+ const ended = await db.waitlistEntry.updateMany({ where, data: { status: "EXPIRED", acceptingAt: null } });
5132
+ return row && ended.count > 0 && row.offerCalendarId && row.offerSlotStart ? { organizationId: row.organizationId, calendarId: row.offerCalendarId, startTime: row.offerSlotStart } : null;
5133
+ }
5134
+ async function findBookingForOffer(db, entry4) {
5135
+ if (!entry4.offerCalendarId || !entry4.offerSlotStart) return null;
5136
+ return db.appointment.findFirst({
5137
+ where: {
5138
+ calendarId: entry4.offerCalendarId,
5139
+ startTime: entry4.offerSlotStart,
5140
+ clientEmail: { equals: entry4.clientEmail, mode: "insensitive" },
5141
+ status: { in: ["PENDING", "CONFIRMED"] }
5142
+ },
5143
+ select: { id: true }
5144
+ });
5145
+ }
5146
+ async function settleBookedAccept(db, entryId) {
5147
+ const entry4 = await db.waitlistEntry.findFirst({
5148
+ where: { id: entryId, status: "ACCEPTING" },
5149
+ select: { offerCalendarId: true, offerSlotStart: true, clientEmail: true }
5150
+ });
5151
+ const found = entry4 ? await findBookingForOffer(db, entry4) : null;
5152
+ if (!found) return null;
5153
+ await db.waitlistEntry.updateMany({
5154
+ where: { id: entryId, status: "ACCEPTING" },
5155
+ data: { status: "BOOKED", bookedAppointmentId: found.id, acceptingAt: null }
5156
+ });
5157
+ return db.appointment.findUnique({
5158
+ where: { id: found.id },
5159
+ select: { id: true, status: true, startTime: true, endTime: true, manageToken: true, clientName: true, clientEmail: true }
5160
+ });
5161
+ }
5162
+
5163
+ // src/waitlist/offer.ts
5164
+ var DEFAULT_OFFER_MINUTES = 30;
5165
+ var CANDIDATES_PER_SLOT = 25;
5166
+ function isUniqueViolation(error) {
5167
+ return typeof error === "object" && error !== null && error.code === "P2002";
5168
+ }
5169
+ async function offerFreedSlot(db, input) {
5170
+ const now = input.now ?? /* @__PURE__ */ new Date();
5171
+ if (input.startTime <= now) return null;
5172
+ const calendar = await db.schedulingCalendar.findUnique({
5173
+ where: { id: input.calendarId },
5174
+ select: { name: true, timezone: true, organizationId: true }
5175
+ });
5176
+ if (!calendar || calendar.organizationId !== null && calendar.organizationId !== input.organizationId) return null;
5177
+ await db.waitlistEntry.updateMany({
5178
+ where: {
5179
+ organizationId: input.organizationId,
5180
+ status: "OFFERED",
5181
+ offerCalendarId: input.calendarId,
5182
+ offerSlotStart: input.startTime,
5183
+ offerExpiresAt: { lte: now }
5184
+ },
5185
+ data: { status: "EXPIRED" }
5186
+ });
5187
+ const candidates = await db.waitlistEntry.findMany({
5188
+ where: {
5189
+ organizationId: input.organizationId,
5190
+ status: "WAITING",
5191
+ day: localDay(input.startTime, calendar.timezone),
5192
+ // Only people whose type runs on this calendar, so earlier people it cannot fit never crowd out later ones that it can.
5193
+ type: { isActive: true, calendars: { some: { calendarId: input.calendarId } } },
5194
+ AND: [
5195
+ { OR: [{ calendarId: null }, { calendarId: input.calendarId }] },
5196
+ { OR: [{ slotStart: null }, { slotStart: input.startTime }] }
5197
+ ]
5198
+ },
5199
+ orderBy: { createdAt: "asc" },
5200
+ take: CANDIDATES_PER_SLOT,
5201
+ select: { ...VIEW_SELECT, token: true, timezone: true }
5202
+ });
5203
+ const expiresAt = new Date(Math.min(now.getTime() + (input.offerMinutes ?? DEFAULT_OFFER_MINUTES) * 6e4, input.startTime.getTime()));
5204
+ for (const candidate of candidates) {
5205
+ const type = await db.appointmentType.findFirst({
5206
+ where: { id: candidate.typeId, isActive: true, calendars: { some: { calendarId: input.calendarId } } },
5207
+ select: { name: true, duration: true }
5208
+ });
5209
+ if (!type || !await isSlotAvailable(db, input.calendarId, input.startTime, type.duration)) continue;
5210
+ let claimed;
5211
+ try {
5212
+ claimed = await db.waitlistEntry.updateMany({
5213
+ where: { id: candidate.id, status: "WAITING" },
5214
+ data: { status: "OFFERED", offerCalendarId: input.calendarId, offerSlotStart: input.startTime, offerExpiresAt: expiresAt, offeredAt: now }
5215
+ });
5216
+ } catch (error) {
5217
+ if (isUniqueViolation(error)) return null;
5218
+ throw error;
5219
+ }
5220
+ if (claimed.count === 0) continue;
5221
+ const { token, timezone, ...view2 } = candidate;
5222
+ return {
5223
+ entry: { ...view2, status: "OFFERED", offerSlotStart: input.startTime, offerExpiresAt: expiresAt },
5224
+ token,
5225
+ calendarId: input.calendarId,
5226
+ calendarName: calendar.name,
5227
+ typeName: type.name,
5228
+ startTime: input.startTime,
5229
+ timezone,
5230
+ expiresAt
5231
+ };
5232
+ }
5233
+ return null;
5234
+ }
5235
+ async function tryOfferFreedSlot(db, input) {
5236
+ try {
5237
+ return await offerFreedSlot(db, input);
5238
+ } catch (error) {
5239
+ const diagnostic = schedError("SCHED_1109", { organizationId: input.organizationId, calendarId: input.calendarId, error });
5240
+ console.error(`[waitlist] ${diagnostic.ref} could not offer a freed slot:`, error);
5241
+ return null;
5242
+ }
5243
+ }
5244
+ async function expireWaitlistOffers(db, options = {}) {
5245
+ const now = options.now ?? /* @__PURE__ */ new Date();
5246
+ const stuckBefore = new Date(now.getTime() - (options.acceptTimeoutMs ?? 5 * 6e4));
5247
+ const rows = await db.$queryRaw`
5248
+ UPDATE "WaitlistEntry" SET status = 'EXPIRED'
5249
+ WHERE status = 'OFFERED' AND "offerExpiresAt" <= ${now}
5250
+ RETURNING "organizationId", "offerCalendarId", "offerSlotStart"
5251
+ `;
5252
+ const lapsed = rows.map((r) => ({ organizationId: r.organizationId, calendarId: r.offerCalendarId, startTime: r.offerSlotStart }));
5253
+ const stuck = await db.waitlistEntry.findMany({
5254
+ where: { status: "ACCEPTING", acceptingAt: { lte: stuckBefore } },
5255
+ take: 100,
5256
+ select: { id: true, organizationId: true, offerCalendarId: true, offerSlotStart: true, clientEmail: true }
5257
+ });
5258
+ let released = 0;
5259
+ let booked = 0;
5260
+ for (const entry4 of stuck) {
5261
+ const appointment = await findBookingForOffer(db, entry4);
5262
+ if (appointment) {
5263
+ const done = await db.waitlistEntry.updateMany({
5264
+ where: { id: entry4.id, status: "ACCEPTING" },
5265
+ data: { status: "BOOKED", bookedAppointmentId: appointment.id, acceptingAt: null }
5266
+ });
5267
+ booked += done.count;
5268
+ continue;
5269
+ }
5270
+ const back = await db.waitlistEntry.updateMany({
5271
+ where: { id: entry4.id, status: "ACCEPTING" },
5272
+ data: { status: "WAITING", offerCalendarId: null, offerSlotStart: null, offerExpiresAt: null, offeredAt: null, acceptingAt: null }
5273
+ });
5274
+ if (back.count > 0) {
5275
+ released++;
5276
+ if (entry4.offerCalendarId && entry4.offerSlotStart) {
5277
+ lapsed.push({ organizationId: entry4.organizationId, calendarId: entry4.offerCalendarId, startTime: entry4.offerSlotStart });
5278
+ }
5279
+ }
5280
+ }
5281
+ return { lapsed, released, booked };
5282
+ }
5283
+
5284
+ // src/waitlist/manage.ts
5285
+ var OFFER_FIELDS = { organizationId: true, status: true, offerCalendarId: true, offerSlotStart: true };
5286
+ function freedSlot(row) {
5287
+ return row.status === "OFFERED" && row.offerCalendarId && row.offerSlotStart ? { organizationId: row.organizationId, calendarId: row.offerCalendarId, startTime: row.offerSlotStart } : null;
5288
+ }
5289
+ async function listWaitlist(db, input) {
5290
+ const where = { organizationId: input.organizationId, ...input.status ? { status: input.status } : {} };
5291
+ const [entries, total] = await Promise.all([
5292
+ db.waitlistEntry.findMany({
5293
+ where,
5294
+ orderBy: { createdAt: "asc" },
5295
+ take: Math.min(input.limit ?? 50, 200),
5296
+ skip: input.offset ?? 0,
5297
+ select: VIEW_SELECT
5298
+ }),
5299
+ db.waitlistEntry.count({ where })
5300
+ ]);
5301
+ return { entries, total };
5302
+ }
5303
+ async function removeWaitlistEntry(db, organizationId, entryId) {
5304
+ const where = { id: entryId, organizationId, status: { in: ["WAITING", "OFFERED", "EXPIRED", "BOOKED"] } };
5305
+ const row = await db.waitlistEntry.findFirst({ where, select: OFFER_FIELDS });
5306
+ const removed = row ? await db.waitlistEntry.deleteMany({ where: { ...where, status: row.status } }) : { count: 0 };
5307
+ if (!row || removed.count === 0) throw new SchedulingNotFoundError("Waitlist entry not found", "SCHED_1106", { entryId });
5308
+ return freedSlot(row);
5309
+ }
5310
+ async function leaveWaitlist(db, token) {
5311
+ const where = { token, status: { in: ["WAITING", "OFFERED"] } };
5312
+ const row = await db.waitlistEntry.findFirst({ where, select: OFFER_FIELDS });
5313
+ const removed = row ? await db.waitlistEntry.deleteMany({ where: { ...where, status: row.status } }) : { count: 0 };
5314
+ if (!row || removed.count === 0) throw new SchedulingNotFoundError("No waitlist entry for this link", "SCHED_1106");
5315
+ return freedSlot(row);
5316
+ }
5317
+
5318
+ // src/routing/types.ts
5319
+ var LIMITS = {
5320
+ questions: 20,
5321
+ rules: 50,
5322
+ conditionsPerRule: 10,
5323
+ options: 50,
5324
+ label: 200,
5325
+ option: 100,
5326
+ message: 500,
5327
+ textAnswer: 1e3,
5328
+ problems: 50,
5329
+ formsPerOrganization: 50
5330
+ };
5331
+
5332
+ // src/routing/validate-structure.ts
5333
+ var ID = /^[A-Za-z][A-Za-z0-9_-]{0,39}$/;
5334
+ var QUESTION_TYPES = ["select", "radio", "checkbox", "text", "number"];
5335
+ var NO_VALUE = ["is_answered", "is_empty"];
5336
+ var OPERATORS_BY_TYPE = {
5337
+ select: ["equals", "not_equals", "in", "is_answered", "is_empty"],
5338
+ radio: ["equals", "not_equals", "in", "is_answered", "is_empty"],
5339
+ checkbox: ["contains", "not_contains", "is_answered", "is_empty"],
5340
+ text: ["equals", "not_equals", "contains", "not_contains", "is_answered", "is_empty"],
5341
+ number: ["equals", "not_equals", "gt", "gte", "lt", "lte", "is_answered", "is_empty"]
5342
+ };
5343
+ var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5344
+ var isText = (value, max) => typeof value === "string" && value.trim().length > 0 && value.length <= max && !value.includes("\0");
5345
+ function checkQuestions(input, problems) {
5346
+ if (!Array.isArray(input) || input.length === 0) {
5347
+ problems.push({ path: "questions", message: "Add at least one question" });
5348
+ return [];
5349
+ }
5350
+ if (input.length > LIMITS.questions) problems.push({ path: "questions", message: `At most ${LIMITS.questions} questions` });
5351
+ const seen = /* @__PURE__ */ new Set();
5352
+ const questions = [];
5353
+ input.slice(0, LIMITS.questions).forEach((raw, i) => {
5354
+ const at = `questions[${i}]`;
5355
+ if (!isObject(raw)) return void problems.push({ path: at, message: "A question must be an object" });
5356
+ const { id, label, type, required, options } = raw;
5357
+ if (typeof id !== "string" || !ID.test(id)) problems.push({ path: `${at}.id`, message: "The id must start with a letter and use only letters, numbers, - and _ (40 characters at most)" });
5358
+ else if (seen.has(id)) problems.push({ path: `${at}.id`, message: `Another question already uses the id "${id}"` });
5359
+ else seen.add(id);
5360
+ if (!isText(label, LIMITS.label)) problems.push({ path: `${at}.label`, message: `A label of 1 to ${LIMITS.label} characters is required` });
5361
+ if (!QUESTION_TYPES.includes(type)) problems.push({ path: `${at}.type`, message: `The type must be one of ${QUESTION_TYPES.join(", ")}` });
5362
+ if (required !== void 0 && typeof required !== "boolean") problems.push({ path: `${at}.required`, message: "required must be true or false" });
5363
+ const choice = type === "select" || type === "radio" || type === "checkbox";
5364
+ let cleanOptions;
5365
+ if (choice) {
5366
+ if (!Array.isArray(options) || options.length < 2 || options.length > LIMITS.options) {
5367
+ problems.push({ path: `${at}.options`, message: `A choice question needs 2 to ${LIMITS.options} options` });
5368
+ } else if (!options.every((o) => isText(o, LIMITS.option))) {
5369
+ problems.push({ path: `${at}.options`, message: `Each option must be 1 to ${LIMITS.option} characters` });
5370
+ } else if (new Set(options).size !== options.length) {
5371
+ problems.push({ path: `${at}.options`, message: "Options must all be different" });
5372
+ } else cleanOptions = options;
5373
+ } else if (options !== void 0) {
5374
+ problems.push({ path: `${at}.options`, message: "Only choice questions have options" });
5375
+ }
5376
+ if (typeof id === "string" && typeof label === "string" && QUESTION_TYPES.includes(type)) {
5377
+ questions.push({ id, label: label.trim(), type, required: required === true, ...cleanOptions ? { options: cleanOptions } : {} });
5378
+ }
5379
+ });
5380
+ return questions;
5381
+ }
5382
+ function checkValue(question, condition, at, problems) {
5383
+ const { operator, value } = condition;
5384
+ if (NO_VALUE.includes(operator)) {
5385
+ if (value !== void 0) problems.push({ path: `${at}.value`, message: `${String(operator)} takes no value` });
5386
+ return void 0;
5387
+ }
5388
+ if (value === void 0) {
5389
+ problems.push({ path: `${at}.value`, message: "A value is required" });
5390
+ return void 0;
5391
+ }
5392
+ if (question.type === "number") {
5393
+ if (typeof value !== "number" || !Number.isFinite(value)) problems.push({ path: `${at}.value`, message: "The value must be a number" });
5394
+ else return value;
5395
+ return void 0;
5396
+ }
5397
+ if (question.type === "text") {
5398
+ if (!isText(value, LIMITS.option * 2)) problems.push({ path: `${at}.value`, message: "The value must be a text of 1 to 200 characters" });
5399
+ else return value;
5400
+ return void 0;
5401
+ }
5402
+ const options = question.options ?? [];
5403
+ if (operator === "in") {
5404
+ if (!Array.isArray(value) || value.length === 0 || !value.every((v) => typeof v === "string" && options.includes(v))) {
5405
+ problems.push({ path: `${at}.value`, message: "The value must be a list of this question's options" });
5406
+ return void 0;
5407
+ }
5408
+ return value;
5409
+ }
5410
+ if (typeof value !== "string" || !options.includes(value)) {
5411
+ problems.push({ path: `${at}.value`, message: "The value must be one of this question's options" });
5412
+ return void 0;
5413
+ }
5414
+ return value;
5415
+ }
5416
+ function checkDestination(raw, at, problems) {
5417
+ if (!isObject(raw)) {
5418
+ problems.push({ path: at, message: "Say where to send the client" });
5419
+ return null;
5420
+ }
5421
+ const { typeId, calendarId } = raw;
5422
+ const okType = typeId === void 0 || typeof typeId === "string" && typeId.length > 0 && typeId.length <= 100;
5423
+ const okCalendar = calendarId === void 0 || typeof calendarId === "string" && calendarId.length > 0 && calendarId.length <= 100;
5424
+ if (!okType || !okCalendar) {
5425
+ problems.push({ path: at, message: "typeId and calendarId must be ids" });
5426
+ return null;
5427
+ }
5428
+ if (typeId === void 0 && calendarId === void 0) {
5429
+ problems.push({ path: at, message: "Name an appointment type, a calendar, or both" });
5430
+ return null;
5431
+ }
5432
+ return { ...typeId !== void 0 ? { typeId } : {}, ...calendarId !== void 0 ? { calendarId } : {} };
5433
+ }
5434
+ function checkRules(input, questions, problems) {
5435
+ if (!Array.isArray(input) || input.length === 0) {
5436
+ problems.push({ path: "rules", message: "Add at least one rule" });
5437
+ return [];
5438
+ }
5439
+ if (input.length > LIMITS.rules) problems.push({ path: "rules", message: `At most ${LIMITS.rules} rules` });
5440
+ const byId = new Map(questions.map((q) => [q.id, q]));
5441
+ const written = new Set(input.flatMap((r) => isObject(r) && typeof r.id === "string" ? [r.id] : []));
5442
+ const seen = /* @__PURE__ */ new Set();
5443
+ const rules = [];
5444
+ input.slice(0, LIMITS.rules).forEach((raw, i) => {
5445
+ const at = `rules[${i}]`;
5446
+ if (!isObject(raw)) return void problems.push({ path: at, message: "A rule must be an object" });
5447
+ let id = typeof raw.id === "string" && ID.test(raw.id) ? raw.id : null;
5448
+ if (raw.id !== void 0 && id === null) problems.push({ path: `${at}.id`, message: "The id must start with a letter and use only letters, numbers, - and _" });
5449
+ if (id === null) {
5450
+ id = `rule_${i + 1}`;
5451
+ while (written.has(id)) id = `${id}_auto`;
5452
+ }
5453
+ if (seen.has(id)) problems.push({ path: `${at}.id`, message: `Another rule already uses the id "${id}"` });
5454
+ seen.add(id);
5455
+ if (raw.label !== void 0 && !isText(raw.label, LIMITS.label)) problems.push({ path: `${at}.label`, message: `A label must be 1 to ${LIMITS.label} characters` });
5456
+ const match = raw.match === void 0 ? "all" : raw.match;
5457
+ if (match !== "all" && match !== "any") problems.push({ path: `${at}.match`, message: 'match must be "all" or "any"' });
5458
+ const conditions = [];
5459
+ if (!Array.isArray(raw.conditions) || raw.conditions.length === 0 || raw.conditions.length > LIMITS.conditionsPerRule) {
5460
+ problems.push({ path: `${at}.conditions`, message: `A rule needs 1 to ${LIMITS.conditionsPerRule} conditions` });
5461
+ } else {
5462
+ raw.conditions.forEach((c, j) => {
5463
+ const cat = `${at}.conditions[${j}]`;
5464
+ if (!isObject(c)) return void problems.push({ path: cat, message: "A condition must be an object" });
5465
+ const question = typeof c.questionId === "string" ? byId.get(c.questionId) : void 0;
5466
+ if (!question) return void problems.push({ path: `${cat}.questionId`, message: "This names a question the form does not have" });
5467
+ if (!OPERATORS_BY_TYPE[question.type].includes(c.operator)) {
5468
+ return void problems.push({ path: `${cat}.operator`, message: `A ${question.type} question allows: ${OPERATORS_BY_TYPE[question.type].join(", ")}` });
5469
+ }
5470
+ const value = checkValue(question, c, cat, problems);
5471
+ conditions.push({ questionId: question.id, operator: c.operator, ...value !== void 0 ? { value } : {} });
5472
+ });
5473
+ }
5474
+ const destination = checkDestination(raw.destination, `${at}.destination`, problems);
5475
+ if (destination && (match === "all" || match === "any")) {
5476
+ rules.push({ id, ...typeof raw.label === "string" ? { label: raw.label.trim() } : {}, match, conditions, destination });
5477
+ }
5478
+ });
5479
+ return rules;
5480
+ }
5481
+ function checkFallback(raw, problems) {
5482
+ if (!isObject(raw)) {
5483
+ problems.push({ path: "fallback", message: "Say what happens when no rule matches" });
5484
+ return null;
5485
+ }
5486
+ if (raw.kind === "MESSAGE") {
5487
+ if (!isText(raw.message, LIMITS.message)) {
5488
+ problems.push({ path: "fallback.message", message: `A message of 1 to ${LIMITS.message} characters is required` });
5489
+ return null;
5490
+ }
5491
+ return { kind: "MESSAGE", message: raw.message.trim() };
5492
+ }
5493
+ if (raw.kind === "DESTINATION") {
5494
+ const destination = checkDestination(raw.destination, "fallback.destination", problems);
5495
+ return destination ? { kind: "DESTINATION", destination } : null;
5496
+ }
5497
+ problems.push({ path: "fallback.kind", message: 'kind must be "DESTINATION" or "MESSAGE"' });
5498
+ return null;
5499
+ }
5500
+ function validateRoutingStructure(input) {
5501
+ const problems = [];
5502
+ if (!isObject(input)) return { ok: false, problems: [{ path: "", message: "A routing form must be an object" }] };
5503
+ const questions = checkQuestions(input.questions, problems);
5504
+ const rules = checkRules(input.rules, questions, problems);
5505
+ const fallback = checkFallback(input.fallback, problems);
5506
+ if (problems.length > 0 || !fallback) return { ok: false, problems: problems.slice(0, LIMITS.problems) };
5507
+ return { ok: true, value: { questions, rules, fallback } };
5508
+ }
5509
+
5510
+ // src/routing/validate-destinations.ts
5511
+ function placesOf(definition) {
5512
+ const places = definition.rules.map((rule, i) => ({ path: `rules[${i}].destination`, destination: rule.destination }));
5513
+ if (definition.fallback.kind === "DESTINATION") places.push({ path: "fallback.destination", destination: definition.fallback.destination });
5514
+ return places;
5515
+ }
5516
+ async function validateRoutingDestinations(db, organizationId, definition) {
5517
+ const places = placesOf(definition);
5518
+ const typeIds = [...new Set(places.flatMap((p) => p.destination.typeId ? [p.destination.typeId] : []))];
5519
+ const calendarIds = [...new Set(places.flatMap((p) => p.destination.calendarId ? [p.destination.calendarId] : []))];
5520
+ const scope = [{ organizationId }, { organizationId: null }];
5521
+ const [types, calendars] = await Promise.all([
5522
+ typeIds.length ? db.appointmentType.findMany({ where: { id: { in: typeIds }, isActive: true, OR: scope }, select: { id: true } }) : [],
5523
+ calendarIds.length ? db.schedulingCalendar.findMany({ where: { id: { in: calendarIds }, isActive: true, OR: scope }, select: { id: true } }) : []
5524
+ ]);
5525
+ const liveTypes = new Set(types.map((t) => t.id));
5526
+ const liveCalendars = new Set(calendars.map((c) => c.id));
5527
+ const problems = [];
5528
+ const pairs = [];
5529
+ for (const { path, destination } of places) {
5530
+ const typeOk = !destination.typeId || liveTypes.has(destination.typeId);
5531
+ const calendarOk = !destination.calendarId || liveCalendars.has(destination.calendarId);
5532
+ if (!typeOk) problems.push({ path: `${path}.typeId`, message: "This appointment type does not exist here or is switched off" });
5533
+ if (!calendarOk) problems.push({ path: `${path}.calendarId`, message: "This calendar does not exist here or is switched off" });
5534
+ if (typeOk && calendarOk && destination.typeId && destination.calendarId) pairs.push({ path, destination });
5535
+ }
5536
+ if (pairs.length > 0) {
5537
+ const links = await db.appointmentTypeCalendar.findMany({
5538
+ where: { OR: pairs.map((p) => ({ appointmentTypeId: p.destination.typeId, calendarId: p.destination.calendarId })) },
5539
+ select: { appointmentTypeId: true, calendarId: true }
5540
+ });
5541
+ const linked = new Set(links.map((l) => `${l.appointmentTypeId}:${l.calendarId}`));
5542
+ for (const { path, destination } of pairs) {
5543
+ if (!linked.has(`${destination.typeId}:${destination.calendarId}`)) {
5544
+ problems.push({ path, message: "This appointment type is not offered on this calendar" });
5545
+ }
5546
+ }
5547
+ }
5548
+ return problems;
5549
+ }
5550
+
5551
+ // src/routing/evaluate.ts
5552
+ var blank = (value) => value === void 0 || value === null || value === "" || Array.isArray(value) && value.length === 0;
5553
+ function checkAnswers(questions, input) {
5554
+ const problems = [];
5555
+ const raw = typeof input === "object" && input !== null && !Array.isArray(input) ? input : {};
5556
+ if (input !== void 0 && raw !== input) problems.push({ path: "answers", message: "Answers must be an object keyed by question id" });
5557
+ const known = new Set(questions.map((q) => q.id));
5558
+ for (const key of Object.keys(raw)) if (!known.has(key)) problems.push({ path: `answers.${key}`, message: "The form does not ask this question" });
5559
+ const answers = /* @__PURE__ */ Object.create(null);
5560
+ for (const q of questions) {
5561
+ const at = `answers.${q.id}`;
5562
+ const value = Object.prototype.hasOwnProperty.call(raw, q.id) ? raw[q.id] : void 0;
5563
+ if (blank(value)) {
5564
+ if (q.required) problems.push({ path: at, message: "This question needs an answer" });
5565
+ continue;
5566
+ }
5567
+ if (q.type === "select" || q.type === "radio") {
5568
+ if (typeof value !== "string" || !q.options?.includes(value)) problems.push({ path: at, message: "Pick one of the offered options" });
5569
+ else answers[q.id] = value;
5570
+ } else if (q.type === "checkbox") {
5571
+ if (!Array.isArray(value) || !value.every((v) => typeof v === "string" && q.options?.includes(v)) || new Set(value).size !== value.length) {
5572
+ problems.push({ path: at, message: "Send a list of offered options, each once" });
5573
+ } else answers[q.id] = value;
5574
+ } else if (q.type === "number") {
5575
+ if (typeof value !== "number" || !Number.isFinite(value)) problems.push({ path: at, message: "The answer must be a number" });
5576
+ else answers[q.id] = value;
5577
+ } else if (typeof value !== "string" || value.length > LIMITS.textAnswer) {
5578
+ problems.push({ path: at, message: `The answer must be a text of at most ${LIMITS.textAnswer} characters` });
5579
+ } else answers[q.id] = value;
5580
+ }
5581
+ return problems.length > 0 ? { ok: false, problems: problems.slice(0, LIMITS.problems) } : { ok: true, answers };
5582
+ }
5583
+ function holds(condition, answers) {
5584
+ const answer = answers[condition.questionId];
5585
+ const { operator, value } = condition;
5586
+ if (operator === "is_empty") return blank(answer);
5587
+ if (operator === "is_answered") return !blank(answer);
5588
+ if (blank(answer)) return false;
5589
+ if (typeof answer === "number") {
5590
+ if (typeof value !== "number") return false;
5591
+ return { equals: answer === value, not_equals: answer !== value, gt: answer > value, gte: answer >= value, lt: answer < value, lte: answer <= value }[operator] ?? false;
5592
+ }
5593
+ if (Array.isArray(answer)) {
5594
+ if (typeof value !== "string") return false;
5595
+ return operator === "contains" ? answer.includes(value) : operator === "not_contains" ? !answer.includes(value) : false;
5596
+ }
5597
+ if (operator === "in") return Array.isArray(value) && value.includes(answer);
5598
+ if (typeof value !== "string") return false;
5599
+ const a = answer;
5600
+ switch (operator) {
5601
+ case "equals":
5602
+ return a === value;
5603
+ case "not_equals":
5604
+ return a !== value;
5605
+ case "contains":
5606
+ return a.toLowerCase().includes(value.toLowerCase());
5607
+ case "not_contains":
5608
+ return !a.toLowerCase().includes(value.toLowerCase());
5609
+ default:
5610
+ return false;
5611
+ }
5612
+ }
5613
+ function matchingRules(definition, answers) {
5614
+ return definition.rules.filter(
5615
+ (rule) => rule.match === "any" ? rule.conditions.some((c) => holds(c, answers)) : rule.conditions.every((c) => holds(c, answers))
5616
+ );
5617
+ }
5618
+
5619
+ // src/routing/crud.ts
5620
+ var SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
5621
+ var FULL = { id: true, name: true, slug: true, description: true, isActive: true, questions: true, rules: true, fallback: true, createdAt: true, updatedAt: true };
5622
+ function invalid(problems) {
5623
+ return new SchedulingValidationError("The routing form has problems", "SCHED_1200", { errors: problems });
5624
+ }
5625
+ function view(row) {
5626
+ return { ...row, questions: row.questions, rules: row.rules, fallback: row.fallback };
5627
+ }
5628
+ async function check(db, organizationId, input, options) {
5629
+ const problems = [];
5630
+ const name = typeof input.name === "string" ? input.name.trim() : "";
5631
+ if (name.length < 1 || name.length > 100 || name.includes("\0")) problems.push({ path: "name", message: "A name of 1 to 100 characters is required" });
5632
+ if (typeof input.slug !== "string" || !SLUG.test(input.slug) || input.slug.length > 60) {
5633
+ problems.push({ path: "slug", message: "The slug must be lower-case words joined by dashes, 60 characters at most" });
5634
+ } else {
5635
+ const taken = await db.routingForm.count({ where: { slug: input.slug, organizationId: { not: organizationId } } });
5636
+ if (taken > 0) problems.push({ path: "slug", message: "That slug is already in use; choose another" });
5637
+ }
5638
+ const description = typeof input.description === "string" ? input.description.trim() || null : null;
5639
+ if (description && (description.length > 500 || description.includes("\0"))) problems.push({ path: "description", message: "The description is at most 500 characters" });
5640
+ const structure = validateRoutingStructure({ questions: input.questions, rules: input.rules, fallback: input.fallback });
5641
+ if (!structure.ok) problems.push(...structure.problems);
5642
+ else if (options.checkDestinations) problems.push(...await validateRoutingDestinations(db, organizationId, structure.value));
5643
+ if (problems.length > 0 || !structure.ok) throw invalid(problems.slice(0, LIMITS.problems));
5644
+ return { definition: structure.value, name, slug: input.slug, description };
5645
+ }
5646
+ async function createRoutingForm(db, organizationId, input) {
5647
+ const { definition, name, slug, description } = await check(db, organizationId, input, { checkDestinations: true });
5648
+ const existing = await db.routingForm.count({ where: { organizationId } });
5649
+ if (existing >= LIMITS.formsPerOrganization) {
5650
+ throw new SchedulingValidationError(`An organization can have at most ${LIMITS.formsPerOrganization} routing forms`, "SCHED_1204", { organizationId });
5651
+ }
5652
+ try {
5653
+ const row = await db.routingForm.create({
5654
+ data: {
5655
+ organizationId,
5656
+ name,
5657
+ slug,
5658
+ description,
5659
+ isActive: input.isActive ?? true,
5660
+ questions: definition.questions,
5661
+ rules: definition.rules,
5662
+ fallback: definition.fallback
5663
+ },
5664
+ select: FULL
5665
+ });
5666
+ return view(row);
5667
+ } catch (error) {
5668
+ if (error.code === "P2002") throw new SchedulingValidationError("That slug is already used by another form", "SCHED_1202", { slug });
5669
+ throw error;
5670
+ }
5671
+ }
5672
+ async function getRoutingForm(db, organizationId, id) {
5673
+ const row = await db.routingForm.findFirst({ where: { id, organizationId }, select: FULL });
5674
+ if (!row) throw new SchedulingNotFoundError("Routing form not found", "SCHED_1201", { id });
5675
+ return view(row);
5676
+ }
5677
+ async function listRoutingForms(db, organizationId) {
5678
+ return db.routingForm.findMany({
5679
+ where: { organizationId },
5680
+ orderBy: { name: "asc" },
5681
+ select: { id: true, name: true, slug: true, description: true, isActive: true, updatedAt: true }
5682
+ });
5683
+ }
5684
+ async function updateRoutingForm(db, organizationId, id, patch) {
5685
+ const current = await getRoutingForm(db, organizationId, id);
5686
+ const merged = {
5687
+ name: patch.name ?? current.name,
5688
+ slug: patch.slug ?? current.slug,
5689
+ description: patch.description === void 0 ? current.description : patch.description,
5690
+ isActive: patch.isActive ?? current.isActive,
5691
+ questions: patch.questions ?? current.questions,
5692
+ rules: patch.rules ?? current.rules,
5693
+ fallback: patch.fallback ?? current.fallback
5694
+ };
5695
+ const changesRouting = patch.questions !== void 0 || patch.rules !== void 0 || patch.fallback !== void 0;
5696
+ const { definition, name, slug, description } = await check(db, organizationId, merged, { checkDestinations: changesRouting });
5697
+ try {
5698
+ const updated = await db.routingForm.updateMany({
5699
+ where: { id, organizationId },
5700
+ data: {
5701
+ name,
5702
+ slug,
5703
+ description,
5704
+ isActive: merged.isActive,
5705
+ questions: definition.questions,
5706
+ rules: definition.rules,
5707
+ fallback: definition.fallback
5708
+ }
5709
+ });
5710
+ if (updated.count === 0) throw new SchedulingNotFoundError("Routing form not found", "SCHED_1201", { id });
5711
+ } catch (error) {
5712
+ if (error.code === "P2002") throw new SchedulingValidationError("That slug is already used by another form", "SCHED_1202", { slug });
5713
+ throw error;
5714
+ }
5715
+ return getRoutingForm(db, organizationId, id);
5716
+ }
5717
+ async function deleteRoutingForm(db, organizationId, id) {
5718
+ const removed = await db.routingForm.deleteMany({ where: { id, organizationId } });
5719
+ if (removed.count === 0) throw new SchedulingNotFoundError("Routing form not found", "SCHED_1201", { id });
5720
+ }
5721
+
5722
+ // src/routing/route.ts
5723
+ var UNAVAILABLE = "Online booking is not available for this choice right now. Please contact us to book.";
5724
+ async function findForm(db, organizationId, slug) {
5725
+ const select = { organizationId: true, name: true, slug: true, description: true, questions: true, rules: true, fallback: true };
5726
+ if (organizationId) return db.routingForm.findFirst({ where: { organizationId, slug, isActive: true }, select });
5727
+ const found = await db.routingForm.findMany({ where: { slug, isActive: true }, take: 2, select });
5728
+ return found.length === 1 ? found[0] : null;
5729
+ }
5730
+ async function load(db, organizationId, slug) {
5731
+ const row = await findForm(db, organizationId, slug);
5732
+ if (!row) throw new SchedulingNotFoundError("Routing form not found", "SCHED_1201", { slug });
5733
+ return row;
5734
+ }
5735
+ async function getPublicRoutingForm(db, input) {
5736
+ const row = await load(db, input.organizationId, input.slug);
5737
+ return { name: row.name, slug: row.slug, description: row.description, questions: row.questions };
5738
+ }
5739
+ async function resolveDestination(db, organizationId, destination) {
5740
+ const scope = [{ organizationId }, { organizationId: null }];
5741
+ const [type, calendar] = await Promise.all([
5742
+ destination.typeId ? db.appointmentType.findFirst({ where: { id: destination.typeId, isActive: true, OR: scope }, select: { id: true, slug: true, name: true } }) : null,
5743
+ destination.calendarId ? db.schedulingCalendar.findFirst({ where: { id: destination.calendarId, isActive: true, OR: scope }, select: { id: true, slug: true, name: true } }) : null
5744
+ ]);
5745
+ if (destination.typeId && !type || destination.calendarId && !calendar) return null;
5746
+ if (type && calendar) {
5747
+ const link = await db.appointmentTypeCalendar.findUnique({
5748
+ where: { appointmentTypeId_calendarId: { appointmentTypeId: type.id, calendarId: calendar.id } },
5749
+ select: { calendarId: true }
5750
+ });
5751
+ if (!link) return null;
5752
+ }
5753
+ return {
5754
+ typeId: type?.id ?? null,
5755
+ typeSlug: type?.slug ?? null,
5756
+ typeName: type?.name ?? null,
5757
+ calendarId: calendar?.id ?? null,
5758
+ calendarSlug: calendar?.slug ?? null,
5759
+ calendarName: calendar?.name ?? null
5760
+ };
5761
+ }
5762
+ async function decide(db, organizationId, definition, answers) {
5763
+ const checked = checkAnswers(definition.questions, answers);
5764
+ if (!checked.ok) throw new SchedulingValidationError("The answers do not fit the form", "SCHED_1203", { errors: checked.problems });
5765
+ for (const rule of matchingRules(definition, checked.answers)) {
5766
+ const destination = await resolveDestination(db, organizationId, rule.destination);
5767
+ if (destination) return { destination, message: null, matchedRuleId: rule.id, usedFallback: false };
5768
+ }
5769
+ if (definition.fallback.kind === "DESTINATION") {
5770
+ const destination = await resolveDestination(db, organizationId, definition.fallback.destination);
5771
+ return { destination, message: destination ? null : UNAVAILABLE, matchedRuleId: null, usedFallback: true };
5772
+ }
5773
+ return { destination: null, message: definition.fallback.message, matchedRuleId: null, usedFallback: true };
5774
+ }
5775
+ async function routeClient(db, input) {
5776
+ const row = await load(db, input.organizationId, input.slug);
5777
+ return decide(db, row.organizationId, row, input.answers);
5778
+ }
5779
+ async function testRoutingForm(db, input) {
5780
+ const row = await db.routingForm.findFirst({
5781
+ where: { id: input.id, organizationId: input.organizationId },
5782
+ select: { questions: true, rules: true, fallback: true }
5783
+ });
5784
+ if (!row) throw new SchedulingNotFoundError("Routing form not found", "SCHED_1201", { id: input.id });
5785
+ const definition = row;
5786
+ const outcome = await decide(db, input.organizationId, definition, input.answers);
5787
+ const checked = checkAnswers(definition.questions, input.answers);
5788
+ const allMatchedRuleIds = checked.ok ? matchingRules(definition, checked.answers).map((r) => r.id) : [];
5789
+ return { ...outcome, allMatchedRuleIds };
5790
+ }
5791
+
5792
+ // src/privacy/subject.ts
5793
+ var import_node_crypto6 = require("crypto");
5794
+ var EMAIL2 = /^[^\s@]+@[^\s@]+$/;
5795
+ function invalid2(reason) {
5796
+ return new SchedulingValidationError(`Say whose data this is: ${reason}`, "SCHED_1300", { reason });
5797
+ }
5798
+ function parseSubject(input) {
5799
+ let email2 = null;
5800
+ let clientId = null;
5801
+ if (input.email !== void 0 && input.email !== null) {
5802
+ if (typeof input.email !== "string") throw invalid2("the email must be text");
5803
+ const trimmed = input.email.trim().toLowerCase();
5804
+ if (trimmed.length > 254 || !EMAIL2.test(trimmed)) throw invalid2("the email is not a single valid address");
5805
+ email2 = trimmed;
5806
+ }
5807
+ if (input.clientId !== void 0 && input.clientId !== null) {
5808
+ if (typeof input.clientId !== "string") throw invalid2("the client id must be text");
5809
+ const trimmed = input.clientId.trim();
5810
+ if (trimmed.length < 1 || trimmed.length > 200) throw invalid2("the client id must be 1 to 200 characters");
5811
+ clientId = trimmed;
5812
+ }
5813
+ if (!email2 && !clientId) throw invalid2("send an email address, a client id, or both");
5814
+ return { email: email2, clientId };
5815
+ }
5816
+ function subjectHashes(organizationId, subject) {
5817
+ const identifiers = [...subject.emails, ...subject.clientId ? [`client:${subject.clientId}`] : []];
5818
+ return identifiers.map((identifier) => (0, import_node_crypto6.createHash)("sha256").update(`${organizationId}
5819
+ ${identifier}`).digest("hex"));
5820
+ }
5821
+ async function resolveSubject(db, organizationId, parsed) {
5822
+ const emails = new Set(parsed.email ? [parsed.email] : []);
5823
+ if (parsed.clientId) {
5824
+ const [bookings, series] = await Promise.all([
5825
+ db.appointment.findMany({ where: { clientId: parsed.clientId, calendar: { organizationId } }, select: { clientEmail: true } }),
5826
+ db.recurringSeries.findMany({ where: { clientId: parsed.clientId, organizationId }, select: { clientEmail: true } })
5827
+ ]);
5828
+ for (const row of [...bookings, ...series]) emails.add(row.clientEmail.trim().toLowerCase());
5829
+ }
5830
+ return { emails: [...emails], clientId: parsed.clientId };
5831
+ }
5832
+
5833
+ // src/privacy/audit.ts
5834
+ async function recordPrivacyRequest(db, input) {
5835
+ await db.dataSubjectRequest.create({
5836
+ data: {
5837
+ organizationId: input.organizationId,
5838
+ kind: input.kind,
5839
+ subjectHashes: subjectHashes(input.organizationId, input.subject),
5840
+ requestedBy: input.requestedBy,
5841
+ counts: { ...input.counts },
5842
+ createdAt: input.now
5843
+ }
5844
+ });
5845
+ }
5846
+ async function listPrivacyRequests(db, input) {
5847
+ const where = { organizationId: input.organizationId };
5848
+ const [requests, total] = await Promise.all([
5849
+ db.dataSubjectRequest.findMany({
5850
+ where,
5851
+ orderBy: { createdAt: "desc" },
5852
+ take: Math.min(input.limit ?? 50, 200),
5853
+ skip: input.offset ?? 0,
5854
+ select: { id: true, kind: true, requestedBy: true, counts: true, createdAt: true }
5855
+ }),
5856
+ db.dataSubjectRequest.count({ where })
5857
+ ]);
5858
+ return { requests, total };
5859
+ }
5860
+
5861
+ // src/privacy/collect.ts
5862
+ var APPOINTMENT = {
5863
+ id: true,
5864
+ startTime: true,
5865
+ endTime: true,
5866
+ duration: true,
5867
+ timezone: true,
5868
+ status: true,
5869
+ isGroup: true,
5870
+ clientName: true,
5871
+ clientEmail: true,
5872
+ clientPhone: true,
5873
+ clientId: true,
5874
+ cancelledAt: true,
5875
+ cancelledBy: true,
5876
+ cancelReason: true,
5877
+ rescheduledFrom: true,
5878
+ rescheduleCount: true,
5879
+ intakeResponses: true,
5880
+ notes: true,
5881
+ staffNotes: true,
5882
+ location: true,
5883
+ meetingUrl: true,
5884
+ paymentStatus: true,
5885
+ paymentAmount: true,
5886
+ depositAmount: true,
5887
+ tipAmount: true,
5888
+ paymentProvider: true,
5889
+ paymentId: true,
5890
+ balancePaymentId: true,
5891
+ couponCode: true,
5892
+ discountAmount: true,
5893
+ cancellationFeeAmount: true,
5894
+ refundAmount: true,
5895
+ refundStatus: true,
5896
+ recurringId: true,
5897
+ recurringIndex: true,
5898
+ packagePurchaseId: true,
5899
+ createdAt: true,
5900
+ updatedAt: true,
5901
+ calendar: { select: { name: true } },
5902
+ type: { select: { name: true } }
5903
+ };
5904
+ var NOTIFICATION = {
5905
+ id: true,
5906
+ appointmentId: true,
5907
+ channel: true,
5908
+ trigger: true,
5909
+ recipient: true,
5910
+ subject: true,
5911
+ body: true,
5912
+ status: true,
5913
+ scheduledFor: true,
5914
+ sentAt: true,
5915
+ createdAt: true
5916
+ };
5917
+ var WAITLIST = {
5918
+ id: true,
5919
+ typeId: true,
5920
+ calendarId: true,
5921
+ day: true,
5922
+ slotStart: true,
5923
+ timezone: true,
5924
+ clientName: true,
5925
+ clientEmail: true,
5926
+ clientPhone: true,
5927
+ status: true,
5928
+ offerSlotStart: true,
5929
+ offerExpiresAt: true,
5930
+ offeredAt: true,
5931
+ bookedAppointmentId: true,
5932
+ createdAt: true
5933
+ };
5934
+ var PURCHASE = {
5935
+ id: true,
5936
+ packageId: true,
5937
+ clientEmail: true,
5938
+ clientName: true,
5939
+ sessionsTotal: true,
5940
+ sessionsUsed: true,
5941
+ expiresAt: true,
5942
+ purchasedAt: true,
5943
+ status: true,
5944
+ paymentId: true,
5945
+ notes: true,
5946
+ pricePaidCents: true,
5947
+ createdAt: true
5948
+ };
5949
+ var SERIES = {
5950
+ id: true,
5951
+ calendarId: true,
5952
+ typeId: true,
5953
+ frequency: true,
5954
+ occurrences: true,
5955
+ startTimeLocal: true,
5956
+ durationMins: true,
5957
+ timezone: true,
5958
+ endsAt: true,
5959
+ clientEmail: true,
5960
+ clientName: true,
5961
+ clientPhone: true,
5962
+ clientId: true,
5963
+ notes: true,
5964
+ status: true,
5965
+ createdAt: true
5966
+ };
5967
+ var DELIVERY = { id: true, eventId: true, eventType: true, body: true, status: true, createdAt: true };
5968
+ var emailIs = (field, emails) => emails.map((email2) => ({ [field]: { equals: email2, mode: "insensitive" } }));
5969
+ var escape = (text2) => text2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5970
+ function mentions(body, emails, ids) {
5971
+ const lower = body.toLowerCase();
5972
+ const whole = emails.some((email2) => new RegExp(`(?<![a-z0-9._%+-])${escape(email2.toLowerCase())}(?![a-z0-9_-]|\\.[a-z0-9])`).test(lower));
5973
+ return whole || ids.some((id) => body.includes(`"${id}"`));
5974
+ }
5975
+ async function collectSubjectRows(db, organizationId, subject) {
5976
+ const person = (field) => [...emailIs(field, subject.emails), ...subject.clientId ? [{ clientId: subject.clientId }] : []];
5977
+ const byEmail = emailIs("clientEmail", subject.emails);
5978
+ const none = subject.emails.length === 0 && !subject.clientId;
5979
+ const appointments = none ? [] : await db.appointment.findMany({
5980
+ where: { calendar: { organizationId }, OR: person("clientEmail") },
5981
+ orderBy: { startTime: "asc" },
5982
+ select: APPOINTMENT
5983
+ });
5984
+ const appointmentIds = appointments.map((row) => row.id);
5985
+ const [notifications, waitlistEntries, packagePurchases, recurringSeries] = await Promise.all([
5986
+ appointmentIds.length ? db.scheduledNotification.findMany({ where: { appointmentId: { in: appointmentIds } }, orderBy: { createdAt: "asc" }, select: NOTIFICATION }) : [],
5987
+ byEmail.length ? db.waitlistEntry.findMany({ where: { organizationId, OR: byEmail }, orderBy: { createdAt: "asc" }, select: WAITLIST }) : [],
5988
+ byEmail.length ? db.packagePurchase.findMany({ where: { organizationId, OR: byEmail }, orderBy: { createdAt: "asc" }, select: PURCHASE }) : [],
5989
+ none ? [] : db.recurringSeries.findMany({ where: { organizationId, OR: person("clientEmail") }, orderBy: { createdAt: "asc" }, select: SERIES })
5990
+ ]);
5991
+ const terms = [...subject.emails, ...appointmentIds.map((id) => `"${id}"`), ...waitlistEntries.map((row) => `"${row.id}"`)];
5992
+ const deliveries = /* @__PURE__ */ new Map();
5993
+ for (let start = 0; start < terms.length; start += 40) {
5994
+ const chunk = terms.slice(start, start + 40);
5995
+ const rows = await db.webhookDelivery.findMany({
5996
+ where: { organizationId, OR: chunk.map((term) => ({ body: { contains: term, mode: "insensitive" } })) },
5997
+ orderBy: { createdAt: "asc" },
5998
+ select: DELIVERY
5999
+ });
6000
+ for (const row of rows) if (mentions(row.body, subject.emails, [...appointmentIds, ...waitlistEntries.map((entry4) => entry4.id)])) deliveries.set(row.id, row);
6001
+ }
6002
+ return { appointments, notifications, waitlistEntries, packagePurchases, recurringSeries, webhookDeliveries: [...deliveries.values()] };
6003
+ }
6004
+ function countRows(rows) {
6005
+ return {
6006
+ appointments: rows.appointments.length,
6007
+ notifications: rows.notifications.length,
6008
+ waitlistEntries: rows.waitlistEntries.length,
6009
+ packagePurchases: rows.packagePurchases.length,
6010
+ recurringSeries: rows.recurringSeries.length,
6011
+ webhookDeliveries: rows.webhookDeliveries.length
6012
+ };
6013
+ }
6014
+
6015
+ // src/privacy/export.ts
6016
+ function withoutOfferToken(body) {
6017
+ try {
6018
+ const parsed = JSON.parse(body);
6019
+ if (parsed?.data?.offer && "token" in parsed.data.offer) {
6020
+ delete parsed.data.offer.token;
6021
+ return JSON.stringify(parsed);
6022
+ }
6023
+ } catch {
6024
+ }
6025
+ return body;
6026
+ }
6027
+ function withoutLinks(body) {
6028
+ return body.replace(/\/appt\/[A-Za-z0-9_-]+/g, "/appt/[removed]").replace(/([?&]token=)[A-Za-z0-9_-]+/g, "$1[removed]");
6029
+ }
6030
+ async function exportSubject(db, input) {
6031
+ const parsed = parseSubject(input);
6032
+ const now = input.now ?? /* @__PURE__ */ new Date();
6033
+ const subject = await resolveSubject(db, input.organizationId, parsed);
6034
+ const rows = await collectSubjectRows(db, input.organizationId, subject);
6035
+ const counts = countRows(rows);
6036
+ await recordPrivacyRequest(db, { organizationId: input.organizationId, kind: "EXPORT", subject, requestedBy: input.requestedBy, counts, now });
6037
+ return {
6038
+ format: "ordinatio-scheduling-subject-export",
6039
+ version: 1,
6040
+ exportedAt: now.toISOString(),
6041
+ organizationId: input.organizationId,
6042
+ subject,
6043
+ counts,
6044
+ appointments: rows.appointments.map(({ calendar, type, ...rest }) => ({ ...rest, calendarName: calendar.name, typeName: type.name })),
6045
+ notifications: rows.notifications.map((row) => ({ ...row, body: withoutLinks(row.body) })),
6046
+ waitlistEntries: rows.waitlistEntries,
6047
+ packagePurchases: rows.packagePurchases,
6048
+ recurringSeries: rows.recurringSeries,
6049
+ webhookDeliveries: rows.webhookDeliveries.map((row) => ({ ...row, body: withoutOfferToken(row.body) }))
6050
+ };
6051
+ }
6052
+
6053
+ // src/privacy/erase.ts
6054
+ var import_node_crypto7 = require("crypto");
6055
+ var import_client9 = require("@prisma/client");
6056
+ var ERASED_NAME = "Erased client";
6057
+ var ERASED_EMAIL = "erased@erased.invalid";
6058
+ var LIVE_BOOKING = ["PENDING", "CONFIRMED"];
6059
+ var LIVE_OFFER = ["OFFERED", "ACCEPTING"];
6060
+ function blockersOf(rows, now) {
6061
+ return {
6062
+ upcomingAppointments: rows.appointments.filter((row) => LIVE_BOOKING.includes(row.status) && row.endTime > now).length,
6063
+ liveWaitlistEntries: rows.waitlistEntries.filter((row) => LIVE_OFFER.includes(row.status)).length
6064
+ };
6065
+ }
6066
+ function warningsOf(rows) {
6067
+ const unused = rows.packagePurchases.filter((row) => row.status === "ACTIVE").reduce((sum, row) => sum + Math.max(0, row.sessionsTotal - row.sessionsUsed), 0);
6068
+ return unused > 0 ? [`An active package still has ${unused} unused sessions; after erasure it can no longer be matched to this person`] : [];
6069
+ }
6070
+ var blocked = (blockers) => blockers.upcomingAppointments + blockers.liveWaitlistEntries > 0;
6071
+ async function previewErase(db, input) {
6072
+ const subject = await resolveSubject(db, input.organizationId, parseSubject(input));
6073
+ const rows = await collectSubjectRows(db, input.organizationId, subject);
6074
+ const blockers = blockersOf(rows, input.now ?? /* @__PURE__ */ new Date());
6075
+ return { counts: countRows(rows), blockers, canErase: !blocked(blockers), warnings: warningsOf(rows) };
6076
+ }
6077
+ async function eraseSubject(db, input) {
6078
+ const parsed = parseSubject(input);
6079
+ const now = input.now ?? /* @__PURE__ */ new Date();
6080
+ const { organizationId } = input;
6081
+ return withTransaction(db, async (tx) => {
6082
+ const subject = await resolveSubject(tx, organizationId, parsed);
6083
+ const rows = await collectSubjectRows(tx, organizationId, subject);
6084
+ const blockers = blockersOf(rows, now);
6085
+ if (blocked(blockers)) {
6086
+ throw new SchedulingValidationError("This person still has upcoming bookings or an open waitlist offer", "SCHED_1301", { blockers });
6087
+ }
6088
+ for (const { id } of rows.appointments) {
6089
+ await tx.appointment.update({
6090
+ where: { id },
6091
+ data: {
6092
+ clientName: ERASED_NAME,
6093
+ clientEmail: ERASED_EMAIL,
6094
+ clientPhone: null,
6095
+ clientId: null,
6096
+ intakeResponses: import_client9.Prisma.DbNull,
6097
+ notes: null,
6098
+ staffNotes: null,
6099
+ cancelReason: null,
6100
+ manageToken: `erased_${(0, import_node_crypto7.randomUUID)()}`
6101
+ }
6102
+ });
6103
+ }
6104
+ const idsOf = (list) => list.map((row) => row.id);
6105
+ if (rows.notifications.length) await tx.scheduledNotification.deleteMany({ where: { id: { in: idsOf(rows.notifications) } } });
6106
+ if (rows.waitlistEntries.length) await tx.waitlistEntry.deleteMany({ where: { organizationId, id: { in: idsOf(rows.waitlistEntries) } } });
6107
+ if (rows.webhookDeliveries.length) await tx.webhookDelivery.deleteMany({ where: { organizationId, id: { in: idsOf(rows.webhookDeliveries) } } });
6108
+ if (rows.packagePurchases.length) {
6109
+ await tx.packagePurchase.updateMany({
6110
+ where: { organizationId, id: { in: idsOf(rows.packagePurchases) } },
6111
+ data: { clientEmail: ERASED_EMAIL, clientName: null, notes: null }
6112
+ });
6113
+ }
6114
+ if (rows.recurringSeries.length) {
6115
+ await tx.recurringSeries.updateMany({
6116
+ where: { organizationId, id: { in: idsOf(rows.recurringSeries) } },
6117
+ data: { clientEmail: ERASED_EMAIL, clientName: ERASED_NAME, clientPhone: null, clientId: null, notes: null }
6118
+ });
6119
+ }
6120
+ const counts = countRows(rows);
6121
+ await recordPrivacyRequest(tx, { organizationId, kind: "ERASE", subject, requestedBy: input.requestedBy, counts, now });
6122
+ return { counts };
6123
+ }, { timeout: 12e4 });
6124
+ }
3891
6125
  // Annotate the CommonJS export names for ESM import in node:
3892
6126
  0 && (module.exports = {
6127
+ BRAND_FIELDS,
6128
+ BlockedTargetError,
6129
+ DEFAULT_BACKOFF_SECONDS,
6130
+ DEFAULT_OFFER_MINUTES,
6131
+ ERASED_EMAIL,
6132
+ ERASED_NAME,
6133
+ MAX_ENDPOINTS_PER_ORGANIZATION,
6134
+ MAX_WAITING_PER_TYPE_DAY,
6135
+ OPERATORS_BY_TYPE,
3893
6136
  RECURRING_MAX_OCCURRENCES,
6137
+ ROUTING_LIMITS,
3894
6138
  SCHEDULING_ERRORS,
6139
+ SIGNATURE_HEADER,
3895
6140
  SchedulingNotFoundError,
3896
6141
  SchedulingValidationError,
3897
6142
  USER_DAY_LIMIT,
6143
+ WEBHOOK_EVENT_TYPES,
6144
+ WEBHOOK_TEST_EVENT,
3898
6145
  adaptersToCallbacks,
3899
6146
  addDateOverride,
3900
6147
  addTimeBlock,
6148
+ appointmentWebhookData,
3901
6149
  archiveCalendar,
6150
+ beginWaitlistAccept,
3902
6151
  bookAppointment,
6152
+ brandTemplateFields,
3903
6153
  buildJitsiUrl,
3904
6154
  buildNotificationContext,
3905
6155
  buildOccurrenceStartTime,
@@ -3907,18 +6157,35 @@ async function getTeamAvailableSlots(db, query, _getSlots = getAvailableSlots) {
3907
6157
  calculateCancellationFee,
3908
6158
  cancelAppointment,
3909
6159
  cancelPendingNotifications,
6160
+ checkAnswers,
3910
6161
  checkAuthContract,
3911
6162
  checkCalendarSyncContract,
3912
6163
  checkClockContract,
3913
6164
  checkNotificationContract,
3914
6165
  checkPaymentContract,
6166
+ checkWebhookUrl,
6167
+ completeWaitlistAccept,
3915
6168
  createAppointmentType,
3916
6169
  createCalendar,
3917
6170
  createInMemoryAdapters,
6171
+ createNodeTransport,
3918
6172
  createNotificationTemplate,
6173
+ createRoutingForm,
6174
+ createWebhookEndpoint,
6175
+ deleteBrand,
3919
6176
  deleteCalendar,
3920
6177
  deleteNotificationTemplate,
6178
+ deleteRoutingForm,
6179
+ deleteWebhookEndpoint,
6180
+ deliverDueWebhooks,
6181
+ enqueueAppointmentWebhook,
6182
+ enqueueReminderSent,
6183
+ enqueueWebhookEvent,
6184
+ eraseSubject,
6185
+ expireWaitlistOffers,
6186
+ exportSubject,
3921
6187
  generateOccurrenceDates,
6188
+ generateWebhookSecret,
3922
6189
  getAppointment,
3923
6190
  getAppointmentDashboard,
3924
6191
  getAppointmentType,
@@ -3926,35 +6193,73 @@ async function getTeamAvailableSlots(db, query, _getSlots = getAvailableSlots) {
3926
6193
  getAvailableDates,
3927
6194
  getAvailableSlots,
3928
6195
  getBookingAnalytics,
6196
+ getBrand,
3929
6197
  getCalendar,
3930
6198
  getGroupCapacity,
3931
6199
  getGroupSessions,
3932
6200
  getNotificationTemplate,
6201
+ getPublicBrand,
6202
+ getPublicRoutingForm,
6203
+ getRoutingForm,
3933
6204
  getTeamAvailableSlots,
3934
6205
  getUserDayAppointments,
6206
+ getWaitlistOffer,
6207
+ isPrivateAddress,
3935
6208
  isSlotAvailable,
3936
6209
  isVirtualMeeting,
6210
+ joinWaitlist,
6211
+ leaveWaitlist,
3937
6212
  listAppointmentTypes,
3938
6213
  listAppointments,
3939
6214
  listAvailabilityRules,
3940
6215
  listCalendars,
3941
6216
  listNotificationTemplates,
6217
+ listPrivacyRequests,
6218
+ listRoutingForms,
6219
+ listWaitlist,
6220
+ listWebhookDeliveries,
6221
+ listWebhookEndpoints,
6222
+ localDay,
3942
6223
  localToUTC,
3943
6224
  markNoShow,
6225
+ matchingRules,
6226
+ offerFreedSlot,
6227
+ parseSubject,
3944
6228
  parseTimeLocal,
6229
+ previewErase,
3945
6230
  processPendingNotifications,
3946
6231
  queueImmediateNotification,
3947
6232
  queueStaffNotification,
6233
+ releaseWaitlistAccept,
3948
6234
  removeDateOverride,
6235
+ removeWaitlistEntry,
3949
6236
  renderTemplate,
3950
6237
  rescheduleAppointment,
6238
+ resolveDestination,
3951
6239
  resolveLocation,
6240
+ resolveSubject,
6241
+ retryWebhookDelivery,
6242
+ routeClient,
6243
+ saveBrand,
3952
6244
  schedError,
3953
6245
  scheduleNotifications,
3954
6246
  selectCalendarForBooking,
6247
+ sendTestWebhook,
6248
+ senderIdentity,
3955
6249
  setWeeklyAvailability,
6250
+ settleBookedAccept,
6251
+ signWebhook,
6252
+ subjectHashes,
6253
+ testRoutingForm,
6254
+ toPublicBrand,
6255
+ tryOfferFreedSlot,
3956
6256
  updateAppointmentType,
3957
6257
  updateCalendar,
3958
6258
  updateNotificationTemplate,
6259
+ updateRoutingForm,
6260
+ validateBrand,
6261
+ validateRoutingDestinations,
6262
+ validateRoutingStructure,
6263
+ verifyWebhookSignature,
3959
6264
  withCalendarVisibility
3960
6265
  });