@ordinatio/scheduling 0.3.0 → 0.5.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
@@ -30,10 +30,17 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
+ BRAND_FIELDS: () => BRAND_FIELDS,
33
34
  BlockedTargetError: () => BlockedTargetError,
34
35
  DEFAULT_BACKOFF_SECONDS: () => DEFAULT_BACKOFF_SECONDS,
36
+ DEFAULT_OFFER_MINUTES: () => DEFAULT_OFFER_MINUTES,
37
+ ERASED_EMAIL: () => ERASED_EMAIL,
38
+ ERASED_NAME: () => ERASED_NAME,
35
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,
36
42
  RECURRING_MAX_OCCURRENCES: () => RECURRING_MAX_OCCURRENCES,
43
+ ROUTING_LIMITS: () => LIMITS,
37
44
  SCHEDULING_ERRORS: () => SCHEDULING_ERRORS,
38
45
  SIGNATURE_HEADER: () => SIGNATURE_HEADER,
39
46
  SchedulingNotFoundError: () => SchedulingNotFoundError,
@@ -46,7 +53,9 @@ __export(index_exports, {
46
53
  addTimeBlock: () => addTimeBlock,
47
54
  appointmentWebhookData: () => appointmentWebhookData,
48
55
  archiveCalendar: () => archiveCalendar,
56
+ beginWaitlistAccept: () => beginWaitlistAccept,
49
57
  bookAppointment: () => bookAppointment,
58
+ brandTemplateFields: () => brandTemplateFields,
50
59
  buildJitsiUrl: () => buildJitsiUrl,
51
60
  buildNotificationContext: () => buildNotificationContext,
52
61
  buildOccurrenceStartTime: () => buildOccurrenceStartTime,
@@ -54,25 +63,33 @@ __export(index_exports, {
54
63
  calculateCancellationFee: () => calculateCancellationFee,
55
64
  cancelAppointment: () => cancelAppointment,
56
65
  cancelPendingNotifications: () => cancelPendingNotifications,
66
+ checkAnswers: () => checkAnswers,
57
67
  checkAuthContract: () => checkAuthContract,
58
68
  checkCalendarSyncContract: () => checkCalendarSyncContract,
59
69
  checkClockContract: () => checkClockContract,
60
70
  checkNotificationContract: () => checkNotificationContract,
61
71
  checkPaymentContract: () => checkPaymentContract,
62
72
  checkWebhookUrl: () => checkWebhookUrl,
73
+ completeWaitlistAccept: () => completeWaitlistAccept,
63
74
  createAppointmentType: () => createAppointmentType,
64
75
  createCalendar: () => createCalendar,
65
76
  createInMemoryAdapters: () => createInMemoryAdapters,
66
77
  createNodeTransport: () => createNodeTransport,
67
78
  createNotificationTemplate: () => createNotificationTemplate,
79
+ createRoutingForm: () => createRoutingForm,
68
80
  createWebhookEndpoint: () => createWebhookEndpoint,
81
+ deleteBrand: () => deleteBrand,
69
82
  deleteCalendar: () => deleteCalendar,
70
83
  deleteNotificationTemplate: () => deleteNotificationTemplate,
84
+ deleteRoutingForm: () => deleteRoutingForm,
71
85
  deleteWebhookEndpoint: () => deleteWebhookEndpoint,
72
86
  deliverDueWebhooks: () => deliverDueWebhooks,
73
87
  enqueueAppointmentWebhook: () => enqueueAppointmentWebhook,
74
88
  enqueueReminderSent: () => enqueueReminderSent,
75
89
  enqueueWebhookEvent: () => enqueueWebhookEvent,
90
+ eraseSubject: () => eraseSubject,
91
+ expireWaitlistOffers: () => expireWaitlistOffers,
92
+ exportSubject: () => exportSubject,
76
93
  generateOccurrenceDates: () => generateOccurrenceDates,
77
94
  generateWebhookSecret: () => generateWebhookSecret,
78
95
  getAppointment: () => getAppointment,
@@ -82,44 +99,77 @@ __export(index_exports, {
82
99
  getAvailableDates: () => getAvailableDates,
83
100
  getAvailableSlots: () => getAvailableSlots,
84
101
  getBookingAnalytics: () => getBookingAnalytics,
102
+ getBrand: () => getBrand,
85
103
  getCalendar: () => getCalendar,
86
104
  getGroupCapacity: () => getGroupCapacity,
87
105
  getGroupSessions: () => getGroupSessions,
88
106
  getNotificationTemplate: () => getNotificationTemplate,
107
+ getPublicBrand: () => getPublicBrand,
108
+ getPublicRoutingForm: () => getPublicRoutingForm,
109
+ getRoutingForm: () => getRoutingForm,
89
110
  getTeamAvailableSlots: () => getTeamAvailableSlots,
90
111
  getUserDayAppointments: () => getUserDayAppointments,
112
+ getWaitlistOffer: () => getWaitlistOffer,
91
113
  isPrivateAddress: () => isPrivateAddress,
92
114
  isSlotAvailable: () => isSlotAvailable,
93
115
  isVirtualMeeting: () => isVirtualMeeting,
116
+ joinWaitlist: () => joinWaitlist,
117
+ leaveWaitlist: () => leaveWaitlist,
94
118
  listAppointmentTypes: () => listAppointmentTypes,
95
119
  listAppointments: () => listAppointments,
96
120
  listAvailabilityRules: () => listAvailabilityRules,
97
121
  listCalendars: () => listCalendars,
98
122
  listNotificationTemplates: () => listNotificationTemplates,
123
+ listPrivacyRequests: () => listPrivacyRequests,
124
+ listRoutingForms: () => listRoutingForms,
125
+ listWaitlist: () => listWaitlist,
99
126
  listWebhookDeliveries: () => listWebhookDeliveries,
100
127
  listWebhookEndpoints: () => listWebhookEndpoints,
128
+ localDay: () => localDay,
101
129
  localToUTC: () => localToUTC,
102
130
  markNoShow: () => markNoShow,
131
+ matchingRules: () => matchingRules,
132
+ offerFreedSlot: () => offerFreedSlot,
133
+ parseSubject: () => parseSubject,
103
134
  parseTimeLocal: () => parseTimeLocal,
135
+ previewErase: () => previewErase,
104
136
  processPendingNotifications: () => processPendingNotifications,
105
137
  queueImmediateNotification: () => queueImmediateNotification,
106
138
  queueStaffNotification: () => queueStaffNotification,
139
+ releaseWaitlistAccept: () => releaseWaitlistAccept,
107
140
  removeDateOverride: () => removeDateOverride,
141
+ removeWaitlistEntry: () => removeWaitlistEntry,
108
142
  renderTemplate: () => renderTemplate,
109
143
  rescheduleAppointment: () => rescheduleAppointment,
144
+ resolveDestination: () => resolveDestination,
110
145
  resolveLocation: () => resolveLocation,
146
+ resolveSubject: () => resolveSubject,
111
147
  retryWebhookDelivery: () => retryWebhookDelivery,
148
+ routeClient: () => routeClient,
149
+ saveBrand: () => saveBrand,
112
150
  schedError: () => schedError,
113
151
  scheduleNotifications: () => scheduleNotifications,
152
+ scopeToOrganization: () => scopeToOrganization,
114
153
  selectCalendarForBooking: () => selectCalendarForBooking,
115
154
  sendTestWebhook: () => sendTestWebhook,
155
+ senderIdentity: () => senderIdentity,
116
156
  setWeeklyAvailability: () => setWeeklyAvailability,
157
+ settleBookedAccept: () => settleBookedAccept,
117
158
  signWebhook: () => signWebhook,
159
+ subjectHashes: () => subjectHashes,
160
+ testRoutingForm: () => testRoutingForm,
161
+ toPublicBrand: () => toPublicBrand,
162
+ tryOfferFreedSlot: () => tryOfferFreedSlot,
118
163
  updateAppointmentType: () => updateAppointmentType,
119
164
  updateCalendar: () => updateCalendar,
120
165
  updateNotificationTemplate: () => updateNotificationTemplate,
166
+ updateRoutingForm: () => updateRoutingForm,
167
+ validateBrand: () => validateBrand,
168
+ validateRoutingDestinations: () => validateRoutingDestinations,
169
+ validateRoutingStructure: () => validateRoutingStructure,
121
170
  verifyWebhookSignature: () => verifyWebhookSignature,
122
- withCalendarVisibility: () => withCalendarVisibility
171
+ withCalendarVisibility: () => withCalendarVisibility,
172
+ withOrganization: () => withOrganization
123
173
  });
124
174
  module.exports = __toCommonJS(index_exports);
125
175
 
@@ -1051,7 +1101,7 @@ var WEBHOOK_ERRORS = {
1051
1101
  description: "The webhook event list is empty or names an event that does not exist",
1052
1102
  diagnosis: [
1053
1103
  'Send at least one event name, or "*" for every event',
1054
- "Valid names: appointment.booked, appointment.rescheduled, appointment.cancelled, appointment.no_show, reminder.sent"
1104
+ "Valid names: appointment.booked, appointment.rescheduled, appointment.cancelled, appointment.no_show, reminder.sent, waitlist.offered"
1055
1105
  ]
1056
1106
  },
1057
1107
  SCHED_1002: {
@@ -1113,6 +1163,153 @@ var WEBHOOK_ERRORS = {
1113
1163
  }
1114
1164
  };
1115
1165
 
1166
+ // src/errors/registry-waitlist.ts
1167
+ function entry(code, fn, description, diagnosis, severity = "warning", recoverable = true) {
1168
+ return { code, file: "waitlist/", function: fn, severity, recoverable, description, diagnosis };
1169
+ }
1170
+ var WAITLIST_ERRORS = {
1171
+ SCHED_1100: entry(
1172
+ "SCHED_1100",
1173
+ "joinWaitlist",
1174
+ "The appointment type or calendar for this waitlist request was not found",
1175
+ ["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"]
1176
+ ),
1177
+ SCHED_1101: entry(
1178
+ "SCHED_1101",
1179
+ "joinWaitlist",
1180
+ "The waitlist day is invalid, in the past, or too far ahead",
1181
+ ["Send the day as YYYY-MM-DD", "The day must be today or later, and within the next 90 days"]
1182
+ ),
1183
+ SCHED_1102: entry(
1184
+ "SCHED_1102",
1185
+ "joinWaitlist",
1186
+ "The waitlist time is invalid or not on the chosen day",
1187
+ ["Send the time as an ISO date-time on the chosen day, in the future"]
1188
+ ),
1189
+ SCHED_1103: entry(
1190
+ "SCHED_1103",
1191
+ "joinWaitlist",
1192
+ "That time or day still has open slots, so the client should book instead of waiting",
1193
+ ["Look up the open slots for the day", "Join the waitlist only for a slot or day that is full"]
1194
+ ),
1195
+ SCHED_1104: entry(
1196
+ "SCHED_1104",
1197
+ "joinWaitlist",
1198
+ "This email is already waiting for that day",
1199
+ ["The client is already on the list for this type and day", "They can leave with their link and join again"]
1200
+ ),
1201
+ SCHED_1105: entry(
1202
+ "SCHED_1105",
1203
+ "joinWaitlist",
1204
+ "A waitlist is not available for a type that needs payment",
1205
+ ["Payment cannot be taken when an offer is accepted", "Use a free type, or let clients book as slots open"]
1206
+ ),
1207
+ SCHED_1106: entry(
1208
+ "SCHED_1106",
1209
+ "getWaitlistOffer",
1210
+ "No open offer for this link",
1211
+ ["The link may be wrong, already used, or the entry may have left the list", "An offer can be accepted once"]
1212
+ ),
1213
+ SCHED_1107: entry(
1214
+ "SCHED_1107",
1215
+ "beginWaitlistAccept",
1216
+ "The offer has expired",
1217
+ ["The time limit ran out; the slot may have gone to the next person", "Join the waitlist again to wait for another slot"]
1218
+ ),
1219
+ SCHED_1108: entry(
1220
+ "SCHED_1108",
1221
+ "joinWaitlist",
1222
+ "The waitlist for that day is full",
1223
+ ["Too many people are already waiting for this type and day"]
1224
+ ),
1225
+ SCHED_1109: entry(
1226
+ "SCHED_1109",
1227
+ "offerFreedSlot",
1228
+ "A waitlist offer could not be made; the cancellation itself was saved",
1229
+ ["Check that the waitlist table exists (run the package migrations)", "Check the database connection"],
1230
+ "error"
1231
+ ),
1232
+ SCHED_1110: entry(
1233
+ "SCHED_1110",
1234
+ "joinWaitlist",
1235
+ "A waitlist is not available for a type with required intake questions",
1236
+ ["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"]
1237
+ )
1238
+ };
1239
+
1240
+ // src/errors/registry-routing.ts
1241
+ function entry2(code, fn, description, diagnosis, severity = "warning") {
1242
+ return { code, file: "routing/", function: fn, severity, recoverable: true, description, diagnosis };
1243
+ }
1244
+ var ROUTING_ERRORS = {
1245
+ SCHED_1200: entry2(
1246
+ "SCHED_1200",
1247
+ "validateRoutingForm",
1248
+ "The routing form is not valid",
1249
+ ["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"]
1250
+ ),
1251
+ SCHED_1201: entry2(
1252
+ "SCHED_1201",
1253
+ "routing form lookup",
1254
+ "The routing form was not found (for the public: no active form with that slug)",
1255
+ ["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"]
1256
+ ),
1257
+ SCHED_1202: entry2(
1258
+ "SCHED_1202",
1259
+ "createRoutingForm / updateRoutingForm",
1260
+ "Another routing form already uses that slug",
1261
+ ["Choose a different slug", "A slug is unique within the organization and must not be used by another organization in the same database"]
1262
+ ),
1263
+ SCHED_1203: entry2(
1264
+ "SCHED_1203",
1265
+ "routeClient",
1266
+ "The answers do not fit the form",
1267
+ ["Answer every required question", "Pick an offered option for choice questions, and send a list for checkbox questions", "Send only questions the form asks"]
1268
+ ),
1269
+ SCHED_1204: entry2(
1270
+ "SCHED_1204",
1271
+ "createRoutingForm",
1272
+ "The organization already has the maximum number of routing forms",
1273
+ ["Remove a form that is no longer used, then add the new one"]
1274
+ )
1275
+ };
1276
+
1277
+ // src/errors/registry-privacy.ts
1278
+ function entry3(code, fn, description, diagnosis) {
1279
+ return { code, file: "privacy/", function: fn, severity: "warning", recoverable: true, description, diagnosis };
1280
+ }
1281
+ var PRIVACY_ERRORS = {
1282
+ SCHED_1300: entry3(
1283
+ "SCHED_1300",
1284
+ "parseSubject",
1285
+ "Say whose data this is: a valid email address, a client id, or both",
1286
+ ["Send `email` (one address) and/or `clientId`", "An address must be a single address with no spaces, at most 254 characters"]
1287
+ ),
1288
+ SCHED_1301: entry3(
1289
+ "SCHED_1301",
1290
+ "eraseSubject",
1291
+ "This person still has upcoming bookings or an open waitlist offer, so their data cannot be erased yet",
1292
+ ["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"]
1293
+ )
1294
+ };
1295
+
1296
+ // src/errors/registry-brand.ts
1297
+ var BRAND_ERRORS = {
1298
+ SCHED_1400: {
1299
+ code: "SCHED_1400",
1300
+ file: "brand/",
1301
+ function: "validateBrand",
1302
+ severity: "warning",
1303
+ recoverable: true,
1304
+ description: "The brand settings are not valid",
1305
+ diagnosis: [
1306
+ "Read the list of problems in the error context: each names the field and what is wrong",
1307
+ "Colours are hex values such as #1a2b3c; the logo is an https address; email addresses are single plain addresses",
1308
+ "A sending address is accepted only for a domain the host has confirmed it may send from"
1309
+ ]
1310
+ }
1311
+ };
1312
+
1116
1313
  // src/errors/registry.ts
1117
1314
  var SCHEDULING_ERRORS = {
1118
1315
  ...CALENDARS_AVAILABILITY_ERRORS,
@@ -1123,7 +1320,11 @@ var SCHEDULING_ERRORS = {
1123
1320
  ...RECURRING_MISC_ERRORS,
1124
1321
  ...PUBLIC_DIRECTORY_ERRORS,
1125
1322
  ...GROUP_SCOPE_ERRORS,
1126
- ...WEBHOOK_ERRORS
1323
+ ...WEBHOOK_ERRORS,
1324
+ ...WAITLIST_ERRORS,
1325
+ ...ROUTING_ERRORS,
1326
+ ...PRIVACY_ERRORS,
1327
+ ...BRAND_ERRORS
1127
1328
  };
1128
1329
 
1129
1330
  // src/errors/diagnostic-error.ts
@@ -2033,6 +2234,37 @@ function buildConfirmationBody(appointment, type, calendar) {
2033
2234
  ].filter(Boolean).join("\n");
2034
2235
  }
2035
2236
 
2237
+ // src/appointments/organization-filter.ts
2238
+ function withOrganization(where, organizationId) {
2239
+ if (organizationId === void 0) return where;
2240
+ return { AND: [where, { calendar: { organizationId } }] };
2241
+ }
2242
+ var NARROWED_METHODS = /* @__PURE__ */ new Set(["findMany", "findFirst", "count"]);
2243
+ function narrowModel(model, narrow) {
2244
+ return new Proxy(model, {
2245
+ get(target, property) {
2246
+ const value = Reflect.get(target, property, target);
2247
+ if (typeof property === "string" && NARROWED_METHODS.has(property) && typeof value === "function") {
2248
+ return (args = {}) => value.call(target, { ...args, where: narrow(args.where ?? {}) });
2249
+ }
2250
+ return typeof value === "function" ? value.bind(target) : value;
2251
+ }
2252
+ });
2253
+ }
2254
+ function scopeToOrganization(db, organizationId) {
2255
+ if (organizationId === void 0) return db;
2256
+ const appointment = narrowModel(db.appointment, (where) => withOrganization(where, organizationId));
2257
+ const schedulingCalendar = narrowModel(db.schedulingCalendar, (where) => ({ AND: [where, { organizationId }] }));
2258
+ return new Proxy(db, {
2259
+ get(target, property) {
2260
+ if (property === "appointment") return appointment;
2261
+ if (property === "schedulingCalendar") return schedulingCalendar;
2262
+ const value = Reflect.get(target, property, target);
2263
+ return typeof value === "function" ? value.bind(target) : value;
2264
+ }
2265
+ });
2266
+ }
2267
+
2036
2268
  // src/appointments/book-appointment.ts
2037
2269
  var import_client5 = require("@prisma/client");
2038
2270
 
@@ -2213,9 +2445,7 @@ async function bookAppointment(db, input, callbacks) {
2213
2445
  clientName: input.clientName,
2214
2446
  clientEmail: input.clientEmail,
2215
2447
  clientPhone: input.clientPhone ?? null,
2216
- // ALFRED-246 (system-1701's .autocode/modules/alfred/debt.md): the public booking
2217
- // route passes this through from caller-supplied, unauthenticated input with no
2218
- // existence/ownership check — a real, disclosed, not-yet-fixed gap.
2448
+ // Not verified here: a caller that takes this from unauthenticated input must check it first.
2219
2449
  clientId: input.clientId ?? null,
2220
2450
  intakeResponses: input.intakeResponses,
2221
2451
  staffNotes: input.staffNotes ?? null,
@@ -2318,13 +2548,13 @@ function renderTemplate(template, context, channel = "EMAIL") {
2318
2548
  for (const [key, value] of Object.entries(context)) {
2319
2549
  if (typeof value === "string") {
2320
2550
  const safeValue = channel === "SMS" ? value : escapeHtml(value);
2321
- result = result.replace(new RegExp(`\\{\\{${key}\\}\\}`, "g"), safeValue);
2551
+ result = result.replace(new RegExp(`\\{\\{${key}\\}\\}`, "g"), () => safeValue);
2322
2552
  }
2323
2553
  }
2324
2554
  if (context.customFields) {
2325
2555
  for (const [key, value] of Object.entries(context.customFields)) {
2326
2556
  const safeValue = channel === "SMS" ? value : escapeHtml(value);
2327
- result = result.replace(new RegExp(`\\{\\{${key}\\}\\}`, "g"), safeValue);
2557
+ result = result.replace(new RegExp(`\\{\\{${key}\\}\\}`, "g"), () => safeValue);
2328
2558
  }
2329
2559
  }
2330
2560
  if (channel === "SMS") {
@@ -2377,6 +2607,196 @@ function buildNotificationContext(appointment, baseUrl) {
2377
2607
  };
2378
2608
  }
2379
2609
 
2610
+ // src/brand/sender.ts
2611
+ var NOT_IN_A_SENDER_NAME = /[<>",;@\\]/g;
2612
+ function senderIdentity(brand) {
2613
+ if (!brand) return null;
2614
+ const fallbackName = brand.displayName.replace(/[\u0000-\u001f\u007f]/g, " ").replace(NOT_IN_A_SENDER_NAME, "").replace(/\s+/g, " ").trim();
2615
+ const name = brand.fromName ?? (fallbackName || void 0);
2616
+ return {
2617
+ ...name ? { name } : {},
2618
+ ...brand.fromEmail ? { email: brand.fromEmail } : {},
2619
+ ...brand.replyToEmail ? { replyTo: brand.replyToEmail } : {}
2620
+ };
2621
+ }
2622
+ function brandTemplateFields(brand) {
2623
+ return {
2624
+ brandName: brand?.displayName ?? "",
2625
+ brandLogoUrl: brand?.logoUrl ?? "",
2626
+ brandColor: brand?.primaryColor ?? "",
2627
+ brandFooter: brand?.footerText ?? ""
2628
+ };
2629
+ }
2630
+ function toPublicBrand(brand) {
2631
+ return {
2632
+ displayName: brand.displayName,
2633
+ logoUrl: brand.logoUrl,
2634
+ primaryColor: brand.primaryColor,
2635
+ accentColor: brand.accentColor,
2636
+ backgroundColor: brand.backgroundColor,
2637
+ textColor: brand.textColor,
2638
+ fontFamily: brand.fontFamily,
2639
+ footerText: brand.footerText
2640
+ };
2641
+ }
2642
+
2643
+ // src/brand/types.ts
2644
+ var BRAND_FIELDS = [
2645
+ "displayName",
2646
+ "logoUrl",
2647
+ "primaryColor",
2648
+ "accentColor",
2649
+ "backgroundColor",
2650
+ "textColor",
2651
+ "fontFamily",
2652
+ "footerText",
2653
+ "replyToEmail",
2654
+ "fromName",
2655
+ "fromEmail"
2656
+ ];
2657
+
2658
+ // src/brand/validate.ts
2659
+ var HEX = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;
2660
+ var FONT = /^[A-Za-z0-9 ,-]{1,100}$/;
2661
+ var EMAIL = /^[^\s@<>,;"'()[\]\\]+@[^\s@<>,;"'()[\]\\]+\.[^\s@<>,;"'()[\]\\]+$/;
2662
+ var CONTROL = /[\u0000-\u001f\u007f]/;
2663
+ var COLOR_FIELDS = ["primaryColor", "accentColor", "backgroundColor", "textColor"];
2664
+ function text(value, path, max, problems, required = false) {
2665
+ if (value === void 0 || value === null || value === "") {
2666
+ if (required) problems.push({ path, message: "Required" });
2667
+ return null;
2668
+ }
2669
+ if (typeof value !== "string") {
2670
+ problems.push({ path, message: "Must be text" });
2671
+ return null;
2672
+ }
2673
+ const trimmed = value.trim();
2674
+ if (trimmed.length === 0) {
2675
+ if (required) problems.push({ path, message: "Required" });
2676
+ return null;
2677
+ }
2678
+ if (trimmed.length > max) problems.push({ path, message: `At most ${max} characters` });
2679
+ else if (CONTROL.test(trimmed)) problems.push({ path, message: "Must not contain control characters" });
2680
+ else return trimmed;
2681
+ return null;
2682
+ }
2683
+ function email(value, path, problems) {
2684
+ const raw = text(value, path, 254, problems);
2685
+ if (raw === null) return null;
2686
+ if (!EMAIL.test(raw)) {
2687
+ problems.push({ path, message: "Must be a single email address" });
2688
+ return null;
2689
+ }
2690
+ return raw.toLowerCase();
2691
+ }
2692
+ function logo(value, problems) {
2693
+ const raw = text(value, "logoUrl", 500, problems);
2694
+ if (raw === null) return null;
2695
+ try {
2696
+ const url = new URL(raw);
2697
+ if (url.protocol === "https:" && !url.username && !url.password && url.hostname) return raw;
2698
+ } catch {
2699
+ }
2700
+ problems.push({ path: "logoUrl", message: "Must be an https address without a user name or password" });
2701
+ return null;
2702
+ }
2703
+ async function validateBrand(input, options) {
2704
+ const problems = [];
2705
+ if (typeof input !== "object" || input === null || Array.isArray(input)) {
2706
+ throw new SchedulingValidationError("The brand settings are not valid", "SCHED_1400", { errors: [{ path: "", message: "Must be an object" }] });
2707
+ }
2708
+ const given = input;
2709
+ for (const key of Object.keys(given)) if (!BRAND_FIELDS.includes(key)) problems.push({ path: key, message: "Unknown field" });
2710
+ const out = {
2711
+ displayName: text(given.displayName, "displayName", 100, problems, true) ?? "",
2712
+ logoUrl: logo(given.logoUrl, problems),
2713
+ primaryColor: null,
2714
+ accentColor: null,
2715
+ backgroundColor: null,
2716
+ textColor: null,
2717
+ fontFamily: null,
2718
+ footerText: text(given.footerText, "footerText", 300, problems),
2719
+ replyToEmail: email(given.replyToEmail, "replyToEmail", problems),
2720
+ fromName: text(given.fromName, "fromName", 100, problems),
2721
+ fromEmail: email(given.fromEmail, "fromEmail", problems)
2722
+ };
2723
+ for (const field of COLOR_FIELDS) {
2724
+ const raw = text(given[field], field, 7, problems);
2725
+ if (raw === null) continue;
2726
+ if (HEX.test(raw)) out[field] = raw.toLowerCase();
2727
+ else problems.push({ path: field, message: "Must be a hex colour such as #1a2b3c" });
2728
+ }
2729
+ const font = text(given.fontFamily, "fontFamily", 100, problems);
2730
+ if (font !== null) {
2731
+ if (FONT.test(font)) out.fontFamily = font;
2732
+ else problems.push({ path: "fontFamily", message: "Letters, digits, spaces, commas and dashes only" });
2733
+ }
2734
+ if (out.fromName !== null && /[<>",;@\\]/.test(out.fromName)) {
2735
+ problems.push({ path: "fromName", message: "Must not contain quotes, angle brackets, commas, semicolons, @ or backslashes" });
2736
+ out.fromName = null;
2737
+ }
2738
+ if (out.fromEmail !== null && !problems.some((p) => p.path === "fromEmail")) {
2739
+ const domain = out.fromEmail.slice(out.fromEmail.lastIndexOf("@") + 1);
2740
+ let verified = false;
2741
+ try {
2742
+ verified = options.isSendingDomainVerified ? await options.isSendingDomainVerified(domain) : false;
2743
+ } catch (error) {
2744
+ console.error("[brand] the sending-domain check failed:", error);
2745
+ verified = false;
2746
+ }
2747
+ if (!verified) problems.push({ path: "fromEmail", message: `Sending from ${domain} is not confirmed for this server` });
2748
+ }
2749
+ if (problems.length > 0) throw new SchedulingValidationError("The brand settings are not valid", "SCHED_1400", { errors: problems });
2750
+ return out;
2751
+ }
2752
+
2753
+ // src/brand/crud.ts
2754
+ var SELECT = {
2755
+ displayName: true,
2756
+ logoUrl: true,
2757
+ primaryColor: true,
2758
+ accentColor: true,
2759
+ backgroundColor: true,
2760
+ textColor: true,
2761
+ fontFamily: true,
2762
+ footerText: true,
2763
+ replyToEmail: true,
2764
+ fromName: true,
2765
+ fromEmail: true,
2766
+ updatedAt: true
2767
+ };
2768
+ async function getBrand(db, organizationId) {
2769
+ return db.organizationBrand.findUnique({ where: { organizationId }, select: SELECT });
2770
+ }
2771
+ async function getPublicBrand(db, organizationId) {
2772
+ if (organizationId) {
2773
+ const brand = await getBrand(db, organizationId);
2774
+ return brand ? toPublicBrand(brand) : null;
2775
+ }
2776
+ const all = await db.organizationBrand.findMany({ take: 2, select: SELECT });
2777
+ return all.length === 1 ? toPublicBrand(all[0]) : null;
2778
+ }
2779
+ async function saveBrand(db, organizationId, input, options) {
2780
+ const fields = await validateBrand(input, options);
2781
+ return db.organizationBrand.upsert({
2782
+ where: { organizationId },
2783
+ create: { organizationId, ...fields },
2784
+ update: { ...fields },
2785
+ select: SELECT
2786
+ });
2787
+ }
2788
+ async function deleteBrand(db, organizationId) {
2789
+ const { count } = await db.organizationBrand.deleteMany({ where: { organizationId } });
2790
+ return count > 0;
2791
+ }
2792
+
2793
+ // src/notifications/brand-context.ts
2794
+ async function withBrandFields(db, organizationId, context, enabled) {
2795
+ if (!enabled) return context;
2796
+ const brand = organizationId ? await getBrand(db, organizationId) : null;
2797
+ return { ...context, customFields: { ...context.customFields, ...brandTemplateFields(brand) } };
2798
+ }
2799
+
2380
2800
  // src/notifications/process-pending-notifications.ts
2381
2801
  var import_crypto = require("crypto");
2382
2802
  var import_client6 = require("@prisma/client");
@@ -2388,7 +2808,8 @@ var WEBHOOK_EVENT_TYPES = [
2388
2808
  "appointment.rescheduled",
2389
2809
  "appointment.cancelled",
2390
2810
  "appointment.no_show",
2391
- "reminder.sent"
2811
+ "reminder.sent",
2812
+ "waitlist.offered"
2392
2813
  ];
2393
2814
  var WEBHOOK_TEST_EVENT = "webhook.test";
2394
2815
  var ALL_EVENTS = "*";
@@ -2535,8 +2956,10 @@ async function processPendingNotifications(db, sender, options) {
2535
2956
  `;
2536
2957
  if (claimed.length === 0) return { sent: 0, failed: 0, deadLettered: 0, skipped: 0 };
2537
2958
  const pending = await db.scheduledNotification.findMany({
2538
- where: { id: { in: claimed.map((c) => c.id) } }
2959
+ where: { id: { in: claimed.map((c) => c.id) } },
2960
+ ...options?.brand ? { include: { appointment: { select: { calendar: { select: { organizationId: true } } } } } } : {}
2539
2961
  });
2962
+ const senders = options?.brand ? await loadSenders(db, pending) : null;
2540
2963
  let sent = 0;
2541
2964
  let failed = 0;
2542
2965
  let deadLettered = 0;
@@ -2548,7 +2971,10 @@ async function processPendingNotifications(db, sender, options) {
2548
2971
  notification.recipient,
2549
2972
  notification.subject || "",
2550
2973
  notification.body,
2551
- { trigger: notification.trigger }
2974
+ {
2975
+ trigger: notification.trigger,
2976
+ ...senderFor(senders, notification)
2977
+ }
2552
2978
  );
2553
2979
  if (result?.skipped) {
2554
2980
  await db.scheduledNotification.update({
@@ -2602,6 +3028,22 @@ async function processPendingNotifications(db, sender, options) {
2602
3028
  }
2603
3029
  return { sent, failed, deadLettered, skipped };
2604
3030
  }
3031
+ async function loadSenders(db, rows) {
3032
+ const ids = [...new Set(rows.map((row) => row.appointment?.calendar?.organizationId).filter((id) => Boolean(id)))];
3033
+ const senders = /* @__PURE__ */ new Map();
3034
+ if (ids.length === 0) return senders;
3035
+ const brands = await db.organizationBrand.findMany({ where: { organizationId: { in: ids } } });
3036
+ for (const brand of brands) {
3037
+ const identity = senderIdentity(brand);
3038
+ if (identity) senders.set(brand.organizationId, identity);
3039
+ }
3040
+ return senders;
3041
+ }
3042
+ function senderFor(senders, row) {
3043
+ const organizationId = row.appointment?.calendar?.organizationId;
3044
+ const from = senders && organizationId ? senders.get(organizationId) : void 0;
3045
+ return from ? { from } : {};
3046
+ }
2605
3047
 
2606
3048
  // src/notifications/engine.ts
2607
3049
  async function scheduleNotifications(db, appointmentId, baseUrl, options) {
@@ -2621,10 +3063,10 @@ async function scheduleNotifications(db, appointmentId, baseUrl, options) {
2621
3063
  }
2622
3064
  });
2623
3065
  if (!appointment) return;
2624
- const context = buildNotificationContext({
3066
+ const context = await withBrandFields(db, appointment.calendar.organizationId, buildNotificationContext({
2625
3067
  ...appointment,
2626
3068
  intakeResponses: appointment.intakeResponses
2627
- }, baseUrl);
3069
+ }, baseUrl), options?.brand);
2628
3070
  const now = /* @__PURE__ */ new Date();
2629
3071
  const startTime = new Date(appointment.startTime);
2630
3072
  const templates = await db.notificationTemplate.findMany({
@@ -2697,7 +3139,7 @@ async function cancelPendingNotifications(db, appointmentId) {
2697
3139
  data: { status: "CANCELLED" }
2698
3140
  });
2699
3141
  }
2700
- async function queueImmediateNotification(db, appointmentId, trigger, baseUrl) {
3142
+ async function queueImmediateNotification(db, appointmentId, trigger, baseUrl, options) {
2701
3143
  const appointment = await db.appointment.findUnique({
2702
3144
  where: { id: appointmentId },
2703
3145
  include: {
@@ -2706,10 +3148,10 @@ async function queueImmediateNotification(db, appointmentId, trigger, baseUrl) {
2706
3148
  }
2707
3149
  });
2708
3150
  if (!appointment) return;
2709
- const context = buildNotificationContext({
3151
+ const context = await withBrandFields(db, appointment.calendar.organizationId, buildNotificationContext({
2710
3152
  ...appointment,
2711
3153
  intakeResponses: appointment.intakeResponses
2712
- }, baseUrl);
3154
+ }, baseUrl), options?.brand);
2713
3155
  const templates = await db.notificationTemplate.findMany({
2714
3156
  where: { trigger, isActive: true, recipientType: "CLIENT", organizationId: appointment.calendar.organizationId ?? "" }
2715
3157
  });
@@ -2735,7 +3177,7 @@ async function queueImmediateNotification(db, appointmentId, trigger, baseUrl) {
2735
3177
  await db.scheduledNotification.createMany({ data: notifications });
2736
3178
  }
2737
3179
  }
2738
- async function queueStaffNotification(db, appointmentId, trigger, baseUrl) {
3180
+ async function queueStaffNotification(db, appointmentId, trigger, baseUrl, options) {
2739
3181
  const appointment = await db.appointment.findUnique({
2740
3182
  where: { id: appointmentId },
2741
3183
  include: {
@@ -2750,10 +3192,10 @@ async function queueStaffNotification(db, appointmentId, trigger, baseUrl) {
2750
3192
  where: { trigger, recipientType: "STAFF", isActive: true, organizationId: appointment.calendar.organizationId ?? "" }
2751
3193
  });
2752
3194
  if (staffTemplates.length === 0) return;
2753
- const context = buildNotificationContext({
3195
+ const context = await withBrandFields(db, appointment.calendar.organizationId, buildNotificationContext({
2754
3196
  ...appointment,
2755
3197
  intakeResponses: appointment.intakeResponses
2756
- }, baseUrl);
3198
+ }, baseUrl), options?.brand);
2757
3199
  const now = /* @__PURE__ */ new Date();
2758
3200
  const notifications = staffTemplates.map((template) => ({
2759
3201
  appointmentId: appointment.id,
@@ -3081,20 +3523,19 @@ async function rescheduleAppointment(db, input, callbacks) {
3081
3523
  }
3082
3524
 
3083
3525
  // src/appointments/crud.ts
3084
- async function getAppointment(db, appointmentId) {
3085
- const appointment = await db.appointment.findUnique({
3086
- where: { id: appointmentId },
3087
- include: {
3088
- calendar: { select: { name: true } },
3089
- type: { select: { name: true } }
3090
- }
3091
- });
3526
+ async function getAppointment(db, appointmentId, options = {}) {
3527
+ const include = {
3528
+ calendar: { select: { name: true } },
3529
+ type: { select: { name: true } }
3530
+ };
3531
+ const appointment = options.organizationId === void 0 ? await db.appointment.findUnique({ where: { id: appointmentId }, include }) : await db.appointment.findFirst({ where: { id: appointmentId, calendar: { organizationId: options.organizationId } }, include });
3092
3532
  if (!appointment) {
3093
3533
  throw schedError("SCHED_300", { appointmentId });
3094
3534
  }
3095
3535
  return mapToDetails(appointment);
3096
3536
  }
3097
- async function listAppointments(db, options = {}) {
3537
+ async function listAppointments(unscopedDb, options = {}) {
3538
+ const db = scopeToOrganization(unscopedDb, options.organizationId);
3098
3539
  const where = {};
3099
3540
  if (options.calendarId) where.calendarId = options.calendarId;
3100
3541
  if (options.status) where.status = options.status;
@@ -3172,13 +3613,13 @@ var STATUS_ORDER = {
3172
3613
  CANCELLED: 4
3173
3614
  };
3174
3615
  async function getGroupSessions(db, params) {
3175
- const { startDate, endDate, calendarId, visibleCalendarIds } = params;
3616
+ const { startDate, endDate, calendarId, visibleCalendarIds, organizationId } = params;
3176
3617
  const RAW_TAKE_CAP = 1e3;
3177
- const where = withCalendarVisibility({
3618
+ const where = withOrganization(withCalendarVisibility({
3178
3619
  isGroup: true,
3179
3620
  startTime: { gte: startDate, lt: endDate },
3180
3621
  ...calendarId ? { calendarId } : {}
3181
- }, visibleCalendarIds);
3622
+ }, visibleCalendarIds), organizationId);
3182
3623
  const appointments = await db.appointment.findMany({
3183
3624
  where,
3184
3625
  include: {
@@ -3247,7 +3688,7 @@ async function getBookingAnalytics(db, options = {}) {
3247
3688
  startTime: { gte: start, lte: end }
3248
3689
  };
3249
3690
  if (options.calendarId) baseWhere.calendarId = options.calendarId;
3250
- const where = withCalendarVisibility(baseWhere, options.visibleCalendarIds);
3691
+ const where = withOrganization(withCalendarVisibility(baseWhere, options.visibleCalendarIds), options.organizationId);
3251
3692
  const appointments = await db.appointment.findMany({
3252
3693
  where,
3253
3694
  select: {
@@ -3379,7 +3820,8 @@ function weekBoundsUTC(localDateStr, tz) {
3379
3820
  const end = preciseDayEnd(computeDayBoundsUTC(toDateStr(sunday), tz).end);
3380
3821
  return { start, end };
3381
3822
  }
3382
- async function getAppointmentDashboard(db, query = {}) {
3823
+ async function getAppointmentDashboard(unscopedDb, query = {}) {
3824
+ const db = scopeToOrganization(unscopedDb, query.organizationId);
3383
3825
  const now = /* @__PURE__ */ new Date();
3384
3826
  const tz = query.timezone || DEFAULT_DASHBOARD_TIMEZONE;
3385
3827
  const localDateStr = now.toLocaleDateString("en-CA", { timeZone: tz });
@@ -3486,7 +3928,8 @@ async function getAppointmentDashboard(db, query = {}) {
3486
3928
  };
3487
3929
  }
3488
3930
  var RANGE_TAKE_CAP = 2e3;
3489
- async function getAppointmentsForRange(db, rangeStart, rangeEnd) {
3931
+ async function getAppointmentsForRange(unscopedDb, rangeStart, rangeEnd, options = {}) {
3932
+ const db = scopeToOrganization(unscopedDb, options.organizationId);
3490
3933
  const appointments = await db.appointment.findMany({
3491
3934
  where: {
3492
3935
  startTime: { gte: rangeStart, lte: rangeEnd }
@@ -3550,7 +3993,8 @@ function nextDate(date) {
3550
3993
  next.setUTCDate(next.getUTCDate() + 1);
3551
3994
  return next.toISOString().slice(0, 10);
3552
3995
  }
3553
- async function getUserDayAppointments(db, input) {
3996
+ async function getUserDayAppointments(unscopedDb, input) {
3997
+ const db = scopeToOrganization(unscopedDb, input.organizationId);
3554
3998
  if (!input.userId) throw new SchedulingValidationError("A user id is required for a day query");
3555
3999
  if (!validDate(input.date)) throw new SchedulingValidationError("date must be a real day in the form YYYY-MM-DD", void 0, { date: input.date });
3556
4000
  if (!validTimezone(input.timezone)) throw new SchedulingValidationError("timezone must be an IANA time zone", void 0, { timezone: input.timezone });
@@ -3700,7 +4144,7 @@ function adaptersToCallbacks(adapters, passThrough = {}) {
3700
4144
  return {
3701
4145
  ...passThrough,
3702
4146
  sendNotification: async (channel, to, subject, body, context) => {
3703
- const result = await adapters.notifications.send({ channel, to, subject, body, trigger: context?.trigger });
4147
+ const result = await adapters.notifications.send({ channel, to, subject, body, trigger: context?.trigger, ...context?.from ? { from: context.from } : {} });
3704
4148
  if (result.status === "SKIPPED") return { skipped: true, reason: result.reason };
3705
4149
  return void 0;
3706
4150
  },
@@ -3748,10 +4192,10 @@ async function checkNotificationContract(adapter) {
3748
4192
  const result = await adapter.send({ channel: "EMAIL", to: "contract@example.com", subject: "Contract", body: "Body" });
3749
4193
  if (result.status !== "SENT" && result.status !== "SKIPPED") failures.push("send() must return status SENT or SKIPPED");
3750
4194
  });
3751
- for (const blank of ["", " "]) {
3752
- await guarded(`send to an empty recipient (${JSON.stringify(blank)})`, failures, async () => {
3753
- const result = await adapter.send({ channel: "SMS", to: blank, subject: "", body: "Body" }).catch(() => null);
3754
- if (result?.status === "SENT") failures.push(`send() must not report SENT for an empty recipient (${JSON.stringify(blank)})`);
4195
+ for (const blank2 of ["", " "]) {
4196
+ await guarded(`send to an empty recipient (${JSON.stringify(blank2)})`, failures, async () => {
4197
+ const result = await adapter.send({ channel: "SMS", to: blank2, subject: "", body: "Body" }).catch(() => null);
4198
+ if (result?.status === "SENT") failures.push(`send() must not report SENT for an empty recipient (${JSON.stringify(blank2)})`);
3755
4199
  });
3756
4200
  }
3757
4201
  return failures;
@@ -3771,7 +4215,7 @@ async function checkPaymentContract(adapter, options = {}) {
3771
4215
  if (!await refused(() => adapter.charge({ ...request, amount: 0 }))) failures.push("a charge of 0 must not succeed");
3772
4216
  });
3773
4217
  await guarded("verify of an unknown payment", failures, async () => {
3774
- const paid = await adapter.verify("contract-unknown-payment").then((check) => check.paid, () => false);
4218
+ const paid = await adapter.verify("contract-unknown-payment").then((check2) => check2.paid, () => false);
3775
4219
  if (paid) failures.push("verify() must report an unknown payment as not paid");
3776
4220
  });
3777
4221
  await guarded("refund of an unknown payment", failures, async () => {
@@ -3787,10 +4231,10 @@ async function checkPaymentContract(adapter, options = {}) {
3787
4231
  failures.push("a valid charge must succeed and return a paymentId");
3788
4232
  return;
3789
4233
  }
3790
- const check = await adapter.verify(charge.paymentId);
3791
- if (!check.paid) failures.push("verify() must report a charged payment as paid");
3792
- if (check.amount !== void 0 && check.amount !== request.amount) failures.push("verify() must report the amount that was charged");
3793
- if (check.metadata?.contract !== "metadata-round-trip") failures.push("verify() must return the metadata the charge was made with");
4234
+ const check2 = await adapter.verify(charge.paymentId);
4235
+ if (!check2.paid) failures.push("verify() must report a charged payment as paid");
4236
+ if (check2.amount !== void 0 && check2.amount !== request.amount) failures.push("verify() must report the amount that was charged");
4237
+ if (check2.metadata?.contract !== "metadata-round-trip") failures.push("verify() must return the metadata the charge was made with");
3794
4238
  const first = await adapter.refund(charge.paymentId);
3795
4239
  if (!first.success) failures.push("the first refund of a paid payment must succeed");
3796
4240
  if (first.amount !== void 0 && first.amount !== request.amount) failures.push("a full refund must report the amount it refunded");
@@ -4059,7 +4503,7 @@ function buildRecurringSlots(firstDate, frequency, occurrences, startTimeLocal,
4059
4503
 
4060
4504
  // src/appointments/meeting.ts
4061
4505
  function buildJitsiUrl(appointmentId) {
4062
- return `https://meet.jit.si/s1701-${appointmentId}`;
4506
+ return `https://meet.jit.si/ordinatio-${appointmentId}`;
4063
4507
  }
4064
4508
  function isVirtualMeeting(locationType) {
4065
4509
  return locationType === "VIRTUAL";
@@ -4175,13 +4619,13 @@ function isPrivateV4(ip) {
4175
4619
  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;
4176
4620
  }
4177
4621
  function v6Groups(ip) {
4178
- let text = ip.toLowerCase().replace(/^\[|\]$/g, "").split("%")[0];
4179
- const tail = /(\d+\.\d+\.\d+\.\d+)$/.exec(text);
4622
+ let text2 = ip.toLowerCase().replace(/^\[|\]$/g, "").split("%")[0];
4623
+ const tail = /(\d+\.\d+\.\d+\.\d+)$/.exec(text2);
4180
4624
  if (tail) {
4181
4625
  const [a, b, c, d] = v4Parts(tail[1]);
4182
- text = text.slice(0, -tail[1].length) + (a << 8 | b).toString(16) + ":" + (c << 8 | d).toString(16);
4626
+ text2 = text2.slice(0, -tail[1].length) + (a << 8 | b).toString(16) + ":" + (c << 8 | d).toString(16);
4183
4627
  }
4184
- const halves = text.split("::");
4628
+ const halves = text2.split("::");
4185
4629
  if (halves.length > 2) return null;
4186
4630
  const head = halves[0] ? halves[0].split(":") : [];
4187
4631
  const rest = halves.length === 2 && halves[1] ? halves[1].split(":") : [];
@@ -4521,12 +4965,1211 @@ async function retryWebhookDelivery(db, organizationId, deliveryId, now = /* @__
4521
4965
  });
4522
4966
  if (updated.count === 0) throw new SchedulingNotFoundError("Delivery not found or not in the dead-letter list", "SCHED_1004", { deliveryId });
4523
4967
  }
4968
+
4969
+ // src/waitlist/join.ts
4970
+ var import_node_crypto5 = require("crypto");
4971
+
4972
+ // src/waitlist/day.ts
4973
+ var MAX_DAYS_AHEAD = 90;
4974
+ function isDayString(value) {
4975
+ if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
4976
+ const parsed = /* @__PURE__ */ new Date(`${value}T00:00:00Z`);
4977
+ return !Number.isNaN(parsed.getTime()) && parsed.toISOString().slice(0, 10) === value;
4978
+ }
4979
+ function localDay(instant, timeZone) {
4980
+ return new Intl.DateTimeFormat("en-CA", { timeZone, year: "numeric", month: "2-digit", day: "2-digit" }).format(instant);
4981
+ }
4982
+ function daysBetween(from, to) {
4983
+ return Math.round((Date.parse(`${to}T00:00:00Z`) - Date.parse(`${from}T00:00:00Z`)) / 864e5);
4984
+ }
4985
+
4986
+ // src/waitlist/view.ts
4987
+ var VIEW_SELECT = {
4988
+ id: true,
4989
+ typeId: true,
4990
+ calendarId: true,
4991
+ day: true,
4992
+ slotStart: true,
4993
+ clientName: true,
4994
+ clientEmail: true,
4995
+ clientPhone: true,
4996
+ status: true,
4997
+ offerSlotStart: true,
4998
+ offerExpiresAt: true,
4999
+ createdAt: true
5000
+ };
5001
+ var LIVE_STATUSES = ["WAITING", "OFFERED", "ACCEPTING"];
5002
+
5003
+ // src/waitlist/join.ts
5004
+ var MAX_WAITING_PER_TYPE_DAY = 50;
5005
+ async function joinWaitlist(db, input, now = /* @__PURE__ */ new Date()) {
5006
+ const orgScope = [{ organizationId: input.organizationId }, { organizationId: null }];
5007
+ const type = await db.appointmentType.findFirst({
5008
+ where: { id: input.typeId, isActive: true, OR: orgScope },
5009
+ select: { id: true, duration: true, requiresPayment: true, intakeForm: true, calendars: { select: { calendarId: true } } }
5010
+ });
5011
+ if (!type) throw new SchedulingNotFoundError("Appointment type not found", "SCHED_1100", { typeId: input.typeId });
5012
+ if (type.requiresPayment) {
5013
+ throw new SchedulingValidationError("A waitlist is not available for a type that needs payment", "SCHED_1105", { typeId: input.typeId });
5014
+ }
5015
+ const intakeForm = Array.isArray(type.intakeForm) ? type.intakeForm : [];
5016
+ if (intakeForm.some((field) => field.required)) {
5017
+ throw new SchedulingValidationError("A waitlist is not available for a type with required questions", "SCHED_1110", { typeId: input.typeId });
5018
+ }
5019
+ const linked = type.calendars.map((c) => c.calendarId);
5020
+ if (input.calendarId && !linked.includes(input.calendarId)) {
5021
+ throw new SchedulingNotFoundError("Calendar not found for this type", "SCHED_1100", { calendarId: input.calendarId });
5022
+ }
5023
+ const calendars = await db.schedulingCalendar.findMany({
5024
+ where: { id: { in: input.calendarId ? [input.calendarId] : linked }, OR: orgScope },
5025
+ select: { id: true, timezone: true }
5026
+ });
5027
+ if (calendars.length === 0) throw new SchedulingNotFoundError("Calendar not found for this type", "SCHED_1100", { typeId: input.typeId });
5028
+ const timezone = calendars[0].timezone;
5029
+ if (!isDayString(input.day)) throw new SchedulingValidationError("The day must be YYYY-MM-DD", "SCHED_1101", { day: input.day });
5030
+ const ahead = daysBetween(localDay(now, timezone), input.day);
5031
+ if (ahead < 0 || ahead > MAX_DAYS_AHEAD) {
5032
+ throw new SchedulingValidationError(`The day must be within the next ${MAX_DAYS_AHEAD} days`, "SCHED_1101", { day: input.day });
5033
+ }
5034
+ if (input.slotStart) {
5035
+ if (Number.isNaN(input.slotStart.getTime()) || input.slotStart <= now || localDay(input.slotStart, timezone) !== input.day) {
5036
+ throw new SchedulingValidationError("The time must be in the future, on the chosen day", "SCHED_1102", { day: input.day });
5037
+ }
5038
+ }
5039
+ const open = [];
5040
+ for (const calendar of calendars) {
5041
+ const result = await getAvailableSlots(db, {
5042
+ calendarId: calendar.id,
5043
+ date: /* @__PURE__ */ new Date(`${input.day}T12:00:00Z`),
5044
+ localDate: input.day,
5045
+ duration: type.duration,
5046
+ timezone: calendar.timezone
5047
+ });
5048
+ for (const slot of result.slots) if (slot.available) open.push(slot.start);
5049
+ }
5050
+ const stillOpen = input.slotStart ? open.some((start) => start.getTime() === input.slotStart.getTime()) : open.length > 0;
5051
+ if (stillOpen) {
5052
+ throw new SchedulingValidationError("That time is open: book it instead of waiting", "SCHED_1103", { day: input.day });
5053
+ }
5054
+ const email2 = input.clientEmail.trim();
5055
+ const duplicate = await db.waitlistEntry.findFirst({
5056
+ where: {
5057
+ organizationId: input.organizationId,
5058
+ typeId: type.id,
5059
+ day: input.day,
5060
+ slotStart: input.slotStart ?? null,
5061
+ clientEmail: { equals: email2, mode: "insensitive" },
5062
+ status: { in: LIVE_STATUSES }
5063
+ },
5064
+ select: { id: true }
5065
+ });
5066
+ if (duplicate) throw new SchedulingValidationError("This email is already waiting for that day", "SCHED_1104", { day: input.day });
5067
+ const waiting = await db.waitlistEntry.count({ where: { organizationId: input.organizationId, typeId: type.id, day: input.day, status: "WAITING" } });
5068
+ if (waiting >= MAX_WAITING_PER_TYPE_DAY) {
5069
+ throw new SchedulingValidationError("The waitlist for that day is full", "SCHED_1108", { day: input.day });
5070
+ }
5071
+ const token = (0, import_node_crypto5.randomBytes)(24).toString("base64url");
5072
+ const entry4 = await db.waitlistEntry.create({
5073
+ data: {
5074
+ organizationId: input.organizationId,
5075
+ typeId: type.id,
5076
+ calendarId: input.calendarId ?? null,
5077
+ day: input.day,
5078
+ slotStart: input.slotStart ?? null,
5079
+ timezone,
5080
+ clientName: input.clientName.trim(),
5081
+ clientEmail: email2,
5082
+ clientPhone: input.clientPhone?.trim() || null,
5083
+ token
5084
+ },
5085
+ select: VIEW_SELECT
5086
+ });
5087
+ return { entry: entry4, token };
5088
+ }
5089
+
5090
+ // src/waitlist/accept.ts
5091
+ var ENTRY_SELECT = {
5092
+ id: true,
5093
+ organizationId: true,
5094
+ typeId: true,
5095
+ status: true,
5096
+ offerCalendarId: true,
5097
+ offerSlotStart: true,
5098
+ offerExpiresAt: true,
5099
+ clientName: true,
5100
+ clientEmail: true,
5101
+ clientPhone: true,
5102
+ timezone: true,
5103
+ type: { select: { name: true } }
5104
+ };
5105
+ async function loadOffer(db, token) {
5106
+ const entry4 = await db.waitlistEntry.findUnique({ where: { token }, select: ENTRY_SELECT });
5107
+ if (!entry4 || !entry4.offerCalendarId || !entry4.offerSlotStart || !entry4.offerExpiresAt) {
5108
+ throw new SchedulingNotFoundError("No open offer for this link", "SCHED_1106");
5109
+ }
5110
+ const calendar = await db.schedulingCalendar.findUnique({ where: { id: entry4.offerCalendarId }, select: { name: true } });
5111
+ return {
5112
+ status: entry4.status,
5113
+ details: {
5114
+ entryId: entry4.id,
5115
+ organizationId: entry4.organizationId,
5116
+ typeId: entry4.typeId,
5117
+ typeName: entry4.type.name,
5118
+ calendarId: entry4.offerCalendarId,
5119
+ calendarName: calendar?.name ?? "",
5120
+ startTime: entry4.offerSlotStart,
5121
+ timezone: entry4.timezone,
5122
+ expiresAt: entry4.offerExpiresAt,
5123
+ clientName: entry4.clientName,
5124
+ clientEmail: entry4.clientEmail,
5125
+ clientPhone: entry4.clientPhone
5126
+ }
5127
+ };
5128
+ }
5129
+ async function getWaitlistOffer(db, token, now = /* @__PURE__ */ new Date()) {
5130
+ const { details, status } = await loadOffer(db, token);
5131
+ if (status !== "OFFERED") throw new SchedulingNotFoundError("No open offer for this link", "SCHED_1106");
5132
+ if (details.expiresAt <= now) throw new SchedulingValidationError("The offer has expired", "SCHED_1107");
5133
+ return details;
5134
+ }
5135
+ async function beginWaitlistAccept(db, token, now = /* @__PURE__ */ new Date()) {
5136
+ const claimed = await db.waitlistEntry.updateMany({
5137
+ where: { token, status: "OFFERED", offerExpiresAt: { gt: now } },
5138
+ data: { status: "ACCEPTING", acceptingAt: now }
5139
+ });
5140
+ if (claimed.count === 0) {
5141
+ await getWaitlistOffer(db, token, now);
5142
+ throw new SchedulingNotFoundError("No open offer for this link", "SCHED_1106");
5143
+ }
5144
+ return (await loadOffer(db, token)).details;
5145
+ }
5146
+ async function completeWaitlistAccept(db, entryId, appointmentId) {
5147
+ await db.waitlistEntry.updateMany({
5148
+ where: { id: entryId, status: "ACCEPTING" },
5149
+ data: { status: "BOOKED", bookedAppointmentId: appointmentId }
5150
+ });
5151
+ }
5152
+ async function releaseWaitlistAccept(db, entryId, outcome = "BACK_IN_LINE") {
5153
+ const where = { id: entryId, status: "ACCEPTING" };
5154
+ if (outcome === "KEEP_OFFER") {
5155
+ await db.waitlistEntry.updateMany({ where, data: { status: "OFFERED", acceptingAt: null } });
5156
+ return null;
5157
+ }
5158
+ if (outcome === "BACK_IN_LINE") {
5159
+ await db.waitlistEntry.updateMany({
5160
+ where,
5161
+ data: { status: "WAITING", offerCalendarId: null, offerSlotStart: null, offerExpiresAt: null, offeredAt: null, acceptingAt: null }
5162
+ });
5163
+ return null;
5164
+ }
5165
+ const row = await db.waitlistEntry.findFirst({ where, select: { organizationId: true, offerCalendarId: true, offerSlotStart: true } });
5166
+ const ended = await db.waitlistEntry.updateMany({ where, data: { status: "EXPIRED", acceptingAt: null } });
5167
+ return row && ended.count > 0 && row.offerCalendarId && row.offerSlotStart ? { organizationId: row.organizationId, calendarId: row.offerCalendarId, startTime: row.offerSlotStart } : null;
5168
+ }
5169
+ async function findBookingForOffer(db, entry4) {
5170
+ if (!entry4.offerCalendarId || !entry4.offerSlotStart) return null;
5171
+ return db.appointment.findFirst({
5172
+ where: {
5173
+ calendarId: entry4.offerCalendarId,
5174
+ startTime: entry4.offerSlotStart,
5175
+ clientEmail: { equals: entry4.clientEmail, mode: "insensitive" },
5176
+ status: { in: ["PENDING", "CONFIRMED"] }
5177
+ },
5178
+ select: { id: true }
5179
+ });
5180
+ }
5181
+ async function settleBookedAccept(db, entryId) {
5182
+ const entry4 = await db.waitlistEntry.findFirst({
5183
+ where: { id: entryId, status: "ACCEPTING" },
5184
+ select: { offerCalendarId: true, offerSlotStart: true, clientEmail: true }
5185
+ });
5186
+ const found = entry4 ? await findBookingForOffer(db, entry4) : null;
5187
+ if (!found) return null;
5188
+ await db.waitlistEntry.updateMany({
5189
+ where: { id: entryId, status: "ACCEPTING" },
5190
+ data: { status: "BOOKED", bookedAppointmentId: found.id, acceptingAt: null }
5191
+ });
5192
+ return db.appointment.findUnique({
5193
+ where: { id: found.id },
5194
+ select: { id: true, status: true, startTime: true, endTime: true, manageToken: true, clientName: true, clientEmail: true }
5195
+ });
5196
+ }
5197
+
5198
+ // src/waitlist/offer.ts
5199
+ var DEFAULT_OFFER_MINUTES = 30;
5200
+ var CANDIDATES_PER_SLOT = 25;
5201
+ function isUniqueViolation(error) {
5202
+ return typeof error === "object" && error !== null && error.code === "P2002";
5203
+ }
5204
+ async function offerFreedSlot(db, input) {
5205
+ const now = input.now ?? /* @__PURE__ */ new Date();
5206
+ if (input.startTime <= now) return null;
5207
+ const calendar = await db.schedulingCalendar.findUnique({
5208
+ where: { id: input.calendarId },
5209
+ select: { name: true, timezone: true, organizationId: true }
5210
+ });
5211
+ if (!calendar || calendar.organizationId !== null && calendar.organizationId !== input.organizationId) return null;
5212
+ await db.waitlistEntry.updateMany({
5213
+ where: {
5214
+ organizationId: input.organizationId,
5215
+ status: "OFFERED",
5216
+ offerCalendarId: input.calendarId,
5217
+ offerSlotStart: input.startTime,
5218
+ offerExpiresAt: { lte: now }
5219
+ },
5220
+ data: { status: "EXPIRED" }
5221
+ });
5222
+ const candidates = await db.waitlistEntry.findMany({
5223
+ where: {
5224
+ organizationId: input.organizationId,
5225
+ status: "WAITING",
5226
+ day: localDay(input.startTime, calendar.timezone),
5227
+ // Only people whose type runs on this calendar, so earlier people it cannot fit never crowd out later ones that it can.
5228
+ type: { isActive: true, calendars: { some: { calendarId: input.calendarId } } },
5229
+ AND: [
5230
+ { OR: [{ calendarId: null }, { calendarId: input.calendarId }] },
5231
+ { OR: [{ slotStart: null }, { slotStart: input.startTime }] }
5232
+ ]
5233
+ },
5234
+ orderBy: { createdAt: "asc" },
5235
+ take: CANDIDATES_PER_SLOT,
5236
+ select: { ...VIEW_SELECT, token: true, timezone: true }
5237
+ });
5238
+ const expiresAt = new Date(Math.min(now.getTime() + (input.offerMinutes ?? DEFAULT_OFFER_MINUTES) * 6e4, input.startTime.getTime()));
5239
+ for (const candidate of candidates) {
5240
+ const type = await db.appointmentType.findFirst({
5241
+ where: { id: candidate.typeId, isActive: true, calendars: { some: { calendarId: input.calendarId } } },
5242
+ select: { name: true, duration: true }
5243
+ });
5244
+ if (!type || !await isSlotAvailable(db, input.calendarId, input.startTime, type.duration)) continue;
5245
+ let claimed;
5246
+ try {
5247
+ claimed = await db.waitlistEntry.updateMany({
5248
+ where: { id: candidate.id, status: "WAITING" },
5249
+ data: { status: "OFFERED", offerCalendarId: input.calendarId, offerSlotStart: input.startTime, offerExpiresAt: expiresAt, offeredAt: now }
5250
+ });
5251
+ } catch (error) {
5252
+ if (isUniqueViolation(error)) return null;
5253
+ throw error;
5254
+ }
5255
+ if (claimed.count === 0) continue;
5256
+ const { token, timezone, ...view2 } = candidate;
5257
+ return {
5258
+ entry: { ...view2, status: "OFFERED", offerSlotStart: input.startTime, offerExpiresAt: expiresAt },
5259
+ token,
5260
+ calendarId: input.calendarId,
5261
+ calendarName: calendar.name,
5262
+ typeName: type.name,
5263
+ startTime: input.startTime,
5264
+ timezone,
5265
+ expiresAt
5266
+ };
5267
+ }
5268
+ return null;
5269
+ }
5270
+ async function tryOfferFreedSlot(db, input) {
5271
+ try {
5272
+ return await offerFreedSlot(db, input);
5273
+ } catch (error) {
5274
+ const diagnostic = schedError("SCHED_1109", { organizationId: input.organizationId, calendarId: input.calendarId, error });
5275
+ console.error(`[waitlist] ${diagnostic.ref} could not offer a freed slot:`, error);
5276
+ return null;
5277
+ }
5278
+ }
5279
+ async function expireWaitlistOffers(db, options = {}) {
5280
+ const now = options.now ?? /* @__PURE__ */ new Date();
5281
+ const stuckBefore = new Date(now.getTime() - (options.acceptTimeoutMs ?? 5 * 6e4));
5282
+ const rows = await db.$queryRaw`
5283
+ UPDATE "WaitlistEntry" SET status = 'EXPIRED'
5284
+ WHERE status = 'OFFERED' AND "offerExpiresAt" <= ${now}
5285
+ RETURNING "organizationId", "offerCalendarId", "offerSlotStart"
5286
+ `;
5287
+ const lapsed = rows.map((r) => ({ organizationId: r.organizationId, calendarId: r.offerCalendarId, startTime: r.offerSlotStart }));
5288
+ const stuck = await db.waitlistEntry.findMany({
5289
+ where: { status: "ACCEPTING", acceptingAt: { lte: stuckBefore } },
5290
+ take: 100,
5291
+ select: { id: true, organizationId: true, offerCalendarId: true, offerSlotStart: true, clientEmail: true }
5292
+ });
5293
+ let released = 0;
5294
+ let booked = 0;
5295
+ for (const entry4 of stuck) {
5296
+ const appointment = await findBookingForOffer(db, entry4);
5297
+ if (appointment) {
5298
+ const done = await db.waitlistEntry.updateMany({
5299
+ where: { id: entry4.id, status: "ACCEPTING" },
5300
+ data: { status: "BOOKED", bookedAppointmentId: appointment.id, acceptingAt: null }
5301
+ });
5302
+ booked += done.count;
5303
+ continue;
5304
+ }
5305
+ const back = await db.waitlistEntry.updateMany({
5306
+ where: { id: entry4.id, status: "ACCEPTING" },
5307
+ data: { status: "WAITING", offerCalendarId: null, offerSlotStart: null, offerExpiresAt: null, offeredAt: null, acceptingAt: null }
5308
+ });
5309
+ if (back.count > 0) {
5310
+ released++;
5311
+ if (entry4.offerCalendarId && entry4.offerSlotStart) {
5312
+ lapsed.push({ organizationId: entry4.organizationId, calendarId: entry4.offerCalendarId, startTime: entry4.offerSlotStart });
5313
+ }
5314
+ }
5315
+ }
5316
+ return { lapsed, released, booked };
5317
+ }
5318
+
5319
+ // src/waitlist/manage.ts
5320
+ var OFFER_FIELDS = { organizationId: true, status: true, offerCalendarId: true, offerSlotStart: true };
5321
+ function freedSlot(row) {
5322
+ return row.status === "OFFERED" && row.offerCalendarId && row.offerSlotStart ? { organizationId: row.organizationId, calendarId: row.offerCalendarId, startTime: row.offerSlotStart } : null;
5323
+ }
5324
+ async function listWaitlist(db, input) {
5325
+ const where = { organizationId: input.organizationId, ...input.status ? { status: input.status } : {} };
5326
+ const [entries, total] = await Promise.all([
5327
+ db.waitlistEntry.findMany({
5328
+ where,
5329
+ orderBy: { createdAt: "asc" },
5330
+ take: Math.min(input.limit ?? 50, 200),
5331
+ skip: input.offset ?? 0,
5332
+ select: VIEW_SELECT
5333
+ }),
5334
+ db.waitlistEntry.count({ where })
5335
+ ]);
5336
+ return { entries, total };
5337
+ }
5338
+ async function removeWaitlistEntry(db, organizationId, entryId) {
5339
+ const where = { id: entryId, organizationId, status: { in: ["WAITING", "OFFERED", "EXPIRED", "BOOKED"] } };
5340
+ const row = await db.waitlistEntry.findFirst({ where, select: OFFER_FIELDS });
5341
+ const removed = row ? await db.waitlistEntry.deleteMany({ where: { ...where, status: row.status } }) : { count: 0 };
5342
+ if (!row || removed.count === 0) throw new SchedulingNotFoundError("Waitlist entry not found", "SCHED_1106", { entryId });
5343
+ return freedSlot(row);
5344
+ }
5345
+ async function leaveWaitlist(db, token) {
5346
+ const where = { token, status: { in: ["WAITING", "OFFERED"] } };
5347
+ const row = await db.waitlistEntry.findFirst({ where, select: OFFER_FIELDS });
5348
+ const removed = row ? await db.waitlistEntry.deleteMany({ where: { ...where, status: row.status } }) : { count: 0 };
5349
+ if (!row || removed.count === 0) throw new SchedulingNotFoundError("No waitlist entry for this link", "SCHED_1106");
5350
+ return freedSlot(row);
5351
+ }
5352
+
5353
+ // src/routing/types.ts
5354
+ var LIMITS = {
5355
+ questions: 20,
5356
+ rules: 50,
5357
+ conditionsPerRule: 10,
5358
+ options: 50,
5359
+ label: 200,
5360
+ option: 100,
5361
+ message: 500,
5362
+ textAnswer: 1e3,
5363
+ problems: 50,
5364
+ formsPerOrganization: 50
5365
+ };
5366
+
5367
+ // src/routing/validate-structure.ts
5368
+ var ID = /^[A-Za-z][A-Za-z0-9_-]{0,39}$/;
5369
+ var QUESTION_TYPES = ["select", "radio", "checkbox", "text", "number"];
5370
+ var NO_VALUE = ["is_answered", "is_empty"];
5371
+ var OPERATORS_BY_TYPE = {
5372
+ select: ["equals", "not_equals", "in", "is_answered", "is_empty"],
5373
+ radio: ["equals", "not_equals", "in", "is_answered", "is_empty"],
5374
+ checkbox: ["contains", "not_contains", "is_answered", "is_empty"],
5375
+ text: ["equals", "not_equals", "contains", "not_contains", "is_answered", "is_empty"],
5376
+ number: ["equals", "not_equals", "gt", "gte", "lt", "lte", "is_answered", "is_empty"]
5377
+ };
5378
+ var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5379
+ var isText = (value, max) => typeof value === "string" && value.trim().length > 0 && value.length <= max && !value.includes("\0");
5380
+ function checkQuestions(input, problems) {
5381
+ if (!Array.isArray(input) || input.length === 0) {
5382
+ problems.push({ path: "questions", message: "Add at least one question" });
5383
+ return [];
5384
+ }
5385
+ if (input.length > LIMITS.questions) problems.push({ path: "questions", message: `At most ${LIMITS.questions} questions` });
5386
+ const seen = /* @__PURE__ */ new Set();
5387
+ const questions = [];
5388
+ input.slice(0, LIMITS.questions).forEach((raw, i) => {
5389
+ const at = `questions[${i}]`;
5390
+ if (!isObject(raw)) return void problems.push({ path: at, message: "A question must be an object" });
5391
+ const { id, label, type, required, options } = raw;
5392
+ 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)" });
5393
+ else if (seen.has(id)) problems.push({ path: `${at}.id`, message: `Another question already uses the id "${id}"` });
5394
+ else seen.add(id);
5395
+ if (!isText(label, LIMITS.label)) problems.push({ path: `${at}.label`, message: `A label of 1 to ${LIMITS.label} characters is required` });
5396
+ if (!QUESTION_TYPES.includes(type)) problems.push({ path: `${at}.type`, message: `The type must be one of ${QUESTION_TYPES.join(", ")}` });
5397
+ if (required !== void 0 && typeof required !== "boolean") problems.push({ path: `${at}.required`, message: "required must be true or false" });
5398
+ const choice = type === "select" || type === "radio" || type === "checkbox";
5399
+ let cleanOptions;
5400
+ if (choice) {
5401
+ if (!Array.isArray(options) || options.length < 2 || options.length > LIMITS.options) {
5402
+ problems.push({ path: `${at}.options`, message: `A choice question needs 2 to ${LIMITS.options} options` });
5403
+ } else if (!options.every((o) => isText(o, LIMITS.option))) {
5404
+ problems.push({ path: `${at}.options`, message: `Each option must be 1 to ${LIMITS.option} characters` });
5405
+ } else if (new Set(options).size !== options.length) {
5406
+ problems.push({ path: `${at}.options`, message: "Options must all be different" });
5407
+ } else cleanOptions = options;
5408
+ } else if (options !== void 0) {
5409
+ problems.push({ path: `${at}.options`, message: "Only choice questions have options" });
5410
+ }
5411
+ if (typeof id === "string" && typeof label === "string" && QUESTION_TYPES.includes(type)) {
5412
+ questions.push({ id, label: label.trim(), type, required: required === true, ...cleanOptions ? { options: cleanOptions } : {} });
5413
+ }
5414
+ });
5415
+ return questions;
5416
+ }
5417
+ function checkValue(question, condition, at, problems) {
5418
+ const { operator, value } = condition;
5419
+ if (NO_VALUE.includes(operator)) {
5420
+ if (value !== void 0) problems.push({ path: `${at}.value`, message: `${String(operator)} takes no value` });
5421
+ return void 0;
5422
+ }
5423
+ if (value === void 0) {
5424
+ problems.push({ path: `${at}.value`, message: "A value is required" });
5425
+ return void 0;
5426
+ }
5427
+ if (question.type === "number") {
5428
+ if (typeof value !== "number" || !Number.isFinite(value)) problems.push({ path: `${at}.value`, message: "The value must be a number" });
5429
+ else return value;
5430
+ return void 0;
5431
+ }
5432
+ if (question.type === "text") {
5433
+ if (!isText(value, LIMITS.option * 2)) problems.push({ path: `${at}.value`, message: "The value must be a text of 1 to 200 characters" });
5434
+ else return value;
5435
+ return void 0;
5436
+ }
5437
+ const options = question.options ?? [];
5438
+ if (operator === "in") {
5439
+ if (!Array.isArray(value) || value.length === 0 || !value.every((v) => typeof v === "string" && options.includes(v))) {
5440
+ problems.push({ path: `${at}.value`, message: "The value must be a list of this question's options" });
5441
+ return void 0;
5442
+ }
5443
+ return value;
5444
+ }
5445
+ if (typeof value !== "string" || !options.includes(value)) {
5446
+ problems.push({ path: `${at}.value`, message: "The value must be one of this question's options" });
5447
+ return void 0;
5448
+ }
5449
+ return value;
5450
+ }
5451
+ function checkDestination(raw, at, problems) {
5452
+ if (!isObject(raw)) {
5453
+ problems.push({ path: at, message: "Say where to send the client" });
5454
+ return null;
5455
+ }
5456
+ const { typeId, calendarId } = raw;
5457
+ const okType = typeId === void 0 || typeof typeId === "string" && typeId.length > 0 && typeId.length <= 100;
5458
+ const okCalendar = calendarId === void 0 || typeof calendarId === "string" && calendarId.length > 0 && calendarId.length <= 100;
5459
+ if (!okType || !okCalendar) {
5460
+ problems.push({ path: at, message: "typeId and calendarId must be ids" });
5461
+ return null;
5462
+ }
5463
+ if (typeId === void 0 && calendarId === void 0) {
5464
+ problems.push({ path: at, message: "Name an appointment type, a calendar, or both" });
5465
+ return null;
5466
+ }
5467
+ return { ...typeId !== void 0 ? { typeId } : {}, ...calendarId !== void 0 ? { calendarId } : {} };
5468
+ }
5469
+ function checkRules(input, questions, problems) {
5470
+ if (!Array.isArray(input) || input.length === 0) {
5471
+ problems.push({ path: "rules", message: "Add at least one rule" });
5472
+ return [];
5473
+ }
5474
+ if (input.length > LIMITS.rules) problems.push({ path: "rules", message: `At most ${LIMITS.rules} rules` });
5475
+ const byId = new Map(questions.map((q) => [q.id, q]));
5476
+ const written = new Set(input.flatMap((r) => isObject(r) && typeof r.id === "string" ? [r.id] : []));
5477
+ const seen = /* @__PURE__ */ new Set();
5478
+ const rules = [];
5479
+ input.slice(0, LIMITS.rules).forEach((raw, i) => {
5480
+ const at = `rules[${i}]`;
5481
+ if (!isObject(raw)) return void problems.push({ path: at, message: "A rule must be an object" });
5482
+ let id = typeof raw.id === "string" && ID.test(raw.id) ? raw.id : null;
5483
+ 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 _" });
5484
+ if (id === null) {
5485
+ id = `rule_${i + 1}`;
5486
+ while (written.has(id)) id = `${id}_auto`;
5487
+ }
5488
+ if (seen.has(id)) problems.push({ path: `${at}.id`, message: `Another rule already uses the id "${id}"` });
5489
+ seen.add(id);
5490
+ 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` });
5491
+ const match = raw.match === void 0 ? "all" : raw.match;
5492
+ if (match !== "all" && match !== "any") problems.push({ path: `${at}.match`, message: 'match must be "all" or "any"' });
5493
+ const conditions = [];
5494
+ if (!Array.isArray(raw.conditions) || raw.conditions.length === 0 || raw.conditions.length > LIMITS.conditionsPerRule) {
5495
+ problems.push({ path: `${at}.conditions`, message: `A rule needs 1 to ${LIMITS.conditionsPerRule} conditions` });
5496
+ } else {
5497
+ raw.conditions.forEach((c, j) => {
5498
+ const cat = `${at}.conditions[${j}]`;
5499
+ if (!isObject(c)) return void problems.push({ path: cat, message: "A condition must be an object" });
5500
+ const question = typeof c.questionId === "string" ? byId.get(c.questionId) : void 0;
5501
+ if (!question) return void problems.push({ path: `${cat}.questionId`, message: "This names a question the form does not have" });
5502
+ if (!OPERATORS_BY_TYPE[question.type].includes(c.operator)) {
5503
+ return void problems.push({ path: `${cat}.operator`, message: `A ${question.type} question allows: ${OPERATORS_BY_TYPE[question.type].join(", ")}` });
5504
+ }
5505
+ const value = checkValue(question, c, cat, problems);
5506
+ conditions.push({ questionId: question.id, operator: c.operator, ...value !== void 0 ? { value } : {} });
5507
+ });
5508
+ }
5509
+ const destination = checkDestination(raw.destination, `${at}.destination`, problems);
5510
+ if (destination && (match === "all" || match === "any")) {
5511
+ rules.push({ id, ...typeof raw.label === "string" ? { label: raw.label.trim() } : {}, match, conditions, destination });
5512
+ }
5513
+ });
5514
+ return rules;
5515
+ }
5516
+ function checkFallback(raw, problems) {
5517
+ if (!isObject(raw)) {
5518
+ problems.push({ path: "fallback", message: "Say what happens when no rule matches" });
5519
+ return null;
5520
+ }
5521
+ if (raw.kind === "MESSAGE") {
5522
+ if (!isText(raw.message, LIMITS.message)) {
5523
+ problems.push({ path: "fallback.message", message: `A message of 1 to ${LIMITS.message} characters is required` });
5524
+ return null;
5525
+ }
5526
+ return { kind: "MESSAGE", message: raw.message.trim() };
5527
+ }
5528
+ if (raw.kind === "DESTINATION") {
5529
+ const destination = checkDestination(raw.destination, "fallback.destination", problems);
5530
+ return destination ? { kind: "DESTINATION", destination } : null;
5531
+ }
5532
+ problems.push({ path: "fallback.kind", message: 'kind must be "DESTINATION" or "MESSAGE"' });
5533
+ return null;
5534
+ }
5535
+ function validateRoutingStructure(input) {
5536
+ const problems = [];
5537
+ if (!isObject(input)) return { ok: false, problems: [{ path: "", message: "A routing form must be an object" }] };
5538
+ const questions = checkQuestions(input.questions, problems);
5539
+ const rules = checkRules(input.rules, questions, problems);
5540
+ const fallback = checkFallback(input.fallback, problems);
5541
+ if (problems.length > 0 || !fallback) return { ok: false, problems: problems.slice(0, LIMITS.problems) };
5542
+ return { ok: true, value: { questions, rules, fallback } };
5543
+ }
5544
+
5545
+ // src/routing/validate-destinations.ts
5546
+ function placesOf(definition) {
5547
+ const places = definition.rules.map((rule, i) => ({ path: `rules[${i}].destination`, destination: rule.destination }));
5548
+ if (definition.fallback.kind === "DESTINATION") places.push({ path: "fallback.destination", destination: definition.fallback.destination });
5549
+ return places;
5550
+ }
5551
+ async function validateRoutingDestinations(db, organizationId, definition) {
5552
+ const places = placesOf(definition);
5553
+ const typeIds = [...new Set(places.flatMap((p) => p.destination.typeId ? [p.destination.typeId] : []))];
5554
+ const calendarIds = [...new Set(places.flatMap((p) => p.destination.calendarId ? [p.destination.calendarId] : []))];
5555
+ const scope = [{ organizationId }, { organizationId: null }];
5556
+ const [types, calendars] = await Promise.all([
5557
+ typeIds.length ? db.appointmentType.findMany({ where: { id: { in: typeIds }, isActive: true, OR: scope }, select: { id: true } }) : [],
5558
+ calendarIds.length ? db.schedulingCalendar.findMany({ where: { id: { in: calendarIds }, isActive: true, OR: scope }, select: { id: true } }) : []
5559
+ ]);
5560
+ const liveTypes = new Set(types.map((t) => t.id));
5561
+ const liveCalendars = new Set(calendars.map((c) => c.id));
5562
+ const problems = [];
5563
+ const pairs = [];
5564
+ for (const { path, destination } of places) {
5565
+ const typeOk = !destination.typeId || liveTypes.has(destination.typeId);
5566
+ const calendarOk = !destination.calendarId || liveCalendars.has(destination.calendarId);
5567
+ if (!typeOk) problems.push({ path: `${path}.typeId`, message: "This appointment type does not exist here or is switched off" });
5568
+ if (!calendarOk) problems.push({ path: `${path}.calendarId`, message: "This calendar does not exist here or is switched off" });
5569
+ if (typeOk && calendarOk && destination.typeId && destination.calendarId) pairs.push({ path, destination });
5570
+ }
5571
+ if (pairs.length > 0) {
5572
+ const links = await db.appointmentTypeCalendar.findMany({
5573
+ where: { OR: pairs.map((p) => ({ appointmentTypeId: p.destination.typeId, calendarId: p.destination.calendarId })) },
5574
+ select: { appointmentTypeId: true, calendarId: true }
5575
+ });
5576
+ const linked = new Set(links.map((l) => `${l.appointmentTypeId}:${l.calendarId}`));
5577
+ for (const { path, destination } of pairs) {
5578
+ if (!linked.has(`${destination.typeId}:${destination.calendarId}`)) {
5579
+ problems.push({ path, message: "This appointment type is not offered on this calendar" });
5580
+ }
5581
+ }
5582
+ }
5583
+ return problems;
5584
+ }
5585
+
5586
+ // src/routing/evaluate.ts
5587
+ var blank = (value) => value === void 0 || value === null || value === "" || Array.isArray(value) && value.length === 0;
5588
+ function checkAnswers(questions, input) {
5589
+ const problems = [];
5590
+ const raw = typeof input === "object" && input !== null && !Array.isArray(input) ? input : {};
5591
+ if (input !== void 0 && raw !== input) problems.push({ path: "answers", message: "Answers must be an object keyed by question id" });
5592
+ const known = new Set(questions.map((q) => q.id));
5593
+ for (const key of Object.keys(raw)) if (!known.has(key)) problems.push({ path: `answers.${key}`, message: "The form does not ask this question" });
5594
+ const answers = /* @__PURE__ */ Object.create(null);
5595
+ for (const q of questions) {
5596
+ const at = `answers.${q.id}`;
5597
+ const value = Object.prototype.hasOwnProperty.call(raw, q.id) ? raw[q.id] : void 0;
5598
+ if (blank(value)) {
5599
+ if (q.required) problems.push({ path: at, message: "This question needs an answer" });
5600
+ continue;
5601
+ }
5602
+ if (q.type === "select" || q.type === "radio") {
5603
+ if (typeof value !== "string" || !q.options?.includes(value)) problems.push({ path: at, message: "Pick one of the offered options" });
5604
+ else answers[q.id] = value;
5605
+ } else if (q.type === "checkbox") {
5606
+ if (!Array.isArray(value) || !value.every((v) => typeof v === "string" && q.options?.includes(v)) || new Set(value).size !== value.length) {
5607
+ problems.push({ path: at, message: "Send a list of offered options, each once" });
5608
+ } else answers[q.id] = value;
5609
+ } else if (q.type === "number") {
5610
+ if (typeof value !== "number" || !Number.isFinite(value)) problems.push({ path: at, message: "The answer must be a number" });
5611
+ else answers[q.id] = value;
5612
+ } else if (typeof value !== "string" || value.length > LIMITS.textAnswer) {
5613
+ problems.push({ path: at, message: `The answer must be a text of at most ${LIMITS.textAnswer} characters` });
5614
+ } else answers[q.id] = value;
5615
+ }
5616
+ return problems.length > 0 ? { ok: false, problems: problems.slice(0, LIMITS.problems) } : { ok: true, answers };
5617
+ }
5618
+ function holds(condition, answers) {
5619
+ const answer = answers[condition.questionId];
5620
+ const { operator, value } = condition;
5621
+ if (operator === "is_empty") return blank(answer);
5622
+ if (operator === "is_answered") return !blank(answer);
5623
+ if (blank(answer)) return false;
5624
+ if (typeof answer === "number") {
5625
+ if (typeof value !== "number") return false;
5626
+ return { equals: answer === value, not_equals: answer !== value, gt: answer > value, gte: answer >= value, lt: answer < value, lte: answer <= value }[operator] ?? false;
5627
+ }
5628
+ if (Array.isArray(answer)) {
5629
+ if (typeof value !== "string") return false;
5630
+ return operator === "contains" ? answer.includes(value) : operator === "not_contains" ? !answer.includes(value) : false;
5631
+ }
5632
+ if (operator === "in") return Array.isArray(value) && value.includes(answer);
5633
+ if (typeof value !== "string") return false;
5634
+ const a = answer;
5635
+ switch (operator) {
5636
+ case "equals":
5637
+ return a === value;
5638
+ case "not_equals":
5639
+ return a !== value;
5640
+ case "contains":
5641
+ return a.toLowerCase().includes(value.toLowerCase());
5642
+ case "not_contains":
5643
+ return !a.toLowerCase().includes(value.toLowerCase());
5644
+ default:
5645
+ return false;
5646
+ }
5647
+ }
5648
+ function matchingRules(definition, answers) {
5649
+ return definition.rules.filter(
5650
+ (rule) => rule.match === "any" ? rule.conditions.some((c) => holds(c, answers)) : rule.conditions.every((c) => holds(c, answers))
5651
+ );
5652
+ }
5653
+
5654
+ // src/routing/crud.ts
5655
+ var SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
5656
+ var FULL = { id: true, name: true, slug: true, description: true, isActive: true, questions: true, rules: true, fallback: true, createdAt: true, updatedAt: true };
5657
+ function invalid(problems) {
5658
+ return new SchedulingValidationError("The routing form has problems", "SCHED_1200", { errors: problems });
5659
+ }
5660
+ function view(row) {
5661
+ return { ...row, questions: row.questions, rules: row.rules, fallback: row.fallback };
5662
+ }
5663
+ async function check(db, organizationId, input, options) {
5664
+ const problems = [];
5665
+ const name = typeof input.name === "string" ? input.name.trim() : "";
5666
+ if (name.length < 1 || name.length > 100 || name.includes("\0")) problems.push({ path: "name", message: "A name of 1 to 100 characters is required" });
5667
+ if (typeof input.slug !== "string" || !SLUG.test(input.slug) || input.slug.length > 60) {
5668
+ problems.push({ path: "slug", message: "The slug must be lower-case words joined by dashes, 60 characters at most" });
5669
+ } else {
5670
+ const taken = await db.routingForm.count({ where: { slug: input.slug, organizationId: { not: organizationId } } });
5671
+ if (taken > 0) problems.push({ path: "slug", message: "That slug is already in use; choose another" });
5672
+ }
5673
+ const description = typeof input.description === "string" ? input.description.trim() || null : null;
5674
+ if (description && (description.length > 500 || description.includes("\0"))) problems.push({ path: "description", message: "The description is at most 500 characters" });
5675
+ const structure = validateRoutingStructure({ questions: input.questions, rules: input.rules, fallback: input.fallback });
5676
+ if (!structure.ok) problems.push(...structure.problems);
5677
+ else if (options.checkDestinations) problems.push(...await validateRoutingDestinations(db, organizationId, structure.value));
5678
+ if (problems.length > 0 || !structure.ok) throw invalid(problems.slice(0, LIMITS.problems));
5679
+ return { definition: structure.value, name, slug: input.slug, description };
5680
+ }
5681
+ async function createRoutingForm(db, organizationId, input) {
5682
+ const { definition, name, slug, description } = await check(db, organizationId, input, { checkDestinations: true });
5683
+ const existing = await db.routingForm.count({ where: { organizationId } });
5684
+ if (existing >= LIMITS.formsPerOrganization) {
5685
+ throw new SchedulingValidationError(`An organization can have at most ${LIMITS.formsPerOrganization} routing forms`, "SCHED_1204", { organizationId });
5686
+ }
5687
+ try {
5688
+ const row = await db.routingForm.create({
5689
+ data: {
5690
+ organizationId,
5691
+ name,
5692
+ slug,
5693
+ description,
5694
+ isActive: input.isActive ?? true,
5695
+ questions: definition.questions,
5696
+ rules: definition.rules,
5697
+ fallback: definition.fallback
5698
+ },
5699
+ select: FULL
5700
+ });
5701
+ return view(row);
5702
+ } catch (error) {
5703
+ if (error.code === "P2002") throw new SchedulingValidationError("That slug is already used by another form", "SCHED_1202", { slug });
5704
+ throw error;
5705
+ }
5706
+ }
5707
+ async function getRoutingForm(db, organizationId, id) {
5708
+ const row = await db.routingForm.findFirst({ where: { id, organizationId }, select: FULL });
5709
+ if (!row) throw new SchedulingNotFoundError("Routing form not found", "SCHED_1201", { id });
5710
+ return view(row);
5711
+ }
5712
+ async function listRoutingForms(db, organizationId) {
5713
+ return db.routingForm.findMany({
5714
+ where: { organizationId },
5715
+ orderBy: { name: "asc" },
5716
+ select: { id: true, name: true, slug: true, description: true, isActive: true, updatedAt: true }
5717
+ });
5718
+ }
5719
+ async function updateRoutingForm(db, organizationId, id, patch) {
5720
+ const current = await getRoutingForm(db, organizationId, id);
5721
+ const merged = {
5722
+ name: patch.name ?? current.name,
5723
+ slug: patch.slug ?? current.slug,
5724
+ description: patch.description === void 0 ? current.description : patch.description,
5725
+ isActive: patch.isActive ?? current.isActive,
5726
+ questions: patch.questions ?? current.questions,
5727
+ rules: patch.rules ?? current.rules,
5728
+ fallback: patch.fallback ?? current.fallback
5729
+ };
5730
+ const changesRouting = patch.questions !== void 0 || patch.rules !== void 0 || patch.fallback !== void 0;
5731
+ const { definition, name, slug, description } = await check(db, organizationId, merged, { checkDestinations: changesRouting });
5732
+ try {
5733
+ const updated = await db.routingForm.updateMany({
5734
+ where: { id, organizationId },
5735
+ data: {
5736
+ name,
5737
+ slug,
5738
+ description,
5739
+ isActive: merged.isActive,
5740
+ questions: definition.questions,
5741
+ rules: definition.rules,
5742
+ fallback: definition.fallback
5743
+ }
5744
+ });
5745
+ if (updated.count === 0) throw new SchedulingNotFoundError("Routing form not found", "SCHED_1201", { id });
5746
+ } catch (error) {
5747
+ if (error.code === "P2002") throw new SchedulingValidationError("That slug is already used by another form", "SCHED_1202", { slug });
5748
+ throw error;
5749
+ }
5750
+ return getRoutingForm(db, organizationId, id);
5751
+ }
5752
+ async function deleteRoutingForm(db, organizationId, id) {
5753
+ const removed = await db.routingForm.deleteMany({ where: { id, organizationId } });
5754
+ if (removed.count === 0) throw new SchedulingNotFoundError("Routing form not found", "SCHED_1201", { id });
5755
+ }
5756
+
5757
+ // src/routing/route.ts
5758
+ var UNAVAILABLE = "Online booking is not available for this choice right now. Please contact us to book.";
5759
+ async function findForm(db, organizationId, slug) {
5760
+ const select = { organizationId: true, name: true, slug: true, description: true, questions: true, rules: true, fallback: true };
5761
+ if (organizationId) return db.routingForm.findFirst({ where: { organizationId, slug, isActive: true }, select });
5762
+ const found = await db.routingForm.findMany({ where: { slug, isActive: true }, take: 2, select });
5763
+ return found.length === 1 ? found[0] : null;
5764
+ }
5765
+ async function load(db, organizationId, slug) {
5766
+ const row = await findForm(db, organizationId, slug);
5767
+ if (!row) throw new SchedulingNotFoundError("Routing form not found", "SCHED_1201", { slug });
5768
+ return row;
5769
+ }
5770
+ async function getPublicRoutingForm(db, input) {
5771
+ const row = await load(db, input.organizationId, input.slug);
5772
+ return { name: row.name, slug: row.slug, description: row.description, questions: row.questions };
5773
+ }
5774
+ async function resolveDestination(db, organizationId, destination) {
5775
+ const scope = [{ organizationId }, { organizationId: null }];
5776
+ const [type, calendar] = await Promise.all([
5777
+ destination.typeId ? db.appointmentType.findFirst({ where: { id: destination.typeId, isActive: true, OR: scope }, select: { id: true, slug: true, name: true } }) : null,
5778
+ destination.calendarId ? db.schedulingCalendar.findFirst({ where: { id: destination.calendarId, isActive: true, OR: scope }, select: { id: true, slug: true, name: true } }) : null
5779
+ ]);
5780
+ if (destination.typeId && !type || destination.calendarId && !calendar) return null;
5781
+ if (type && calendar) {
5782
+ const link = await db.appointmentTypeCalendar.findUnique({
5783
+ where: { appointmentTypeId_calendarId: { appointmentTypeId: type.id, calendarId: calendar.id } },
5784
+ select: { calendarId: true }
5785
+ });
5786
+ if (!link) return null;
5787
+ }
5788
+ return {
5789
+ typeId: type?.id ?? null,
5790
+ typeSlug: type?.slug ?? null,
5791
+ typeName: type?.name ?? null,
5792
+ calendarId: calendar?.id ?? null,
5793
+ calendarSlug: calendar?.slug ?? null,
5794
+ calendarName: calendar?.name ?? null
5795
+ };
5796
+ }
5797
+ async function decide(db, organizationId, definition, answers) {
5798
+ const checked = checkAnswers(definition.questions, answers);
5799
+ if (!checked.ok) throw new SchedulingValidationError("The answers do not fit the form", "SCHED_1203", { errors: checked.problems });
5800
+ for (const rule of matchingRules(definition, checked.answers)) {
5801
+ const destination = await resolveDestination(db, organizationId, rule.destination);
5802
+ if (destination) return { destination, message: null, matchedRuleId: rule.id, usedFallback: false };
5803
+ }
5804
+ if (definition.fallback.kind === "DESTINATION") {
5805
+ const destination = await resolveDestination(db, organizationId, definition.fallback.destination);
5806
+ return { destination, message: destination ? null : UNAVAILABLE, matchedRuleId: null, usedFallback: true };
5807
+ }
5808
+ return { destination: null, message: definition.fallback.message, matchedRuleId: null, usedFallback: true };
5809
+ }
5810
+ async function routeClient(db, input) {
5811
+ const row = await load(db, input.organizationId, input.slug);
5812
+ return decide(db, row.organizationId, row, input.answers);
5813
+ }
5814
+ async function testRoutingForm(db, input) {
5815
+ const row = await db.routingForm.findFirst({
5816
+ where: { id: input.id, organizationId: input.organizationId },
5817
+ select: { questions: true, rules: true, fallback: true }
5818
+ });
5819
+ if (!row) throw new SchedulingNotFoundError("Routing form not found", "SCHED_1201", { id: input.id });
5820
+ const definition = row;
5821
+ const outcome = await decide(db, input.organizationId, definition, input.answers);
5822
+ const checked = checkAnswers(definition.questions, input.answers);
5823
+ const allMatchedRuleIds = checked.ok ? matchingRules(definition, checked.answers).map((r) => r.id) : [];
5824
+ return { ...outcome, allMatchedRuleIds };
5825
+ }
5826
+
5827
+ // src/privacy/subject.ts
5828
+ var import_node_crypto6 = require("crypto");
5829
+ var EMAIL2 = /^[^\s@]+@[^\s@]+$/;
5830
+ function invalid2(reason) {
5831
+ return new SchedulingValidationError(`Say whose data this is: ${reason}`, "SCHED_1300", { reason });
5832
+ }
5833
+ function parseSubject(input) {
5834
+ let email2 = null;
5835
+ let clientId = null;
5836
+ if (input.email !== void 0 && input.email !== null) {
5837
+ if (typeof input.email !== "string") throw invalid2("the email must be text");
5838
+ const trimmed = input.email.trim().toLowerCase();
5839
+ if (trimmed.length > 254 || !EMAIL2.test(trimmed)) throw invalid2("the email is not a single valid address");
5840
+ email2 = trimmed;
5841
+ }
5842
+ if (input.clientId !== void 0 && input.clientId !== null) {
5843
+ if (typeof input.clientId !== "string") throw invalid2("the client id must be text");
5844
+ const trimmed = input.clientId.trim();
5845
+ if (trimmed.length < 1 || trimmed.length > 200) throw invalid2("the client id must be 1 to 200 characters");
5846
+ clientId = trimmed;
5847
+ }
5848
+ if (!email2 && !clientId) throw invalid2("send an email address, a client id, or both");
5849
+ return { email: email2, clientId };
5850
+ }
5851
+ function subjectHashes(organizationId, subject) {
5852
+ const identifiers = [...subject.emails, ...subject.clientId ? [`client:${subject.clientId}`] : []];
5853
+ return identifiers.map((identifier) => (0, import_node_crypto6.createHash)("sha256").update(`${organizationId}
5854
+ ${identifier}`).digest("hex"));
5855
+ }
5856
+ async function resolveSubject(db, organizationId, parsed) {
5857
+ const emails = new Set(parsed.email ? [parsed.email] : []);
5858
+ if (parsed.clientId) {
5859
+ const [bookings, series] = await Promise.all([
5860
+ db.appointment.findMany({ where: { clientId: parsed.clientId, calendar: { organizationId } }, select: { clientEmail: true } }),
5861
+ db.recurringSeries.findMany({ where: { clientId: parsed.clientId, organizationId }, select: { clientEmail: true } })
5862
+ ]);
5863
+ for (const row of [...bookings, ...series]) emails.add(row.clientEmail.trim().toLowerCase());
5864
+ }
5865
+ return { emails: [...emails], clientId: parsed.clientId };
5866
+ }
5867
+
5868
+ // src/privacy/audit.ts
5869
+ async function recordPrivacyRequest(db, input) {
5870
+ await db.dataSubjectRequest.create({
5871
+ data: {
5872
+ organizationId: input.organizationId,
5873
+ kind: input.kind,
5874
+ subjectHashes: subjectHashes(input.organizationId, input.subject),
5875
+ requestedBy: input.requestedBy,
5876
+ counts: { ...input.counts },
5877
+ createdAt: input.now
5878
+ }
5879
+ });
5880
+ }
5881
+ async function listPrivacyRequests(db, input) {
5882
+ const where = { organizationId: input.organizationId };
5883
+ const [requests, total] = await Promise.all([
5884
+ db.dataSubjectRequest.findMany({
5885
+ where,
5886
+ orderBy: { createdAt: "desc" },
5887
+ take: Math.min(input.limit ?? 50, 200),
5888
+ skip: input.offset ?? 0,
5889
+ select: { id: true, kind: true, requestedBy: true, counts: true, createdAt: true }
5890
+ }),
5891
+ db.dataSubjectRequest.count({ where })
5892
+ ]);
5893
+ return { requests, total };
5894
+ }
5895
+
5896
+ // src/privacy/collect.ts
5897
+ var APPOINTMENT = {
5898
+ id: true,
5899
+ startTime: true,
5900
+ endTime: true,
5901
+ duration: true,
5902
+ timezone: true,
5903
+ status: true,
5904
+ isGroup: true,
5905
+ clientName: true,
5906
+ clientEmail: true,
5907
+ clientPhone: true,
5908
+ clientId: true,
5909
+ cancelledAt: true,
5910
+ cancelledBy: true,
5911
+ cancelReason: true,
5912
+ rescheduledFrom: true,
5913
+ rescheduleCount: true,
5914
+ intakeResponses: true,
5915
+ notes: true,
5916
+ staffNotes: true,
5917
+ location: true,
5918
+ meetingUrl: true,
5919
+ paymentStatus: true,
5920
+ paymentAmount: true,
5921
+ depositAmount: true,
5922
+ tipAmount: true,
5923
+ paymentProvider: true,
5924
+ paymentId: true,
5925
+ balancePaymentId: true,
5926
+ couponCode: true,
5927
+ discountAmount: true,
5928
+ cancellationFeeAmount: true,
5929
+ refundAmount: true,
5930
+ refundStatus: true,
5931
+ recurringId: true,
5932
+ recurringIndex: true,
5933
+ packagePurchaseId: true,
5934
+ createdAt: true,
5935
+ updatedAt: true,
5936
+ calendar: { select: { name: true } },
5937
+ type: { select: { name: true } }
5938
+ };
5939
+ var NOTIFICATION = {
5940
+ id: true,
5941
+ appointmentId: true,
5942
+ channel: true,
5943
+ trigger: true,
5944
+ recipient: true,
5945
+ subject: true,
5946
+ body: true,
5947
+ status: true,
5948
+ scheduledFor: true,
5949
+ sentAt: true,
5950
+ createdAt: true
5951
+ };
5952
+ var WAITLIST = {
5953
+ id: true,
5954
+ typeId: true,
5955
+ calendarId: true,
5956
+ day: true,
5957
+ slotStart: true,
5958
+ timezone: true,
5959
+ clientName: true,
5960
+ clientEmail: true,
5961
+ clientPhone: true,
5962
+ status: true,
5963
+ offerSlotStart: true,
5964
+ offerExpiresAt: true,
5965
+ offeredAt: true,
5966
+ bookedAppointmentId: true,
5967
+ createdAt: true
5968
+ };
5969
+ var PURCHASE = {
5970
+ id: true,
5971
+ packageId: true,
5972
+ clientEmail: true,
5973
+ clientName: true,
5974
+ sessionsTotal: true,
5975
+ sessionsUsed: true,
5976
+ expiresAt: true,
5977
+ purchasedAt: true,
5978
+ status: true,
5979
+ paymentId: true,
5980
+ notes: true,
5981
+ pricePaidCents: true,
5982
+ createdAt: true
5983
+ };
5984
+ var SERIES = {
5985
+ id: true,
5986
+ calendarId: true,
5987
+ typeId: true,
5988
+ frequency: true,
5989
+ occurrences: true,
5990
+ startTimeLocal: true,
5991
+ durationMins: true,
5992
+ timezone: true,
5993
+ endsAt: true,
5994
+ clientEmail: true,
5995
+ clientName: true,
5996
+ clientPhone: true,
5997
+ clientId: true,
5998
+ notes: true,
5999
+ status: true,
6000
+ createdAt: true
6001
+ };
6002
+ var DELIVERY = { id: true, eventId: true, eventType: true, body: true, status: true, createdAt: true };
6003
+ var emailIs = (field, emails) => emails.map((email2) => ({ [field]: { equals: email2, mode: "insensitive" } }));
6004
+ var escape = (text2) => text2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
6005
+ function mentions(body, emails, ids) {
6006
+ const lower = body.toLowerCase();
6007
+ const whole = emails.some((email2) => new RegExp(`(?<![a-z0-9._%+-])${escape(email2.toLowerCase())}(?![a-z0-9_-]|\\.[a-z0-9])`).test(lower));
6008
+ return whole || ids.some((id) => body.includes(`"${id}"`));
6009
+ }
6010
+ async function collectSubjectRows(db, organizationId, subject) {
6011
+ const person = (field) => [...emailIs(field, subject.emails), ...subject.clientId ? [{ clientId: subject.clientId }] : []];
6012
+ const byEmail = emailIs("clientEmail", subject.emails);
6013
+ const none = subject.emails.length === 0 && !subject.clientId;
6014
+ const appointments = none ? [] : await db.appointment.findMany({
6015
+ where: { calendar: { organizationId }, OR: person("clientEmail") },
6016
+ orderBy: { startTime: "asc" },
6017
+ select: APPOINTMENT
6018
+ });
6019
+ const appointmentIds = appointments.map((row) => row.id);
6020
+ const [notifications, waitlistEntries, packagePurchases, recurringSeries] = await Promise.all([
6021
+ appointmentIds.length ? db.scheduledNotification.findMany({ where: { appointmentId: { in: appointmentIds } }, orderBy: { createdAt: "asc" }, select: NOTIFICATION }) : [],
6022
+ byEmail.length ? db.waitlistEntry.findMany({ where: { organizationId, OR: byEmail }, orderBy: { createdAt: "asc" }, select: WAITLIST }) : [],
6023
+ byEmail.length ? db.packagePurchase.findMany({ where: { organizationId, OR: byEmail }, orderBy: { createdAt: "asc" }, select: PURCHASE }) : [],
6024
+ none ? [] : db.recurringSeries.findMany({ where: { organizationId, OR: person("clientEmail") }, orderBy: { createdAt: "asc" }, select: SERIES })
6025
+ ]);
6026
+ const terms = [...subject.emails, ...appointmentIds.map((id) => `"${id}"`), ...waitlistEntries.map((row) => `"${row.id}"`)];
6027
+ const deliveries = /* @__PURE__ */ new Map();
6028
+ for (let start = 0; start < terms.length; start += 40) {
6029
+ const chunk = terms.slice(start, start + 40);
6030
+ const rows = await db.webhookDelivery.findMany({
6031
+ where: { organizationId, OR: chunk.map((term) => ({ body: { contains: term, mode: "insensitive" } })) },
6032
+ orderBy: { createdAt: "asc" },
6033
+ select: DELIVERY
6034
+ });
6035
+ for (const row of rows) if (mentions(row.body, subject.emails, [...appointmentIds, ...waitlistEntries.map((entry4) => entry4.id)])) deliveries.set(row.id, row);
6036
+ }
6037
+ return { appointments, notifications, waitlistEntries, packagePurchases, recurringSeries, webhookDeliveries: [...deliveries.values()] };
6038
+ }
6039
+ function countRows(rows) {
6040
+ return {
6041
+ appointments: rows.appointments.length,
6042
+ notifications: rows.notifications.length,
6043
+ waitlistEntries: rows.waitlistEntries.length,
6044
+ packagePurchases: rows.packagePurchases.length,
6045
+ recurringSeries: rows.recurringSeries.length,
6046
+ webhookDeliveries: rows.webhookDeliveries.length
6047
+ };
6048
+ }
6049
+
6050
+ // src/privacy/export.ts
6051
+ function withoutOfferToken(body) {
6052
+ try {
6053
+ const parsed = JSON.parse(body);
6054
+ if (parsed?.data?.offer && "token" in parsed.data.offer) {
6055
+ delete parsed.data.offer.token;
6056
+ return JSON.stringify(parsed);
6057
+ }
6058
+ } catch {
6059
+ }
6060
+ return body;
6061
+ }
6062
+ function withoutLinks(body) {
6063
+ return body.replace(/\/appt\/[A-Za-z0-9_-]+/g, "/appt/[removed]").replace(/([?&]token=)[A-Za-z0-9_-]+/g, "$1[removed]");
6064
+ }
6065
+ async function exportSubject(db, input) {
6066
+ const parsed = parseSubject(input);
6067
+ const now = input.now ?? /* @__PURE__ */ new Date();
6068
+ const subject = await resolveSubject(db, input.organizationId, parsed);
6069
+ const rows = await collectSubjectRows(db, input.organizationId, subject);
6070
+ const counts = countRows(rows);
6071
+ await recordPrivacyRequest(db, { organizationId: input.organizationId, kind: "EXPORT", subject, requestedBy: input.requestedBy, counts, now });
6072
+ return {
6073
+ format: "ordinatio-scheduling-subject-export",
6074
+ version: 1,
6075
+ exportedAt: now.toISOString(),
6076
+ organizationId: input.organizationId,
6077
+ subject,
6078
+ counts,
6079
+ appointments: rows.appointments.map(({ calendar, type, ...rest }) => ({ ...rest, calendarName: calendar.name, typeName: type.name })),
6080
+ notifications: rows.notifications.map((row) => ({ ...row, body: withoutLinks(row.body) })),
6081
+ waitlistEntries: rows.waitlistEntries,
6082
+ packagePurchases: rows.packagePurchases,
6083
+ recurringSeries: rows.recurringSeries,
6084
+ webhookDeliveries: rows.webhookDeliveries.map((row) => ({ ...row, body: withoutOfferToken(row.body) }))
6085
+ };
6086
+ }
6087
+
6088
+ // src/privacy/erase.ts
6089
+ var import_node_crypto7 = require("crypto");
6090
+ var import_client9 = require("@prisma/client");
6091
+ var ERASED_NAME = "Erased client";
6092
+ var ERASED_EMAIL = "erased@erased.invalid";
6093
+ var LIVE_BOOKING = ["PENDING", "CONFIRMED"];
6094
+ var LIVE_OFFER = ["OFFERED", "ACCEPTING"];
6095
+ function blockersOf(rows, now) {
6096
+ return {
6097
+ upcomingAppointments: rows.appointments.filter((row) => LIVE_BOOKING.includes(row.status) && row.endTime > now).length,
6098
+ liveWaitlistEntries: rows.waitlistEntries.filter((row) => LIVE_OFFER.includes(row.status)).length
6099
+ };
6100
+ }
6101
+ function warningsOf(rows) {
6102
+ const unused = rows.packagePurchases.filter((row) => row.status === "ACTIVE").reduce((sum, row) => sum + Math.max(0, row.sessionsTotal - row.sessionsUsed), 0);
6103
+ return unused > 0 ? [`An active package still has ${unused} unused sessions; after erasure it can no longer be matched to this person`] : [];
6104
+ }
6105
+ var blocked = (blockers) => blockers.upcomingAppointments + blockers.liveWaitlistEntries > 0;
6106
+ async function previewErase(db, input) {
6107
+ const subject = await resolveSubject(db, input.organizationId, parseSubject(input));
6108
+ const rows = await collectSubjectRows(db, input.organizationId, subject);
6109
+ const blockers = blockersOf(rows, input.now ?? /* @__PURE__ */ new Date());
6110
+ return { counts: countRows(rows), blockers, canErase: !blocked(blockers), warnings: warningsOf(rows) };
6111
+ }
6112
+ async function eraseSubject(db, input) {
6113
+ const parsed = parseSubject(input);
6114
+ const now = input.now ?? /* @__PURE__ */ new Date();
6115
+ const { organizationId } = input;
6116
+ return withTransaction(db, async (tx) => {
6117
+ const subject = await resolveSubject(tx, organizationId, parsed);
6118
+ const rows = await collectSubjectRows(tx, organizationId, subject);
6119
+ const blockers = blockersOf(rows, now);
6120
+ if (blocked(blockers)) {
6121
+ throw new SchedulingValidationError("This person still has upcoming bookings or an open waitlist offer", "SCHED_1301", { blockers });
6122
+ }
6123
+ for (const { id } of rows.appointments) {
6124
+ await tx.appointment.update({
6125
+ where: { id },
6126
+ data: {
6127
+ clientName: ERASED_NAME,
6128
+ clientEmail: ERASED_EMAIL,
6129
+ clientPhone: null,
6130
+ clientId: null,
6131
+ intakeResponses: import_client9.Prisma.DbNull,
6132
+ notes: null,
6133
+ staffNotes: null,
6134
+ cancelReason: null,
6135
+ manageToken: `erased_${(0, import_node_crypto7.randomUUID)()}`
6136
+ }
6137
+ });
6138
+ }
6139
+ const idsOf = (list) => list.map((row) => row.id);
6140
+ if (rows.notifications.length) await tx.scheduledNotification.deleteMany({ where: { id: { in: idsOf(rows.notifications) } } });
6141
+ if (rows.waitlistEntries.length) await tx.waitlistEntry.deleteMany({ where: { organizationId, id: { in: idsOf(rows.waitlistEntries) } } });
6142
+ if (rows.webhookDeliveries.length) await tx.webhookDelivery.deleteMany({ where: { organizationId, id: { in: idsOf(rows.webhookDeliveries) } } });
6143
+ if (rows.packagePurchases.length) {
6144
+ await tx.packagePurchase.updateMany({
6145
+ where: { organizationId, id: { in: idsOf(rows.packagePurchases) } },
6146
+ data: { clientEmail: ERASED_EMAIL, clientName: null, notes: null }
6147
+ });
6148
+ }
6149
+ if (rows.recurringSeries.length) {
6150
+ await tx.recurringSeries.updateMany({
6151
+ where: { organizationId, id: { in: idsOf(rows.recurringSeries) } },
6152
+ data: { clientEmail: ERASED_EMAIL, clientName: ERASED_NAME, clientPhone: null, clientId: null, notes: null }
6153
+ });
6154
+ }
6155
+ const counts = countRows(rows);
6156
+ await recordPrivacyRequest(tx, { organizationId, kind: "ERASE", subject, requestedBy: input.requestedBy, counts, now });
6157
+ return { counts };
6158
+ }, { timeout: 12e4 });
6159
+ }
4524
6160
  // Annotate the CommonJS export names for ESM import in node:
4525
6161
  0 && (module.exports = {
6162
+ BRAND_FIELDS,
4526
6163
  BlockedTargetError,
4527
6164
  DEFAULT_BACKOFF_SECONDS,
6165
+ DEFAULT_OFFER_MINUTES,
6166
+ ERASED_EMAIL,
6167
+ ERASED_NAME,
4528
6168
  MAX_ENDPOINTS_PER_ORGANIZATION,
6169
+ MAX_WAITING_PER_TYPE_DAY,
6170
+ OPERATORS_BY_TYPE,
4529
6171
  RECURRING_MAX_OCCURRENCES,
6172
+ ROUTING_LIMITS,
4530
6173
  SCHEDULING_ERRORS,
4531
6174
  SIGNATURE_HEADER,
4532
6175
  SchedulingNotFoundError,
@@ -4539,7 +6182,9 @@ async function retryWebhookDelivery(db, organizationId, deliveryId, now = /* @__
4539
6182
  addTimeBlock,
4540
6183
  appointmentWebhookData,
4541
6184
  archiveCalendar,
6185
+ beginWaitlistAccept,
4542
6186
  bookAppointment,
6187
+ brandTemplateFields,
4543
6188
  buildJitsiUrl,
4544
6189
  buildNotificationContext,
4545
6190
  buildOccurrenceStartTime,
@@ -4547,25 +6192,33 @@ async function retryWebhookDelivery(db, organizationId, deliveryId, now = /* @__
4547
6192
  calculateCancellationFee,
4548
6193
  cancelAppointment,
4549
6194
  cancelPendingNotifications,
6195
+ checkAnswers,
4550
6196
  checkAuthContract,
4551
6197
  checkCalendarSyncContract,
4552
6198
  checkClockContract,
4553
6199
  checkNotificationContract,
4554
6200
  checkPaymentContract,
4555
6201
  checkWebhookUrl,
6202
+ completeWaitlistAccept,
4556
6203
  createAppointmentType,
4557
6204
  createCalendar,
4558
6205
  createInMemoryAdapters,
4559
6206
  createNodeTransport,
4560
6207
  createNotificationTemplate,
6208
+ createRoutingForm,
4561
6209
  createWebhookEndpoint,
6210
+ deleteBrand,
4562
6211
  deleteCalendar,
4563
6212
  deleteNotificationTemplate,
6213
+ deleteRoutingForm,
4564
6214
  deleteWebhookEndpoint,
4565
6215
  deliverDueWebhooks,
4566
6216
  enqueueAppointmentWebhook,
4567
6217
  enqueueReminderSent,
4568
6218
  enqueueWebhookEvent,
6219
+ eraseSubject,
6220
+ expireWaitlistOffers,
6221
+ exportSubject,
4569
6222
  generateOccurrenceDates,
4570
6223
  generateWebhookSecret,
4571
6224
  getAppointment,
@@ -4575,42 +6228,75 @@ async function retryWebhookDelivery(db, organizationId, deliveryId, now = /* @__
4575
6228
  getAvailableDates,
4576
6229
  getAvailableSlots,
4577
6230
  getBookingAnalytics,
6231
+ getBrand,
4578
6232
  getCalendar,
4579
6233
  getGroupCapacity,
4580
6234
  getGroupSessions,
4581
6235
  getNotificationTemplate,
6236
+ getPublicBrand,
6237
+ getPublicRoutingForm,
6238
+ getRoutingForm,
4582
6239
  getTeamAvailableSlots,
4583
6240
  getUserDayAppointments,
6241
+ getWaitlistOffer,
4584
6242
  isPrivateAddress,
4585
6243
  isSlotAvailable,
4586
6244
  isVirtualMeeting,
6245
+ joinWaitlist,
6246
+ leaveWaitlist,
4587
6247
  listAppointmentTypes,
4588
6248
  listAppointments,
4589
6249
  listAvailabilityRules,
4590
6250
  listCalendars,
4591
6251
  listNotificationTemplates,
6252
+ listPrivacyRequests,
6253
+ listRoutingForms,
6254
+ listWaitlist,
4592
6255
  listWebhookDeliveries,
4593
6256
  listWebhookEndpoints,
6257
+ localDay,
4594
6258
  localToUTC,
4595
6259
  markNoShow,
6260
+ matchingRules,
6261
+ offerFreedSlot,
6262
+ parseSubject,
4596
6263
  parseTimeLocal,
6264
+ previewErase,
4597
6265
  processPendingNotifications,
4598
6266
  queueImmediateNotification,
4599
6267
  queueStaffNotification,
6268
+ releaseWaitlistAccept,
4600
6269
  removeDateOverride,
6270
+ removeWaitlistEntry,
4601
6271
  renderTemplate,
4602
6272
  rescheduleAppointment,
6273
+ resolveDestination,
4603
6274
  resolveLocation,
6275
+ resolveSubject,
4604
6276
  retryWebhookDelivery,
6277
+ routeClient,
6278
+ saveBrand,
4605
6279
  schedError,
4606
6280
  scheduleNotifications,
6281
+ scopeToOrganization,
4607
6282
  selectCalendarForBooking,
4608
6283
  sendTestWebhook,
6284
+ senderIdentity,
4609
6285
  setWeeklyAvailability,
6286
+ settleBookedAccept,
4610
6287
  signWebhook,
6288
+ subjectHashes,
6289
+ testRoutingForm,
6290
+ toPublicBrand,
6291
+ tryOfferFreedSlot,
4611
6292
  updateAppointmentType,
4612
6293
  updateCalendar,
4613
6294
  updateNotificationTemplate,
6295
+ updateRoutingForm,
6296
+ validateBrand,
6297
+ validateRoutingDestinations,
6298
+ validateRoutingStructure,
4614
6299
  verifyWebhookSignature,
4615
- withCalendarVisibility
6300
+ withCalendarVisibility,
6301
+ withOrganization
4616
6302
  });