@ordinatio/scheduling-api 0.6.0 → 0.7.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
@@ -67,9 +67,12 @@ __export(index_exports, {
67
67
  RouteClientSchema: () => RouteClientSchema,
68
68
  SLOT_GRANULARITY_DEFAULT: () => SLOT_GRANULARITY_DEFAULT,
69
69
  SLOT_GRANULARITY_OPTIONS: () => SLOT_GRANULARITY_OPTIONS,
70
+ SmsSendError: () => SmsSendError,
70
71
  TERMINAL_SUCCESS_STATUSES: () => TERMINAL_SUCCESS_STATUSES,
71
72
  TOKEN_TTL_DAYS: () => TOKEN_TTL_DAYS,
73
+ TelnyxSendError: () => SmsSendError,
72
74
  TestRoutingFormSchema: () => TestRoutingFormSchema,
75
+ TextSettingsSchema: () => TextSettingsSchema,
73
76
  UnverifiedPaymentError: () => UnverifiedPaymentError,
74
77
  UpdateAppointmentCategorySchema: () => UpdateAppointmentCategorySchema,
75
78
  UpdateAppointmentTypeSchema: () => UpdateAppointmentTypeSchema,
@@ -85,6 +88,8 @@ __export(index_exports, {
85
88
  calendarVisibilityFilter: () => calendarVisibilityFilter,
86
89
  canSeeAppointmentInScope: () => canSeeAppointmentInScope,
87
90
  canSeeCalendarInScope: () => canSeeCalendarInScope,
91
+ checkSendingDomain: () => checkSendingDomain,
92
+ classifyReply: () => classifyReply,
88
93
  createBalanceIntent: () => createBalanceIntent,
89
94
  createBearerStaffResolver: () => createBearerStaffResolver,
90
95
  createMemoryAvailabilityCache: () => createMemoryAvailabilityCache,
@@ -93,26 +98,38 @@ __export(index_exports, {
93
98
  createNoBalancePaymentControl: () => createNoBalancePaymentControl,
94
99
  createNoPaymentAdapter: () => createNoPaymentAdapter,
95
100
  createNodeListener: () => createNodeListener,
101
+ createOutlookCalendarSync: () => createOutlookCalendarSync,
102
+ createPerBusinessSmsAdapter: () => createPerBusinessSmsAdapter,
96
103
  createSchedulingApi: () => createSchedulingApi,
97
104
  createScopedVisibility: () => createScopedVisibility,
105
+ createSendingDomainVerifier: () => createSendingDomainVerifier,
98
106
  createSingleOrganizationDirectory: () => createSingleOrganizationDirectory,
99
107
  createSingleOrganizationResolver: () => createSingleOrganizationResolver,
100
108
  createStaffContext: () => createStaffContext,
101
109
  createStripePaymentAdapter: () => createStripePaymentAdapter,
110
+ createTelnyxSmsAdapter: () => createTelnyxSmsAdapter,
111
+ createTextSettingsResolver: () => createTextSettingsResolver,
112
+ createTwilioSmsAdapter: () => createTwilioSmsAdapter,
102
113
  decimalToCents: () => decimalToCents,
103
114
  defaultCorsHeaders: () => defaultCorsHeaders,
104
115
  getErrorCode: () => getErrorCode,
105
116
  getErrorMessage: () => getErrorMessage,
106
117
  getErrorRef: () => getErrorRef,
118
+ handleTelnyxWebhook: () => handleTelnyxWebhook,
119
+ handleTwilioWebhook: () => handleTwilioWebhook,
107
120
  isCalendarVisibleInScope: () => isCalendarVisibleInScope,
108
121
  isSchedulingServiceError: () => isSchedulingServiceError,
109
122
  isSupportedCurrency: () => isSupportedCurrency,
110
123
  isTokenExpired: () => isTokenExpired,
124
+ normalizePhoneNumber: () => normalizePhoneNumber,
125
+ normalizeSendingDomain: () => normalizeSendingDomain,
111
126
  parsePagination: () => parsePagination,
112
127
  persistRefundOutcome: () => persistRefundOutcome,
113
128
  recordBalanceIntent: () => recordBalanceIntent,
114
129
  runCalendarRemoveWithoutBlocking: () => runCalendarRemoveWithoutBlocking,
115
130
  runCalendarSyncWithoutBlocking: () => runCalendarSyncWithoutBlocking,
131
+ verifyTelnyxSignature: () => verifyTelnyxSignature,
132
+ verifyTwilioSignature: () => verifyTwilioSignature,
116
133
  visibleCalendarIdsInScope: () => visibleCalendarIdsInScope
117
134
  });
118
135
  module.exports = __toCommonJS(index_exports);
@@ -1774,9 +1791,9 @@ function invalid(error) {
1774
1791
  details: error.issues.map((e) => ({ field: e.path.join("."), message: e.message }))
1775
1792
  }, { status: 400 });
1776
1793
  }
1777
- function failure(label, error, fallback) {
1794
+ function failure(label2, error, fallback) {
1778
1795
  const ref = getErrorRef(error);
1779
- console.error(`[${label}]`, ref, error instanceof Error ? error.message : error);
1796
+ console.error(`[${label2}]`, ref, error instanceof Error ? error.message : error);
1780
1797
  return Response.json({ error: getErrorMessage(error, fallback), ...ref && { ref } }, { status: 500 });
1781
1798
  }
1782
1799
  async function updateLocation(request, { host, params }) {
@@ -2532,16 +2549,16 @@ async function attemptLegRefund(payments, paymentIntentId, idempotencyKeySuffix,
2532
2549
  return failedLeg(errorCode, logLabel, appointmentId, paymentIntentId, idempotencyKey, retriedAfterReplay, { error: result.error, message: result.error ?? result.code ?? "no reason given", requestId: result.requestId });
2533
2550
  }
2534
2551
  }
2535
- function failedLeg(errorCode, logLabel, appointmentId, paymentIntentId, idempotencyKey, retriedAfterReplay, failure3) {
2536
- const diagnostic = (0, import_scheduling24.schedError)(errorCode, { error: failure3.error, appointmentId, paymentIntentId });
2552
+ function failedLeg(errorCode, logLabel, appointmentId, paymentIntentId, idempotencyKey, retriedAfterReplay, failure4) {
2553
+ const diagnostic = (0, import_scheduling24.schedError)(errorCode, { error: failure4.error, appointmentId, paymentIntentId });
2537
2554
  console.error(
2538
2555
  `[resolve-refund] ${logLabel} refund failed${retriedAfterReplay ? " (after a fresh-key re-attempt)" : ""} \u2014 manual refund may be required:`,
2539
2556
  diagnostic.ref,
2540
2557
  appointmentId,
2541
2558
  paymentIntentId,
2542
- `requestId=${failure3.requestId}`,
2559
+ `requestId=${failure4.requestId}`,
2543
2560
  `idempotencyKey=${idempotencyKey}`,
2544
- failure3.message
2561
+ failure4.message
2545
2562
  );
2546
2563
  return { succeeded: false, amountCents: null };
2547
2564
  }
@@ -3387,6 +3404,14 @@ var BrandSchema = import_zod14.z.object({
3387
3404
  fromEmail: optionalText(400)
3388
3405
  }).strict();
3389
3406
 
3407
+ // src/schemas/text-settings.schema.ts
3408
+ var import_zod15 = require("zod");
3409
+ var TextSettingsSchema = import_zod15.z.object({
3410
+ provider: import_zod15.z.string().max(40),
3411
+ fromNumber: import_zod15.z.string().max(40),
3412
+ enabled: import_zod15.z.boolean().optional()
3413
+ }).strict();
3414
+
3390
3415
  // src/pagination.ts
3391
3416
  var DEFAULT_LIMIT = 50;
3392
3417
  var MAX_LIMIT = 200;
@@ -3408,12 +3433,12 @@ function parsePagination(request, maxLimit = MAX_LIMIT, defaultLimit = DEFAULT_L
3408
3433
  }
3409
3434
 
3410
3435
  // src/validation.ts
3411
- var import_zod15 = require("zod");
3436
+ var import_zod16 = require("zod");
3412
3437
  async function parseBody(request, schema) {
3413
3438
  try {
3414
3439
  return { success: true, data: schema.parse(await request.json()) };
3415
3440
  } catch (error) {
3416
- if (error instanceof import_zod15.ZodError) {
3441
+ if (error instanceof import_zod16.ZodError) {
3417
3442
  const details = error.issues.map((issue) => ({ field: issue.path.join("."), message: issue.message }));
3418
3443
  return { success: false, response: Response.json({ error: "Validation failed", details }, { status: 400 }) };
3419
3444
  }
@@ -3427,7 +3452,7 @@ function validateData(data, schema) {
3427
3452
  try {
3428
3453
  return { success: true, data: schema.parse(data) };
3429
3454
  } catch (error) {
3430
- if (error instanceof import_zod15.ZodError) {
3455
+ if (error instanceof import_zod16.ZodError) {
3431
3456
  return { success: false, errors: error.issues.map((issue) => ({ field: issue.path.join("."), message: issue.message })) };
3432
3457
  }
3433
3458
  return { success: false, errors: [{ field: "", message: "Validation failed" }] };
@@ -3958,24 +3983,24 @@ var import_scheduling29 = require("@ordinatio/scheduling");
3958
3983
  // src/recurring/failure-collector.ts
3959
3984
  function createFailureCollector() {
3960
3985
  const problems = /* @__PURE__ */ new Map();
3961
- const record = (label, error) => {
3986
+ const record = (label2, error) => {
3962
3987
  const message = error instanceof Error ? error.message : String(error);
3963
- const key = `${label}\0${message}`;
3988
+ const key = `${label2}\0${message}`;
3964
3989
  const known = problems.get(key);
3965
3990
  if (known) known.count += 1;
3966
- else problems.set(key, { label, message, count: 1 });
3991
+ else problems.set(key, { label: label2, message, count: 1 });
3967
3992
  };
3968
- const attempt = async (label, work) => {
3993
+ const attempt = async (label2, work) => {
3969
3994
  try {
3970
3995
  await work();
3971
3996
  return true;
3972
3997
  } catch (error) {
3973
- record(label, error);
3998
+ record(label2, error);
3974
3999
  return false;
3975
4000
  }
3976
4001
  };
3977
4002
  const lines = () => [...problems.values()].map(
3978
- ({ label, message, count }) => count === 1 ? `${label} failed: ${message}` : `${label} failed for ${count} visits: ${message}`
4003
+ ({ label: label2, message, count }) => count === 1 ? `${label2} failed: ${message}` : `${label2} failed for ${count} visits: ${message}`
3979
4004
  );
3980
4005
  return { record, attempt, lines };
3981
4006
  }
@@ -4525,9 +4550,9 @@ async function businessName(host, db, organizationId) {
4525
4550
 
4526
4551
  // src/handlers/appointment-messages.ts
4527
4552
  var NOT_FOUND4 = () => Response.json({ error: "Appointment not found" }, { status: 404 });
4528
- function failure2(label, error, fallback) {
4553
+ function failure2(label2, error, fallback) {
4529
4554
  const ref = getErrorRef(error);
4530
- console.error(`[${label}]`, ref, error instanceof Error ? error.message : error);
4555
+ console.error(`[${label2}]`, ref, error instanceof Error ? error.message : error);
4531
4556
  return Response.json({ error: getErrorMessage(error, fallback), ...ref && { ref } }, { status: 500 });
4532
4557
  }
4533
4558
  async function sendFollowup(request, { host, params }) {
@@ -6210,7 +6235,7 @@ async function deliverWebhooks(request, { host }) {
6210
6235
 
6211
6236
  // src/handlers/waitlist-join.ts
6212
6237
  var import_scheduling53 = require("@ordinatio/scheduling");
6213
- var import_zod16 = require("zod");
6238
+ var import_zod17 = require("zod");
6214
6239
 
6215
6240
  // src/waitlist/waitlist-http.ts
6216
6241
  var import_scheduling52 = require("@ordinatio/scheduling");
@@ -6243,15 +6268,15 @@ async function requireWaitlistAdmin(host, request, options) {
6243
6268
  }
6244
6269
 
6245
6270
  // src/handlers/waitlist-join.ts
6246
- var JoinWaitlistSchema = import_zod16.z.object({
6247
- orgSlug: import_zod16.z.string().min(1).max(100).optional(),
6248
- typeId: import_zod16.z.string().min(1),
6249
- calendarId: import_zod16.z.string().min(1).optional(),
6250
- day: import_zod16.z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "Day must be YYYY-MM-DD"),
6251
- slotStart: import_zod16.z.string().datetime({ message: "Invalid date/time format" }).optional(),
6252
- clientName: import_zod16.z.string().trim().min(1, "Name is required").max(200),
6253
- clientEmail: import_zod16.z.string().email("Invalid email").max(254),
6254
- clientPhone: import_zod16.z.string().max(30).optional()
6271
+ var JoinWaitlistSchema = import_zod17.z.object({
6272
+ orgSlug: import_zod17.z.string().min(1).max(100).optional(),
6273
+ typeId: import_zod17.z.string().min(1),
6274
+ calendarId: import_zod17.z.string().min(1).optional(),
6275
+ day: import_zod17.z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "Day must be YYYY-MM-DD"),
6276
+ slotStart: import_zod17.z.string().datetime({ message: "Invalid date/time format" }).optional(),
6277
+ clientName: import_zod17.z.string().trim().min(1, "Name is required").max(200),
6278
+ clientEmail: import_zod17.z.string().email("Invalid email").max(254),
6279
+ clientPhone: import_zod17.z.string().max(30).optional()
6255
6280
  });
6256
6281
  async function joinWaitlistRoute(request, { host }) {
6257
6282
  const cors = host.cors(request);
@@ -6309,35 +6334,35 @@ async function leaveWaitlistRoute(request, { host }) {
6309
6334
 
6310
6335
  // src/handlers/waitlist-offer.ts
6311
6336
  var import_scheduling58 = require("@ordinatio/scheduling");
6312
- var import_zod18 = require("zod");
6337
+ var import_zod19 = require("zod");
6313
6338
 
6314
6339
  // src/handlers/appointments-book.ts
6315
6340
  var import_scheduling57 = require("@ordinatio/scheduling");
6316
6341
 
6317
6342
  // src/booking/booking-schema.ts
6318
- var import_zod17 = require("zod");
6319
- var BookingSchema = import_zod17.z.object({
6320
- calendarId: import_zod17.z.string().min(1).optional(),
6321
- preferredCalendarId: import_zod17.z.string().min(1).optional(),
6322
- typeId: import_zod17.z.string().min(1),
6323
- startTime: import_zod17.z.string().datetime({ message: "Invalid date/time format" }),
6324
- timezone: import_zod17.z.string().max(50).optional(),
6325
- clientName: import_zod17.z.string().trim().min(1, "Name is required").max(200),
6326
- clientEmail: import_zod17.z.string().email("Invalid email").max(254),
6327
- clientPhone: import_zod17.z.string().max(30).optional(),
6343
+ var import_zod18 = require("zod");
6344
+ var BookingSchema = import_zod18.z.object({
6345
+ calendarId: import_zod18.z.string().min(1).optional(),
6346
+ preferredCalendarId: import_zod18.z.string().min(1).optional(),
6347
+ typeId: import_zod18.z.string().min(1),
6348
+ startTime: import_zod18.z.string().datetime({ message: "Invalid date/time format" }),
6349
+ timezone: import_zod18.z.string().max(50).optional(),
6350
+ clientName: import_zod18.z.string().trim().min(1, "Name is required").max(200),
6351
+ clientEmail: import_zod18.z.string().email("Invalid email").max(254),
6352
+ clientPhone: import_zod18.z.string().max(30).optional(),
6328
6353
  // Untrusted: the host's client resolver decides whether to honor it.
6329
- clientId: import_zod17.z.string().optional(),
6330
- notes: import_zod17.z.string().max(1e3).optional(),
6354
+ clientId: import_zod18.z.string().optional(),
6355
+ notes: import_zod18.z.string().max(1e3).optional(),
6331
6356
  // Only the primitive types a form field produces; z.unknown() would accept anything.
6332
- intakeResponses: import_zod17.z.record(
6333
- import_zod17.z.string(),
6334
- import_zod17.z.union([import_zod17.z.string().max(1e3), import_zod17.z.number(), import_zod17.z.boolean(), import_zod17.z.null()])
6357
+ intakeResponses: import_zod18.z.record(
6358
+ import_zod18.z.string(),
6359
+ import_zod18.z.union([import_zod18.z.string().max(1e3), import_zod18.z.number(), import_zod18.z.boolean(), import_zod18.z.null()])
6335
6360
  ).optional(),
6336
- paymentId: import_zod17.z.string().optional(),
6337
- couponCode: import_zod17.z.string().min(1).max(50).transform((value) => value.trim().toUpperCase()).optional(),
6338
- packagePurchaseId: import_zod17.z.string().optional(),
6361
+ paymentId: import_zod18.z.string().optional(),
6362
+ couponCode: import_zod18.z.string().min(1).max(50).transform((value) => value.trim().toUpperCase()).optional(),
6363
+ packagePurchaseId: import_zod18.z.string().optional(),
6339
6364
  // Names the organization, so the calendar and type lookups can run against its own database.
6340
- orgSlug: import_zod17.z.string().min(1).max(100).optional()
6365
+ orgSlug: import_zod18.z.string().min(1).max(100).optional()
6341
6366
  });
6342
6367
 
6343
6368
  // src/booking/finalize-booking.ts
@@ -6827,7 +6852,7 @@ async function getWaitlistOfferRoute(request, { host }) {
6827
6852
  return waitlistErrorResponse(cors, error, "Failed to read the offer");
6828
6853
  }
6829
6854
  }
6830
- var AcceptSchema = import_zod18.z.object({ token: import_zod18.z.string().min(1).max(200), orgSlug: import_zod18.z.string().min(1).max(100).optional() });
6855
+ var AcceptSchema = import_zod19.z.object({ token: import_zod19.z.string().min(1).max(200), orgSlug: import_zod19.z.string().min(1).max(100).optional() });
6831
6856
  async function acceptWaitlistOfferRoute(request, context) {
6832
6857
  const { host } = context;
6833
6858
  const cors = host.cors(request);
@@ -7118,15 +7143,138 @@ async function deleteBrandRoute(request, { host }) {
7118
7143
  }
7119
7144
  }
7120
7145
 
7146
+ // src/handlers/admin-text-settings.ts
7147
+ var import_scheduling66 = require("@ordinatio/scheduling");
7148
+ var NOT_ENABLED4 = { error: "Text-message settings are not enabled on this server" };
7149
+ function failure3(error, fallback) {
7150
+ if (error instanceof import_scheduling66.SchedulingValidationError) {
7151
+ const details = error.context.errors;
7152
+ return Response.json({ error: error.message, code: error.code, ref: getErrorRef(error), ...details ? { details } : {} }, { status: 400 });
7153
+ }
7154
+ console.error("[text-settings]", error);
7155
+ return Response.json({ error: fallback }, { status: 500 });
7156
+ }
7157
+ async function requireTextAdmin(host, request, options) {
7158
+ const staff = await requireAdminStaff(host, request, options);
7159
+ if (staff instanceof Response) return staff;
7160
+ if (!host.textMessages) return Response.json(NOT_ENABLED4, { status: 501 });
7161
+ return staff;
7162
+ }
7163
+ async function getTextSettingsRoute(request, { host }) {
7164
+ try {
7165
+ const staff = await requireTextAdmin(host, request, { action: "admin-text-settings-get", tier: "GENERAL" });
7166
+ if (staff instanceof Response) return staff;
7167
+ return Response.json({ settings: await (0, import_scheduling66.getTextSettings)(staff.db, staff.organizationId), providers: host.textMessages?.providers ?? ["TELNYX", "TWILIO"] });
7168
+ } catch (error) {
7169
+ return failure3(error, "Failed to read the text-message settings");
7170
+ }
7171
+ }
7172
+ async function saveTextSettingsRoute(request, { host }) {
7173
+ try {
7174
+ const staff = await requireTextAdmin(host, request, { action: "admin-text-settings-save", tier: "UPDATE" });
7175
+ if (staff instanceof Response) return staff;
7176
+ const validation = await parseBody(request, TextSettingsSchema);
7177
+ if (!validation.success) return validation.response;
7178
+ const settings = await (0, import_scheduling66.saveTextSettings)(staff.db, staff.organizationId, validation.data, { providers: host.textMessages?.providers });
7179
+ await host.activity.log(staff.db, {
7180
+ action: "scheduling.text_settings_saved",
7181
+ description: "changed the text-message settings",
7182
+ metadata: { provider: settings.provider, enabled: settings.enabled }
7183
+ });
7184
+ return Response.json({ settings });
7185
+ } catch (error) {
7186
+ return failure3(error, "Failed to save the text-message settings");
7187
+ }
7188
+ }
7189
+ async function deleteTextSettingsRoute(request, { host }) {
7190
+ try {
7191
+ const staff = await requireTextAdmin(host, request, { action: "admin-text-settings-delete", tier: "DELETE" });
7192
+ if (staff instanceof Response) return staff;
7193
+ const removed = await (0, import_scheduling66.deleteTextSettings)(staff.db, staff.organizationId);
7194
+ if (removed) await host.activity.log(staff.db, { action: "scheduling.text_settings_removed", description: "removed the text-message settings", metadata: {} });
7195
+ return Response.json({ removed });
7196
+ } catch (error) {
7197
+ return failure3(error, "Failed to remove the text-message settings");
7198
+ }
7199
+ }
7200
+
7201
+ // src/sending-domain/check-sending-domain.ts
7202
+ function recordsFor(records, domain) {
7203
+ return typeof records === "function" ? records(domain) : records;
7204
+ }
7205
+ var DOMAIN_PATTERN = /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;
7206
+ var NOT_FOUND_CODES = /* @__PURE__ */ new Set(["ENODATA", "ENOTFOUND"]);
7207
+ function normalizeSendingDomain(raw) {
7208
+ const domain = raw.trim().toLowerCase().replace(/\.$/, "");
7209
+ return DOMAIN_PATTERN.test(domain) ? domain : null;
7210
+ }
7211
+ function recordHost(record, domain) {
7212
+ return record.name === "@" ? domain : `${record.name}.${domain}`;
7213
+ }
7214
+ var clean = (value) => value.trim().replace(/\.$/, "").toLowerCase();
7215
+ function matches(record, published) {
7216
+ if (record.type === "CNAME") return clean(published) === clean(record.value);
7217
+ const fold = (value) => record.purpose === "dkim" ? value.trim() : value.trim().toLowerCase();
7218
+ if (record.match !== "contains") return fold(published) === fold(record.value);
7219
+ const terms = fold(published).split(/\s+/);
7220
+ return fold(record.value).split(/\s+/).every((term) => terms.includes(term));
7221
+ }
7222
+ async function lookUp(resolver, record, host) {
7223
+ if (record.type === "CNAME") return await resolver.resolveCname(host);
7224
+ return (await resolver.resolveTxt(host)).map((chunks) => chunks.join(""));
7225
+ }
7226
+ var label = { spf: "SPF", dkim: "DKIM", dmarc: "DMARC", other: "This" };
7227
+ async function checkRecord(resolver, record, domain) {
7228
+ const host = recordHost(record, domain);
7229
+ const who = label[record.purpose];
7230
+ try {
7231
+ const published = await lookUp(resolver, record, host);
7232
+ if (published.some((value) => matches(record, value))) {
7233
+ return { record, host, status: "found", message: `${who} record is in place.` };
7234
+ }
7235
+ const hint = published.length === 0 ? "is empty" : "does not match";
7236
+ return { record, host, status: "wrong", message: `${who} record at ${host} ${hint}. Replace it with the value shown.` };
7237
+ } catch (error) {
7238
+ const code = error?.code;
7239
+ if (code && NOT_FOUND_CODES.has(code)) {
7240
+ return { record, host, status: "missing", message: `${who} record not found at ${host}. Add it at your domain host. New records can take up to a day to appear.` };
7241
+ }
7242
+ return { record, host, status: "unknown", message: `${who} record could not be checked just now. Try again in a few minutes.` };
7243
+ }
7244
+ }
7245
+ async function checkSendingDomain(config, rawDomain) {
7246
+ const domain = normalizeSendingDomain(rawDomain);
7247
+ if (!domain) return { domain: rawDomain, verified: false, records: [] };
7248
+ const records = await Promise.all(recordsFor(config.records, domain).map((record) => checkRecord(config.resolver, record, domain)));
7249
+ const required = records.filter((check) => check.record.required !== false);
7250
+ const verified = required.length > 0 && required.every((check) => check.status === "found");
7251
+ return { domain, verified, records };
7252
+ }
7253
+
7254
+ // src/handlers/admin-brand-domain-check.ts
7255
+ async function checkSendingDomainRoute(request, { host }) {
7256
+ try {
7257
+ const staff = await requireBrandAdmin(host, request, { action: "admin-brand-domain-check", tier: "SETTINGS" });
7258
+ if (staff instanceof Response) return staff;
7259
+ const check = host.brand?.checkSendingDomain;
7260
+ if (!check) return Response.json({ error: "Sending-domain checking is not set up on this server" }, { status: 501 });
7261
+ const domain = normalizeSendingDomain(new URL(request.url).searchParams.get("domain") ?? "");
7262
+ if (!domain) return Response.json({ error: "Enter a domain such as mail.acme.com" }, { status: 400 });
7263
+ return Response.json({ check: await check.call(host.brand, domain, staff.organizationId) });
7264
+ } catch (error) {
7265
+ return brandErrorResponse(error, "Failed to check the sending domain");
7266
+ }
7267
+ }
7268
+
7121
7269
  // src/handlers/admin-privacy.ts
7122
- var import_scheduling67 = require("@ordinatio/scheduling");
7270
+ var import_scheduling68 = require("@ordinatio/scheduling");
7123
7271
 
7124
7272
  // src/privacy/privacy-http.ts
7125
- var import_scheduling66 = require("@ordinatio/scheduling");
7126
- var NOT_ENABLED4 = { error: "Data export and erasure are not enabled on this server" };
7273
+ var import_scheduling67 = require("@ordinatio/scheduling");
7274
+ var NOT_ENABLED5 = { error: "Data export and erasure are not enabled on this server" };
7127
7275
  var STATUS_BY_CODE3 = { SCHED_1300: 400, SCHED_1301: 409 };
7128
7276
  function privacyErrorResponse(error, fallback) {
7129
- if (error instanceof import_scheduling66.SchedulingValidationError) {
7277
+ if (error instanceof import_scheduling67.SchedulingValidationError) {
7130
7278
  return Response.json(
7131
7279
  { error: error.message, code: error.code, ref: getErrorRef(error), details: error.context },
7132
7280
  { status: STATUS_BY_CODE3[error.code] ?? 400 }
@@ -7138,7 +7286,7 @@ function privacyErrorResponse(error, fallback) {
7138
7286
  async function requirePrivacyAdmin(host, request, options) {
7139
7287
  const staff = await requireAdminStaff(host, request, options);
7140
7288
  if (staff instanceof Response) return staff;
7141
- if (!host.privacy) return Response.json(NOT_ENABLED4, { status: 501 });
7289
+ if (!host.privacy) return Response.json(NOT_ENABLED5, { status: 501 });
7142
7290
  return staff;
7143
7291
  }
7144
7292
 
@@ -7156,7 +7304,7 @@ async function exportPrivacyRoute(request, { host }) {
7156
7304
  if (staff instanceof Response) return staff;
7157
7305
  const validation = await parseBody(request, PrivacySubjectSchema);
7158
7306
  if (!validation.success) return validation.response;
7159
- const result = await (0, import_scheduling67.exportSubject)(staff.db, { organizationId: staff.organizationId, requestedBy: staff.userId, ...validation.data });
7307
+ const result = await (0, import_scheduling68.exportSubject)(staff.db, { organizationId: staff.organizationId, requestedBy: staff.userId, ...validation.data });
7160
7308
  await logQuietly(host, staff.db, {
7161
7309
  action: "scheduling.privacy_export",
7162
7310
  description: "exported the data held about one person",
@@ -7183,10 +7331,10 @@ async function erasePrivacyRoute(request, { host }) {
7183
7331
  if (!validation.success) return validation.response;
7184
7332
  const { confirm, ...subject2 } = validation.data;
7185
7333
  if (confirm !== true) {
7186
- const preview = await (0, import_scheduling67.previewErase)(staff.db, { organizationId: staff.organizationId, ...subject2 });
7334
+ const preview = await (0, import_scheduling68.previewErase)(staff.db, { organizationId: staff.organizationId, ...subject2 });
7187
7335
  return Response.json({ erased: false, preview }, { headers: { "cache-control": "no-store" } });
7188
7336
  }
7189
- const { counts } = await (0, import_scheduling67.eraseSubject)(staff.db, { organizationId: staff.organizationId, requestedBy: staff.userId, ...subject2 });
7337
+ const { counts } = await (0, import_scheduling68.eraseSubject)(staff.db, { organizationId: staff.organizationId, requestedBy: staff.userId, ...subject2 });
7190
7338
  await logQuietly(host, staff.db, {
7191
7339
  action: "scheduling.privacy_erase",
7192
7340
  description: "erased the data held about one person",
@@ -7202,7 +7350,7 @@ async function listPrivacyRequestsRoute(request, { host }) {
7202
7350
  const staff = await requirePrivacyAdmin(host, request, { action: "admin-privacy-requests", tier: "GENERAL" });
7203
7351
  if (staff instanceof Response) return staff;
7204
7352
  const { limit, offset } = parsePagination(request);
7205
- const { requests, total } = await (0, import_scheduling67.listPrivacyRequests)(staff.db, { organizationId: staff.organizationId, limit, offset });
7353
+ const { requests, total } = await (0, import_scheduling68.listPrivacyRequests)(staff.db, { organizationId: staff.organizationId, limit, offset });
7206
7354
  return Response.json({ requests, total, hasMore: offset + requests.length < total });
7207
7355
  } catch (error) {
7208
7356
  return privacyErrorResponse(error, "Failed to list the requests");
@@ -7210,12 +7358,12 @@ async function listPrivacyRequestsRoute(request, { host }) {
7210
7358
  }
7211
7359
 
7212
7360
  // src/handlers/admin-routing-form-detail.ts
7213
- var import_scheduling68 = require("@ordinatio/scheduling");
7361
+ var import_scheduling69 = require("@ordinatio/scheduling");
7214
7362
  async function getRoutingFormAdminRoute(request, { host, params }) {
7215
7363
  try {
7216
7364
  const staff = await requireRoutingAdmin(host, request, { action: "admin-routing-forms-get", tier: "GENERAL" });
7217
7365
  if (staff instanceof Response) return staff;
7218
- return Response.json({ form: await (0, import_scheduling68.getRoutingForm)(staff.db, staff.organizationId, params.id) });
7366
+ return Response.json({ form: await (0, import_scheduling69.getRoutingForm)(staff.db, staff.organizationId, params.id) });
7219
7367
  } catch (error) {
7220
7368
  return routingErrorResponse(error, "Failed to read the form");
7221
7369
  }
@@ -7226,7 +7374,7 @@ async function updateRoutingFormRoute(request, { host, params }) {
7226
7374
  if (staff instanceof Response) return staff;
7227
7375
  const validation = await parseBody(request, UpdateRoutingFormSchema);
7228
7376
  if (!validation.success) return validation.response;
7229
- const form = await (0, import_scheduling68.updateRoutingForm)(staff.db, staff.organizationId, params.id, validation.data);
7377
+ const form = await (0, import_scheduling69.updateRoutingForm)(staff.db, staff.organizationId, params.id, validation.data);
7230
7378
  await host.activity.log(staff.db, {
7231
7379
  action: "scheduling.routing_form_updated",
7232
7380
  description: `changed routing form "${form.name}"`,
@@ -7241,7 +7389,7 @@ async function deleteRoutingFormRoute(request, { host, params }) {
7241
7389
  try {
7242
7390
  const staff = await requireRoutingAdmin(host, request, { action: "admin-routing-forms-delete", tier: "DELETE" });
7243
7391
  if (staff instanceof Response) return staff;
7244
- await (0, import_scheduling68.deleteRoutingForm)(staff.db, staff.organizationId, params.id);
7392
+ await (0, import_scheduling69.deleteRoutingForm)(staff.db, staff.organizationId, params.id);
7245
7393
  await host.activity.log(staff.db, { action: "scheduling.routing_form_deleted", description: "removed a routing form", metadata: { formId: params.id } });
7246
7394
  return Response.json({ success: true });
7247
7395
  } catch (error) {
@@ -7254,14 +7402,14 @@ async function testRoutingFormRoute(request, { host, params }) {
7254
7402
  if (staff instanceof Response) return staff;
7255
7403
  const validation = await parseBody(request, TestRoutingFormSchema);
7256
7404
  if (!validation.success) return validation.response;
7257
- return Response.json(await (0, import_scheduling68.testRoutingForm)(staff.db, { organizationId: staff.organizationId, id: params.id, answers: validation.data.answers }));
7405
+ return Response.json(await (0, import_scheduling69.testRoutingForm)(staff.db, { organizationId: staff.organizationId, id: params.id, answers: validation.data.answers }));
7258
7406
  } catch (error) {
7259
7407
  return routingErrorResponse(error, "Failed to test the form");
7260
7408
  }
7261
7409
  }
7262
7410
 
7263
7411
  // src/handlers/appointments-list.ts
7264
- var import_scheduling69 = require("@ordinatio/scheduling");
7412
+ var import_scheduling70 = require("@ordinatio/scheduling");
7265
7413
  var DEFAULT_LIMIT2 = 50;
7266
7414
  var MAX_LIMIT2 = 500;
7267
7415
  async function listAppointments(request, { host }) {
@@ -7273,7 +7421,7 @@ async function listAppointments(request, { host }) {
7273
7421
  const clientId = params.get("clientId") || void 0;
7274
7422
  const status = params.get("status") || void 0;
7275
7423
  if (!clientId && !staff.isAdmin) {
7276
- const err = (0, import_scheduling69.schedError)("SCHED_900", { role: staff.role });
7424
+ const err = (0, import_scheduling70.schedError)("SCHED_900", { role: staff.role });
7277
7425
  return Response.json({ error: "Forbidden", ref: err.ref }, { status: 403 });
7278
7426
  }
7279
7427
  const startDate = params.get("startDate");
@@ -7284,7 +7432,7 @@ async function listAppointments(request, { host }) {
7284
7432
  MAX_LIMIT2
7285
7433
  );
7286
7434
  const visibility = await staff.visibleCalendars();
7287
- const where = (0, import_scheduling69.withOrganization)({
7435
+ const where = (0, import_scheduling70.withOrganization)({
7288
7436
  ...visibility ? { calendar: visibility } : {},
7289
7437
  ...calendarId ? { calendarId } : {},
7290
7438
  ...clientId ? { clientId } : {},
@@ -7353,7 +7501,7 @@ async function listAppointments(request, { host }) {
7353
7501
  }
7354
7502
 
7355
7503
  // src/handlers/availability.ts
7356
- var import_scheduling70 = require("@ordinatio/scheduling");
7504
+ var import_scheduling71 = require("@ordinatio/scheduling");
7357
7505
 
7358
7506
  // src/availability/picked-day.ts
7359
7507
  var CALENDAR_DAY_SHAPE = /^\d{4}-\d{2}-\d{2}$/;
@@ -7466,7 +7614,7 @@ async function getAvailability(request, { host }) {
7466
7614
  const cached = await readCache(host.availabilityCache, calendarId, cacheDay, typeDuration);
7467
7615
  if (cached != null) return corsJson(cors, cached);
7468
7616
  }
7469
- const result = await (0, import_scheduling70.getAvailableSlots)(db, {
7617
+ const result = await (0, import_scheduling71.getAvailableSlots)(db, {
7470
7618
  calendarId,
7471
7619
  date: dateObj,
7472
7620
  localDate: pickedDay,
@@ -7487,7 +7635,7 @@ async function getAvailability(request, { host }) {
7487
7635
  }
7488
7636
 
7489
7637
  // src/handlers/availability-team.ts
7490
- var import_scheduling71 = require("@ordinatio/scheduling");
7638
+ var import_scheduling72 = require("@ordinatio/scheduling");
7491
7639
 
7492
7640
  // src/loaders/team-type.ts
7493
7641
  async function loadTeamType(db, typeId, organizationId) {
@@ -7535,7 +7683,7 @@ async function getTeamAvailability(request, { host }) {
7535
7683
  { status: 400 }
7536
7684
  );
7537
7685
  }
7538
- const result = await (0, import_scheduling71.getTeamAvailableSlots)(db, {
7686
+ const result = await (0, import_scheduling72.getTeamAvailableSlots)(db, {
7539
7687
  typeId,
7540
7688
  date: dateObj,
7541
7689
  localDate: pickedCalendarDay(date),
@@ -7558,7 +7706,7 @@ async function getTeamAvailability(request, { host }) {
7558
7706
  }
7559
7707
 
7560
7708
  // src/handlers/appointment-types.ts
7561
- var import_scheduling72 = require("@ordinatio/scheduling");
7709
+ var import_scheduling73 = require("@ordinatio/scheduling");
7562
7710
 
7563
7711
  // src/loaders/types-by-calendar.ts
7564
7712
  function loadTypesByCalendarSlug(cache, db, organizationId, calendarSlug) {
@@ -7632,19 +7780,19 @@ async function getAppointmentTypes(request, { host }) {
7632
7780
  }));
7633
7781
  return corsJson(cors, response, { headers: WIDGET_CACHE_HEADERS });
7634
7782
  } catch (error) {
7635
- const diagnostic = (0, import_scheduling72.schedError)("SCHED_202", { error });
7783
+ const diagnostic = (0, import_scheduling73.schedError)("SCHED_202", { error });
7636
7784
  console.error("[appointment-types]", diagnostic.ref, error);
7637
7785
  return corsJson(cors, { error: "Failed to fetch appointment types", ref: diagnostic.ref }, { status: 500 });
7638
7786
  }
7639
7787
  }
7640
7788
 
7641
7789
  // src/handlers/coupons-validate.ts
7642
- var import_zod19 = require("zod");
7643
- var import_scheduling73 = require("@ordinatio/scheduling");
7644
- var Schema4 = import_zod19.z.object({
7645
- code: import_zod19.z.string().min(1).max(50).transform((v) => v.trim().toUpperCase()),
7646
- calendarId: import_zod19.z.string().min(1),
7647
- price: import_zod19.z.number().positive()
7790
+ var import_zod20 = require("zod");
7791
+ var import_scheduling74 = require("@ordinatio/scheduling");
7792
+ var Schema4 = import_zod20.z.object({
7793
+ code: import_zod20.z.string().min(1).max(50).transform((v) => v.trim().toUpperCase()),
7794
+ calendarId: import_zod20.z.string().min(1),
7795
+ price: import_zod20.z.number().positive()
7648
7796
  });
7649
7797
  function calculateDiscount(price, discountType, discountValue) {
7650
7798
  if (discountType === "PERCENTAGE") {
@@ -7702,7 +7850,7 @@ async function validateCoupon(request, { host }) {
7702
7850
  { headers: host.cors(request) }
7703
7851
  );
7704
7852
  } catch (error) {
7705
- const err = (0, import_scheduling73.schedError)("SCHED_408", {
7853
+ const err = (0, import_scheduling74.schedError)("SCHED_408", {
7706
7854
  calendarId,
7707
7855
  error: error instanceof Error ? error.message : String(error)
7708
7856
  });
@@ -7782,7 +7930,7 @@ async function listActiveCalendars(request, { host }) {
7782
7930
  }
7783
7931
 
7784
7932
  // src/handlers/type.ts
7785
- var import_scheduling74 = require("@ordinatio/scheduling");
7933
+ var import_scheduling75 = require("@ordinatio/scheduling");
7786
7934
 
7787
7935
  // src/loaders/type-by-slug.ts
7788
7936
  function loadTypeBySlug(cache, db, organizationId, slug) {
@@ -7887,14 +8035,14 @@ async function getType(request, { host }) {
7887
8035
  { headers: WIDGET_CACHE_HEADERS }
7888
8036
  );
7889
8037
  } catch (error) {
7890
- const diagnostic = (0, import_scheduling74.schedError)("SCHED_207", { error });
8038
+ const diagnostic = (0, import_scheduling75.schedError)("SCHED_207", { error });
7891
8039
  console.error("[type]", diagnostic.ref, error);
7892
8040
  return corsJson(cors, { error: "Failed to fetch appointment type", ref: diagnostic.ref }, { status: 500 });
7893
8041
  }
7894
8042
  }
7895
8043
 
7896
8044
  // src/handlers/widget-init.ts
7897
- var import_scheduling75 = require("@ordinatio/scheduling");
8045
+ var import_scheduling76 = require("@ordinatio/scheduling");
7898
8046
 
7899
8047
  // src/loaders/widget-data.ts
7900
8048
  function loadWidgetData(cache, db, organizationId, calendarSlug) {
@@ -7983,7 +8131,7 @@ async function getWidgetInit(request, { host }) {
7983
8131
  }));
7984
8132
  return corsJson(cors, { calendar, types: sanitizedTypes }, { headers: WIDGET_CACHE_HEADERS });
7985
8133
  } catch (error) {
7986
- const diagnostic = (0, import_scheduling75.schedError)("SCHED_206", { error });
8134
+ const diagnostic = (0, import_scheduling76.schedError)("SCHED_206", { error });
7987
8135
  console.error("[widget-init]", diagnostic.ref, error);
7988
8136
  return corsJson(cors, { error: "Failed to load widget data", ref: diagnostic.ref }, { status: 500 });
7989
8137
  }
@@ -8058,6 +8206,10 @@ var ROUTES = [
8058
8206
  { method: "GET", path: "/admin/brand", public: false, handler: getBrandAdminRoute },
8059
8207
  { method: "PUT", path: "/admin/brand", public: false, handler: saveBrandRoute },
8060
8208
  { method: "DELETE", path: "/admin/brand", public: false, handler: deleteBrandRoute },
8209
+ { method: "GET", path: "/admin/text-settings", public: false, handler: getTextSettingsRoute },
8210
+ { method: "PUT", path: "/admin/text-settings", public: false, handler: saveTextSettingsRoute },
8211
+ { method: "DELETE", path: "/admin/text-settings", public: false, handler: deleteTextSettingsRoute },
8212
+ { method: "GET", path: "/admin/brand/sending-domain", public: false, handler: checkSendingDomainRoute },
8061
8213
  { method: "POST", path: "/admin/privacy/export", public: false, handler: exportPrivacyRoute },
8062
8214
  { method: "POST", path: "/admin/privacy/erase", public: false, handler: erasePrivacyRoute },
8063
8215
  { method: "GET", path: "/admin/privacy/requests", public: false, handler: listPrivacyRequestsRoute },
@@ -8152,6 +8304,7 @@ function createSchedulingApi(config) {
8152
8304
  routingForms: config.host.routingForms ?? null,
8153
8305
  privacy: config.host.privacy ?? null,
8154
8306
  brand: config.host.brand ?? null,
8307
+ textMessages: config.host.textMessages ?? null,
8155
8308
  icalUidDomain: config.host.icalUidDomain?.bind(config.host) ?? (() => null),
8156
8309
  calendarSync: config.host.calendarSync ?? { upsertEvent: async () => ({}), removeEvent: async () => void 0 },
8157
8310
  activity: config.host.activity ?? { log: async () => void 0, isOpen: async () => false, resolve: async () => void 0 },
@@ -8183,16 +8336,16 @@ function createSchedulingApi(config) {
8183
8336
  const { pathname } = new URL(request.url);
8184
8337
  if (pathname !== basePath && !pathname.startsWith(`${basePath}/`)) return notFound();
8185
8338
  const relative = pathname.slice(basePath.length) || "/";
8186
- const matches = routes.map((route) => ({ route, params: matchPath(route.path, relative) })).filter((match) => match.params !== null);
8187
- if (matches.length === 0) return notFound();
8339
+ const matches2 = routes.map((route) => ({ route, params: matchPath(route.path, relative) })).filter((match) => match.params !== null);
8340
+ if (matches2.length === 0) return notFound();
8188
8341
  const method = request.method.toUpperCase();
8189
- if (method === "OPTIONS" && matches.some((match) => match.route.public)) {
8342
+ if (method === "OPTIONS" && matches2.some((match) => match.route.public)) {
8190
8343
  return new Response(null, { status: 204, headers: host.cors(request) });
8191
8344
  }
8192
- const hit = matches.find((match) => match.route.method === method);
8345
+ const hit = matches2.find((match) => match.route.method === method);
8193
8346
  if (!hit) {
8194
- const allowed = [...new Set(matches.map((match) => match.route.method))];
8195
- if (matches.some((match) => match.route.public)) allowed.push("OPTIONS");
8347
+ const allowed = [...new Set(matches2.map((match) => match.route.method))];
8348
+ if (matches2.some((match) => match.route.public)) allowed.push("OPTIONS");
8196
8349
  return Response.json({ error: "Method not allowed" }, { status: 405, headers: { Allow: allowed.join(", ") } });
8197
8350
  }
8198
8351
  try {
@@ -8357,6 +8510,612 @@ function assertStripeTestKey(raw) {
8357
8510
  return key;
8358
8511
  }
8359
8512
 
8513
+ // src/sending-domain/create-sending-domain-verifier.ts
8514
+ function createSendingDomainVerifier(config) {
8515
+ const check = (domain) => checkSendingDomain(config, domain);
8516
+ return {
8517
+ isSendingDomainVerified: async (domain) => (await check(domain)).verified,
8518
+ check,
8519
+ instructions: (rawDomain) => {
8520
+ const domain = normalizeSendingDomain(rawDomain);
8521
+ return domain ? recordsFor(config.records, domain).map((record) => ({ record, host: recordHost(record, domain) })) : [];
8522
+ }
8523
+ };
8524
+ }
8525
+
8526
+ // src/sms/sms-common.ts
8527
+ var SmsSendError = class extends Error {
8528
+ constructor(message, retryable, outcomeUnknown, status, code) {
8529
+ super(message);
8530
+ this.retryable = retryable;
8531
+ this.outcomeUnknown = outcomeUnknown;
8532
+ this.status = status;
8533
+ this.code = code;
8534
+ this.name = "SmsSendError";
8535
+ }
8536
+ };
8537
+ function normalizePhoneNumber(raw) {
8538
+ const digits = raw.trim().replace(/[\s().-]/g, "");
8539
+ if (/^\+[1-9]\d{7,14}$/.test(digits)) return digits;
8540
+ if (/^\d{10}$/.test(digits)) return `+1${digits}`;
8541
+ if (/^1\d{10}$/.test(digits)) return `+${digits}`;
8542
+ return null;
8543
+ }
8544
+ function readHeader(headers, name) {
8545
+ if (typeof headers.get === "function") return headers.get(name) ?? void 0;
8546
+ const found = Object.entries(headers).find(([key]) => key.toLowerCase() === name);
8547
+ const value = found?.[1];
8548
+ return Array.isArray(value) ? value[0] : value;
8549
+ }
8550
+ var STOP_WORDS = ["STOP", "STOPALL", "UNSUBSCRIBE", "END", "QUIT"];
8551
+ var START_WORDS = ["START", "UNSTOP"];
8552
+ function classifyReply(text) {
8553
+ const word = text.trim().toUpperCase().replace(/[.!?,]+$/, "");
8554
+ return STOP_WORDS.includes(word) ? "opt-out" : START_WORDS.includes(word) ? "opt-in" : "reply";
8555
+ }
8556
+
8557
+ // src/telnyx/telnyx-sms.ts
8558
+ var TELNYX_MESSAGES_URL = "https://api.telnyx.com/v2/messages";
8559
+ var DEFAULT_TIMEOUT_MS = 1e4;
8560
+ var OPTED_OUT_CODE = "40300";
8561
+ function firstError(body) {
8562
+ const error = body?.errors?.[0];
8563
+ if (!error) return { text: "no detail given" };
8564
+ return { code: error.code === void 0 ? void 0 : String(error.code), text: error.detail ?? error.title ?? "no detail given" };
8565
+ }
8566
+ function createTelnyxSmsAdapter(config) {
8567
+ const apiKey = typeof config.apiKey === "string" ? config.apiKey.trim() : "";
8568
+ if (!apiKey) throw new Error("createTelnyxSmsAdapter needs an apiKey");
8569
+ const profileId = config.messagingProfileId?.trim() || void 0;
8570
+ const from = config.from ? normalizePhoneNumber(config.from) : null;
8571
+ if (config.from && !from) throw new Error('createTelnyxSmsAdapter: "from" must be a phone number such as +13135550100');
8572
+ if (!from && !profileId) throw new Error('createTelnyxSmsAdapter needs a sending number ("from"), a messagingProfileId, or both');
8573
+ const doFetch = config.fetch ?? fetch;
8574
+ const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
8575
+ return {
8576
+ async send(message) {
8577
+ if (message.channel !== "SMS") return { status: "SKIPPED", reason: "The Telnyx adapter only sends text messages" };
8578
+ const to = normalizePhoneNumber(message.to);
8579
+ if (!to) return { status: "SKIPPED", reason: "The recipient is not a valid phone number" };
8580
+ if (!message.body.trim()) return { status: "SKIPPED", reason: "The message is empty" };
8581
+ const controller = new AbortController();
8582
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
8583
+ let response;
8584
+ let body;
8585
+ try {
8586
+ response = await doFetch(TELNYX_MESSAGES_URL, {
8587
+ method: "POST",
8588
+ headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
8589
+ body: JSON.stringify({
8590
+ to,
8591
+ text: message.body,
8592
+ type: "SMS",
8593
+ ...from ? { from } : {},
8594
+ ...profileId ? { messaging_profile_id: profileId } : {}
8595
+ }),
8596
+ signal: controller.signal
8597
+ });
8598
+ body = await response.json().catch((error) => {
8599
+ if (controller.signal.aborted) throw error;
8600
+ return null;
8601
+ });
8602
+ } catch (error) {
8603
+ const reason = controller.signal.aborted ? `timed out after ${timeoutMs} ms` : error instanceof Error ? error.message : String(error);
8604
+ throw new SmsSendError(`Telnyx could not be reached (${reason}); the message may or may not have been sent`, true, true);
8605
+ } finally {
8606
+ clearTimeout(timer);
8607
+ }
8608
+ if (response.ok) {
8609
+ const id = body?.data?.id;
8610
+ return id ? { status: "SENT", id } : { status: "SENT" };
8611
+ }
8612
+ const { code, text } = firstError(body);
8613
+ if (code === OPTED_OUT_CODE) return { status: "SKIPPED", reason: "The recipient opted out of text messages" };
8614
+ const serverFault = response.status >= 500;
8615
+ const retryable = response.status === 429 || serverFault;
8616
+ throw new SmsSendError(
8617
+ `Telnyx refused the message (HTTP ${response.status}${code ? `, code ${code}` : ""}): ${text}`,
8618
+ retryable,
8619
+ serverFault,
8620
+ response.status,
8621
+ code
8622
+ );
8623
+ }
8624
+ };
8625
+ }
8626
+
8627
+ // src/telnyx/telnyx-inbound.ts
8628
+ var import_node_crypto3 = require("crypto");
8629
+ var ED25519_SPKI_PREFIX = Buffer.from("302a300506032b6570032100", "hex");
8630
+ var DEFAULT_TOLERANCE_SECONDS = 300;
8631
+ function verifyTelnyxSignature(rawBody, headers, options) {
8632
+ const signature = readHeader(headers, "telnyx-signature-ed25519");
8633
+ const timestamp = readHeader(headers, "telnyx-timestamp");
8634
+ if (!signature || !timestamp || !/^\d+$/.test(timestamp)) return false;
8635
+ const nowSeconds = Math.floor((options.now?.() ?? /* @__PURE__ */ new Date()).getTime() / 1e3);
8636
+ if (Math.abs(nowSeconds - Number(timestamp)) > (options.toleranceSeconds ?? DEFAULT_TOLERANCE_SECONDS)) return false;
8637
+ try {
8638
+ const raw = Buffer.from(options.publicKey.trim(), "base64");
8639
+ if (raw.length !== 32) return false;
8640
+ const key = (0, import_node_crypto3.createPublicKey)({ key: Buffer.concat([ED25519_SPKI_PREFIX, raw]), format: "der", type: "spki" });
8641
+ return (0, import_node_crypto3.verify)(null, Buffer.from(`${timestamp}|${rawBody}`), key, Buffer.from(signature, "base64"));
8642
+ } catch {
8643
+ return false;
8644
+ }
8645
+ }
8646
+ function handleTelnyxWebhook(rawBody, headers, options) {
8647
+ if (!verifyTelnyxSignature(rawBody, headers, options)) return { ok: false, status: 401, reason: "The signature is missing, wrong or too old" };
8648
+ let parsed;
8649
+ try {
8650
+ const value = JSON.parse(rawBody);
8651
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return { ok: false, status: 400, reason: "The body is not an event" };
8652
+ parsed = value;
8653
+ } catch {
8654
+ return { ok: false, status: 400, reason: "The body is not JSON" };
8655
+ }
8656
+ const eventType = parsed.data?.event_type ?? "";
8657
+ const payload = parsed.data?.payload;
8658
+ const id = payload?.id;
8659
+ const to = payload?.to?.[0]?.phone_number;
8660
+ if (eventType === "message.received") {
8661
+ const from = payload?.from?.phone_number;
8662
+ if (!id || !from || !to) return { ok: false, status: 400, reason: "The message is missing its id or phone numbers" };
8663
+ const text = typeof payload?.text === "string" ? payload.text : "";
8664
+ const type = classifyReply(text);
8665
+ return { ok: true, event: { type, id, from, to, text } };
8666
+ }
8667
+ if (eventType === "message.finalized" || eventType === "message.sent") {
8668
+ if (!id || !to) return { ok: false, status: 400, reason: "The delivery report is missing its id or number" };
8669
+ const status = payload?.to?.[0]?.status;
8670
+ if (eventType === "message.sent" || status !== "delivered" && status !== "delivery_failed" && status !== "sending_failed") {
8671
+ return { ok: true, event: { type: "ignored", eventType } };
8672
+ }
8673
+ const errorCode = payload?.errors?.[0]?.code;
8674
+ return {
8675
+ ok: true,
8676
+ event: { type: "delivery", id, to, status: status === "delivered" ? "delivered" : "failed", ...errorCode === void 0 ? {} : { errorCode: String(errorCode) } }
8677
+ };
8678
+ }
8679
+ return { ok: true, event: { type: "ignored", eventType } };
8680
+ }
8681
+
8682
+ // src/twilio/twilio-sms.ts
8683
+ var DEFAULT_TIMEOUT_MS2 = 1e4;
8684
+ var OPTED_OUT_CODE2 = "21610";
8685
+ function createTwilioSmsAdapter(config) {
8686
+ const accountSid = typeof config.accountSid === "string" ? config.accountSid.trim() : "";
8687
+ const authToken = typeof config.authToken === "string" ? config.authToken.trim() : "";
8688
+ if (!accountSid || !authToken) throw new Error("createTwilioSmsAdapter needs an accountSid and an authToken");
8689
+ const serviceSid = config.messagingServiceSid?.trim() || void 0;
8690
+ const from = config.from ? normalizePhoneNumber(config.from) : null;
8691
+ if (config.from && !from) throw new Error('createTwilioSmsAdapter: "from" must be a phone number such as +13135550100');
8692
+ if (!from && !serviceSid) throw new Error('createTwilioSmsAdapter needs a sending number ("from") or a messagingServiceSid');
8693
+ const doFetch = config.fetch ?? fetch;
8694
+ const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
8695
+ const url = `https://api.twilio.com/2010-04-01/Accounts/${encodeURIComponent(accountSid)}/Messages.json`;
8696
+ const authorization = `Basic ${Buffer.from(`${accountSid}:${authToken}`).toString("base64")}`;
8697
+ return {
8698
+ async send(message) {
8699
+ if (message.channel !== "SMS") return { status: "SKIPPED", reason: "The Twilio adapter only sends text messages" };
8700
+ const to = normalizePhoneNumber(message.to);
8701
+ if (!to) return { status: "SKIPPED", reason: "The recipient is not a valid phone number" };
8702
+ if (!message.body.trim()) return { status: "SKIPPED", reason: "The message is empty" };
8703
+ const form = new URLSearchParams({ To: to, Body: message.body });
8704
+ if (from) form.set("From", from);
8705
+ else if (serviceSid) form.set("MessagingServiceSid", serviceSid);
8706
+ const controller = new AbortController();
8707
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
8708
+ let response;
8709
+ let body;
8710
+ try {
8711
+ response = await doFetch(url, {
8712
+ method: "POST",
8713
+ headers: { Authorization: authorization, "Content-Type": "application/x-www-form-urlencoded" },
8714
+ body: form.toString(),
8715
+ signal: controller.signal
8716
+ });
8717
+ body = await response.json().catch((error2) => {
8718
+ if (controller.signal.aborted) throw error2;
8719
+ return null;
8720
+ });
8721
+ } catch (error2) {
8722
+ const reason = controller.signal.aborted ? `timed out after ${timeoutMs} ms` : error2 instanceof Error ? error2.message : String(error2);
8723
+ throw new SmsSendError(`Twilio could not be reached (${reason}); the message may or may not have been sent`, true, true);
8724
+ } finally {
8725
+ clearTimeout(timer);
8726
+ }
8727
+ if (response.ok) {
8728
+ const id = body?.sid;
8729
+ return id ? { status: "SENT", id } : { status: "SENT" };
8730
+ }
8731
+ const error = body ?? {};
8732
+ const code = error.code === void 0 ? void 0 : String(error.code);
8733
+ if (code === OPTED_OUT_CODE2) return { status: "SKIPPED", reason: "The recipient opted out of text messages" };
8734
+ const serverFault = response.status >= 500;
8735
+ throw new SmsSendError(
8736
+ `Twilio refused the message (HTTP ${response.status}${code ? `, code ${code}` : ""}): ${error.message ?? "no detail given"}`,
8737
+ response.status === 429 || serverFault,
8738
+ serverFault,
8739
+ response.status,
8740
+ code
8741
+ );
8742
+ }
8743
+ };
8744
+ }
8745
+
8746
+ // src/twilio/twilio-inbound.ts
8747
+ var import_node_crypto4 = require("crypto");
8748
+ function expectedSignature(params, options) {
8749
+ const keys = [...new Set(params.keys())].sort();
8750
+ const signed = keys.reduce((text, key) => text + key + params.getAll(key).join(""), options.url);
8751
+ return (0, import_node_crypto4.createHmac)("sha1", options.authToken.trim()).update(signed).digest("base64");
8752
+ }
8753
+ function verifyTwilioSignature(rawBody, headers, options) {
8754
+ const given = readHeader(headers, "x-twilio-signature");
8755
+ if (!given || !options.authToken.trim()) return false;
8756
+ const expected = Buffer.from(expectedSignature(new URLSearchParams(rawBody), options));
8757
+ const actual = Buffer.from(given);
8758
+ return expected.length === actual.length && (0, import_node_crypto4.timingSafeEqual)(expected, actual);
8759
+ }
8760
+ function handleTwilioWebhook(rawBody, headers, options) {
8761
+ if (!verifyTwilioSignature(rawBody, headers, options)) return { ok: false, status: 401, reason: "The signature is missing or wrong" };
8762
+ const params = new URLSearchParams(rawBody);
8763
+ const id = params.get("MessageSid") ?? params.get("SmsSid");
8764
+ const from = params.get("From");
8765
+ const to = params.get("To");
8766
+ if (params.has("MessageStatus") && !params.has("Body")) {
8767
+ const status = params.get("MessageStatus") ?? "";
8768
+ if (!id || !to) return { ok: false, status: 400, reason: "The status report is missing its id or number" };
8769
+ if (status !== "delivered" && status !== "undelivered" && status !== "failed") return { ok: true, event: { type: "ignored", eventType: `status.${status}` } };
8770
+ const errorCode = params.get("ErrorCode");
8771
+ return { ok: true, event: { type: "delivery", id, to, status: status === "delivered" ? "delivered" : "failed", ...errorCode ? { errorCode } : {} } };
8772
+ }
8773
+ if (params.has("Body")) {
8774
+ if (!id || !from || !to) return { ok: false, status: 400, reason: "The message is missing its id or phone numbers" };
8775
+ const text = params.get("Body") ?? "";
8776
+ return { ok: true, event: { type: classifyReply(text), id, from, to, text } };
8777
+ }
8778
+ return { ok: true, event: { type: "ignored", eventType: "unknown" } };
8779
+ }
8780
+
8781
+ // src/sms/per-business-sms.ts
8782
+ var DEFAULT_ADAPTER_TTL_MS = 5 * 6e4;
8783
+ var DEFAULT_NO_NUMBER_TTL_MS = 6e4;
8784
+ function createPerBusinessSmsAdapter(options) {
8785
+ const adapterTtl = options.adapterTtlMs ?? DEFAULT_ADAPTER_TTL_MS;
8786
+ const noNumberTtl = options.noNumberTtlMs ?? DEFAULT_NO_NUMBER_TTL_MS;
8787
+ const now = options.now ?? Date.now;
8788
+ const kept = /* @__PURE__ */ new Map();
8789
+ function adapterFor(organizationId) {
8790
+ const existing = kept.get(organizationId);
8791
+ if (existing && (existing.expiresAt === null || existing.expiresAt > now())) return existing.lookup;
8792
+ const entry = { lookup: Promise.resolve(options.resolve(organizationId)), expiresAt: null };
8793
+ kept.set(organizationId, entry);
8794
+ entry.lookup.then(
8795
+ (adapter) => {
8796
+ entry.expiresAt = now() + (adapter ? adapterTtl : noNumberTtl);
8797
+ },
8798
+ // A failed lookup is not kept; only this entry is removed, not a newer one.
8799
+ () => {
8800
+ if (kept.get(organizationId) === entry) kept.delete(organizationId);
8801
+ }
8802
+ );
8803
+ return entry.lookup;
8804
+ }
8805
+ return {
8806
+ async send(message) {
8807
+ if (message.channel !== "SMS") return { status: "SKIPPED", reason: "This adapter only sends text messages" };
8808
+ if (!message.organizationId) {
8809
+ return { status: "SKIPPED", reason: "The message names no business, so there is no number to send from (run the sender with organization: true)" };
8810
+ }
8811
+ const adapter = await adapterFor(message.organizationId);
8812
+ if (!adapter) return { status: "SKIPPED", reason: "This business has no text-message number set up" };
8813
+ return adapter.send(message);
8814
+ },
8815
+ forget(organizationId) {
8816
+ kept.delete(organizationId);
8817
+ }
8818
+ };
8819
+ }
8820
+
8821
+ // src/sms/text-settings-resolver.ts
8822
+ var import_scheduling77 = require("@ordinatio/scheduling");
8823
+ function createTextSettingsResolver(options) {
8824
+ return async (organizationId) => {
8825
+ const settings = await (0, import_scheduling77.getTextSettings)(await options.db(organizationId), organizationId);
8826
+ if (!settings || !settings.enabled) return null;
8827
+ try {
8828
+ if (settings.provider === "TELNYX" && options.telnyx?.apiKey?.trim()) {
8829
+ return createTelnyxSmsAdapter({ ...options.telnyx, from: settings.fromNumber, fetch: options.fetch });
8830
+ }
8831
+ if (settings.provider === "TWILIO" && options.twilio?.accountSid?.trim() && options.twilio.authToken?.trim()) {
8832
+ return createTwilioSmsAdapter({ ...options.twilio, from: settings.fromNumber, fetch: options.fetch });
8833
+ }
8834
+ } catch (error) {
8835
+ console.error(`[text-settings] could not build the ${settings.provider} sender for organization ${organizationId}:`, error instanceof Error ? error.message : error);
8836
+ return null;
8837
+ }
8838
+ if (settings.provider === "TELNYX" || settings.provider === "TWILIO") {
8839
+ console.error(`[text-settings] organization ${organizationId} chose ${settings.provider}, but this server has no usable ${settings.provider} account`);
8840
+ }
8841
+ return null;
8842
+ };
8843
+ }
8844
+
8845
+ // src/outlook-sync/outlook-config.ts
8846
+ var BLOCKED_TYPE_SLUG = "blocked";
8847
+ var GRAPH_BASE = "https://graph.microsoft.com/v1.0";
8848
+ var MICROSOFT_TOKEN_ENDPOINT = "https://login.microsoftonline.com/common/oauth2/v2.0/token";
8849
+ var OUTLOOK_CALENDAR_SCOPE = "https://graph.microsoft.com/Calendars.ReadWrite offline_access";
8850
+ function problem(config, message, context) {
8851
+ config.onProblem?.(message, context);
8852
+ }
8853
+
8854
+ // src/outlook-sync/outlook-access-token.ts
8855
+ var REFRESH_MARGIN_MS = 5 * 60 * 1e3;
8856
+ async function getOutlookAccessToken(config, calendarId) {
8857
+ const calendar = await config.db.schedulingCalendar.findUnique({
8858
+ where: { id: calendarId },
8859
+ select: {
8860
+ outlookCalendarId: true,
8861
+ outlookAccessToken: true,
8862
+ outlookRefreshToken: true,
8863
+ outlookTokenExpiresAt: true
8864
+ }
8865
+ });
8866
+ if (!calendar?.outlookCalendarId || !calendar.outlookRefreshToken) return null;
8867
+ const now = (config.now ?? (() => /* @__PURE__ */ new Date()))();
8868
+ const stillValid = calendar.outlookAccessToken && calendar.outlookTokenExpiresAt && calendar.outlookTokenExpiresAt.getTime() - now.getTime() >= REFRESH_MARGIN_MS;
8869
+ if (stillValid) return calendar.outlookAccessToken;
8870
+ try {
8871
+ const response = await (config.fetch ?? fetch)(MICROSOFT_TOKEN_ENDPOINT, {
8872
+ method: "POST",
8873
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
8874
+ body: new URLSearchParams({
8875
+ client_id: config.clientId.trim(),
8876
+ client_secret: config.clientSecret.trim(),
8877
+ refresh_token: calendar.outlookRefreshToken,
8878
+ grant_type: "refresh_token",
8879
+ scope: OUTLOOK_CALENDAR_SCOPE
8880
+ })
8881
+ });
8882
+ if (!response.ok) throw new Error(`Token refresh HTTP ${response.status}`);
8883
+ const data = await response.json();
8884
+ if (!data.access_token || typeof data.expires_in !== "number") throw new Error("Token refresh answered without a token");
8885
+ await config.db.schedulingCalendar.update({
8886
+ where: { id: calendarId },
8887
+ data: {
8888
+ outlookAccessToken: data.access_token,
8889
+ outlookRefreshToken: data.refresh_token ?? calendar.outlookRefreshToken,
8890
+ outlookTokenExpiresAt: new Date(now.getTime() + data.expires_in * 1e3)
8891
+ }
8892
+ });
8893
+ return data.access_token;
8894
+ } catch (error) {
8895
+ problem(config, "Outlook token refresh failed; the calendar must be reconnected", {
8896
+ calendarId,
8897
+ error: error instanceof Error ? error.message : String(error)
8898
+ });
8899
+ return null;
8900
+ }
8901
+ }
8902
+
8903
+ // src/outlook-sync/outlook-push.ts
8904
+ async function pushAppointmentToOutlook(config, appointmentId) {
8905
+ const appointment = await config.db.appointment.findUnique({
8906
+ where: { id: appointmentId },
8907
+ include: {
8908
+ type: { select: { name: true, slug: true } },
8909
+ calendar: { select: { id: true, outlookCalendarId: true } }
8910
+ }
8911
+ });
8912
+ if (!appointment?.calendar.outlookCalendarId) return null;
8913
+ if (appointment.type.slug === BLOCKED_TYPE_SLUG) return null;
8914
+ const accessToken = await getOutlookAccessToken(config, appointment.calendarId);
8915
+ if (!accessToken) return null;
8916
+ const body = {
8917
+ subject: `${appointment.type.name} \u2014 ${appointment.clientName}`,
8918
+ body: {
8919
+ contentType: "text",
8920
+ content: [
8921
+ `Service: ${appointment.type.name}`,
8922
+ `Duration: ${appointment.duration} min`,
8923
+ appointment.clientPhone ? `Phone: ${appointment.clientPhone}` : "",
8924
+ appointment.clientEmail ? `Email: ${appointment.clientEmail}` : ""
8925
+ ].filter(Boolean).join("\n")
8926
+ },
8927
+ // UTC on both sides so the event lands at the stored instant whatever zone the Outlook calendar uses.
8928
+ start: { dateTime: appointment.startTime.toISOString(), timeZone: "UTC" },
8929
+ end: { dateTime: appointment.endTime.toISOString(), timeZone: "UTC" }
8930
+ };
8931
+ const calendarUrl = `${GRAPH_BASE}/me/calendars/${encodeURIComponent(appointment.calendar.outlookCalendarId)}/events`;
8932
+ const isUpdate = Boolean(appointment.outlookEventId);
8933
+ const method = isUpdate ? "PATCH" : "POST";
8934
+ const url = isUpdate ? `${calendarUrl}/${encodeURIComponent(appointment.outlookEventId)}` : calendarUrl;
8935
+ const response = await (config.fetch ?? fetch)(url, {
8936
+ method,
8937
+ headers: { Authorization: `Bearer ${accessToken}`, "Content-Type": "application/json" },
8938
+ body: JSON.stringify(body)
8939
+ });
8940
+ if (!response.ok) throw new Error(`Outlook ${method} event failed with HTTP ${response.status}`);
8941
+ const created = await response.json();
8942
+ if (!isUpdate && created.id) {
8943
+ try {
8944
+ await config.db.appointment.update({ where: { id: appointmentId }, data: { outlookEventId: created.id } });
8945
+ } catch (error) {
8946
+ const removed = await (config.fetch ?? fetch)(`${calendarUrl}/${encodeURIComponent(created.id)}`, {
8947
+ method: "DELETE",
8948
+ headers: { Authorization: `Bearer ${accessToken}` }
8949
+ }).then((r) => r.ok || r.status === 404, () => false);
8950
+ if (!removed) problem(config, "An Outlook event was created but its id could not be saved or the event removed", { appointmentId });
8951
+ throw error;
8952
+ }
8953
+ }
8954
+ return created.id ?? appointment.outlookEventId ?? null;
8955
+ }
8956
+ async function deleteOutlookEvent(config, appointmentId) {
8957
+ const appointment = await config.db.appointment.findUnique({
8958
+ where: { id: appointmentId },
8959
+ select: { outlookEventId: true, calendarId: true, calendar: { select: { outlookCalendarId: true } }, type: { select: { slug: true } } }
8960
+ });
8961
+ if (!appointment?.outlookEventId || !appointment.calendar.outlookCalendarId) return;
8962
+ if (appointment.type.slug === BLOCKED_TYPE_SLUG) return;
8963
+ const accessToken = await getOutlookAccessToken(config, appointment.calendarId);
8964
+ if (!accessToken) return;
8965
+ const response = await (config.fetch ?? fetch)(
8966
+ `${GRAPH_BASE}/me/calendars/${encodeURIComponent(appointment.calendar.outlookCalendarId)}/events/${encodeURIComponent(appointment.outlookEventId)}`,
8967
+ { method: "DELETE", headers: { Authorization: `Bearer ${accessToken}` } }
8968
+ );
8969
+ if (!response.ok && response.status !== 404) throw new Error(`Outlook DELETE event failed with HTTP ${response.status}`);
8970
+ await config.db.appointment.update({ where: { id: appointmentId }, data: { outlookEventId: null } });
8971
+ }
8972
+
8973
+ // src/outlook-sync/outlook-pull.ts
8974
+ var MAX_PAGES = 200;
8975
+ var withZone = (dateTime) => dateTime.endsWith("Z") ? dateTime : `${dateTime}Z`;
8976
+ async function pullChangesFromOutlook(config, hooks, calendarId) {
8977
+ return pullOnce(config, hooks, calendarId, { isRestart: false, skipWindowCheck: false });
8978
+ }
8979
+ async function pullOnce(config, hooks, calendarId, mode) {
8980
+ const { isRestart } = mode;
8981
+ const { db } = config;
8982
+ const calendar = await db.schedulingCalendar.findUnique({ where: { id: calendarId } });
8983
+ if (!calendar?.outlookCalendarId) return { synced: 0 };
8984
+ const now = (config.now ?? (() => /* @__PURE__ */ new Date()))();
8985
+ const windowIsStale = calendar.lastSyncAt != null && calendar.lastSyncAt.getUTCMonth() !== now.getUTCMonth();
8986
+ if (calendar.outlookSyncToken && windowIsStale && !isRestart && !mode.skipWindowCheck) {
8987
+ if (!await getOutlookAccessToken(config, calendarId)) return { synced: 0 };
8988
+ const drained = await pullOnce(config, hooks, calendarId, { isRestart: false, skipWindowCheck: true });
8989
+ const fresh = await pullOnce(config, hooks, calendarId, { isRestart: true, skipWindowCheck: true, ignoreSavedLink: true });
8990
+ return { synced: drained.synced + fresh.synced };
8991
+ }
8992
+ const accessToken = await getOutlookAccessToken(config, calendarId);
8993
+ if (!accessToken) return { synced: 0 };
8994
+ const headers = { Authorization: `Bearer ${accessToken}`, Prefer: 'outlook.timezone="UTC"' };
8995
+ const horizon = new Date(now);
8996
+ horizon.setUTCFullYear(horizon.getUTCFullYear() + 1);
8997
+ const firstUrl = `${GRAPH_BASE}/me/calendars/${encodeURIComponent(calendar.outlookCalendarId)}/calendarView/delta?startDateTime=${now.toISOString()}&endDateTime=${horizon.toISOString()}`;
8998
+ let url = mode.ignoreSavedLink ? firstUrl : calendar.outlookSyncToken ?? firstUrl;
8999
+ let deltaLink = null;
9000
+ let synced = 0;
9001
+ let unhandled = null;
9002
+ let blockedType = null;
9003
+ for (let pageNumber = 0; url; pageNumber++) {
9004
+ if (pageNumber >= MAX_PAGES) throw new Error("Outlook delta query returned more pages than expected");
9005
+ if (!url.startsWith(`${GRAPH_BASE}/`)) throw new Error("Outlook delta link does not point at Microsoft Graph");
9006
+ const response = await (config.fetch ?? fetch)(url, { headers });
9007
+ if (response.status === 410) {
9008
+ if (isRestart) throw new Error("Outlook delta query was refused with HTTP 410 on a fresh start");
9009
+ problem(config, "Outlook delta link expired; starting a full sync", { calendarId });
9010
+ await db.schedulingCalendar.update({ where: { id: calendarId }, data: { outlookSyncToken: null } });
9011
+ return pullOnce(config, hooks, calendarId, { isRestart: true, skipWindowCheck: true });
9012
+ }
9013
+ if (!response.ok) throw new Error(`Outlook delta query failed with HTTP ${response.status}`);
9014
+ const page = await response.json();
9015
+ for (const event of page.value) {
9016
+ if (!event.id) continue;
9017
+ const existing = await db.appointment.findFirst({ where: { outlookEventId: event.id, calendarId } });
9018
+ if (event["@removed"]) {
9019
+ if (existing && existing.status !== "CANCELLED") {
9020
+ try {
9021
+ if (await hooks.cancelAppointment(existing.id)) synced++;
9022
+ else unhandled ??= new Error(`The host did not cancel appointment ${existing.id}`);
9023
+ } catch (error) {
9024
+ unhandled ??= error instanceof Error ? error : new Error(String(error));
9025
+ problem(config, "Cancelling an appointment deleted in Outlook failed", { appointmentId: existing.id, error: unhandled.message });
9026
+ }
9027
+ }
9028
+ continue;
9029
+ }
9030
+ if (!event.start?.dateTime || !event.end?.dateTime) continue;
9031
+ const startTime = new Date(withZone(event.start.dateTime));
9032
+ const endTime = new Date(withZone(event.end.dateTime));
9033
+ if (Number.isNaN(startTime.getTime()) || Number.isNaN(endTime.getTime()) || endTime <= startTime) continue;
9034
+ const duration = Math.round((endTime.getTime() - startTime.getTime()) / 6e4);
9035
+ if (existing) {
9036
+ if (existing.status === "CANCELLED") continue;
9037
+ const moved = existing.startTime.getTime() !== startTime.getTime() || existing.endTime.getTime() !== endTime.getTime();
9038
+ if (!moved) continue;
9039
+ try {
9040
+ await hooks.onAppointmentMoved?.({ appointmentId: existing.id, organizationId: calendar.organizationId, startTime, endTime });
9041
+ await db.appointment.update({ where: { id: existing.id }, data: { startTime, endTime, duration } });
9042
+ } catch (error) {
9043
+ unhandled ??= error instanceof Error ? error : new Error(String(error));
9044
+ problem(config, "Saving a time changed in Outlook failed", { appointmentId: existing.id, error: unhandled.message });
9045
+ continue;
9046
+ }
9047
+ synced++;
9048
+ continue;
9049
+ }
9050
+ blockedType ??= await findOrCreateBlockedType(config, calendar.organizationId);
9051
+ await db.appointment.create({
9052
+ data: {
9053
+ calendarId,
9054
+ typeId: blockedType.id,
9055
+ startTime,
9056
+ endTime,
9057
+ duration,
9058
+ timezone: calendar.timezone,
9059
+ status: "CONFIRMED",
9060
+ clientName: event.subject || "Blocked",
9061
+ clientEmail: "",
9062
+ outlookEventId: event.id
9063
+ }
9064
+ });
9065
+ synced++;
9066
+ }
9067
+ deltaLink = page["@odata.deltaLink"] ?? null;
9068
+ url = page["@odata.nextLink"] ?? "";
9069
+ }
9070
+ if (unhandled) throw unhandled;
9071
+ if (deltaLink) {
9072
+ const isDrain = mode.skipWindowCheck && !isRestart;
9073
+ await db.schedulingCalendar.update({
9074
+ where: { id: calendarId },
9075
+ data: isDrain ? { outlookSyncToken: deltaLink } : { outlookSyncToken: deltaLink, lastSyncAt: now }
9076
+ });
9077
+ }
9078
+ return { synced };
9079
+ }
9080
+ async function findOrCreateBlockedType(config, organizationId) {
9081
+ const find = () => config.db.appointmentType.findFirst({ where: { slug: BLOCKED_TYPE_SLUG, organizationId } });
9082
+ const found = await find();
9083
+ if (found) return found;
9084
+ try {
9085
+ return await config.db.appointmentType.create({
9086
+ data: {
9087
+ name: "Blocked",
9088
+ slug: BLOCKED_TYPE_SLUG,
9089
+ duration: 60,
9090
+ color: "#6B7280",
9091
+ isActive: false,
9092
+ // never offered for booking
9093
+ organizationId
9094
+ }
9095
+ });
9096
+ } catch (error) {
9097
+ const raced = await find();
9098
+ if (raced) return raced;
9099
+ throw error;
9100
+ }
9101
+ }
9102
+
9103
+ // src/outlook-sync/create-outlook-calendar-sync.ts
9104
+ function createOutlookCalendarSync(config, hooks) {
9105
+ return {
9106
+ adapter: {
9107
+ async upsertEvent(event) {
9108
+ const externalId = await pushAppointmentToOutlook(config, event.appointmentId);
9109
+ return externalId ? { externalId } : {};
9110
+ },
9111
+ async removeEvent(ref) {
9112
+ await deleteOutlookEvent(config, ref.appointmentId);
9113
+ }
9114
+ },
9115
+ pull: async (calendarId) => await pullChangesFromOutlook(config, hooks, calendarId)
9116
+ };
9117
+ }
9118
+
8360
9119
  // src/staff/simple-staff.ts
8361
9120
  var DEFAULT_ADMIN_ROLES = ["OWNER", "ADMIN", "MANAGER"];
8362
9121
  function createStaffContext(input) {
@@ -8546,9 +9305,12 @@ function createNodeListener(api, options) {
8546
9305
  RouteClientSchema,
8547
9306
  SLOT_GRANULARITY_DEFAULT,
8548
9307
  SLOT_GRANULARITY_OPTIONS,
9308
+ SmsSendError,
8549
9309
  TERMINAL_SUCCESS_STATUSES,
8550
9310
  TOKEN_TTL_DAYS,
9311
+ TelnyxSendError,
8551
9312
  TestRoutingFormSchema,
9313
+ TextSettingsSchema,
8552
9314
  UnverifiedPaymentError,
8553
9315
  UpdateAppointmentCategorySchema,
8554
9316
  UpdateAppointmentTypeSchema,
@@ -8564,6 +9326,8 @@ function createNodeListener(api, options) {
8564
9326
  calendarVisibilityFilter,
8565
9327
  canSeeAppointmentInScope,
8566
9328
  canSeeCalendarInScope,
9329
+ checkSendingDomain,
9330
+ classifyReply,
8567
9331
  createBalanceIntent,
8568
9332
  createBearerStaffResolver,
8569
9333
  createMemoryAvailabilityCache,
@@ -8572,25 +9336,37 @@ function createNodeListener(api, options) {
8572
9336
  createNoBalancePaymentControl,
8573
9337
  createNoPaymentAdapter,
8574
9338
  createNodeListener,
9339
+ createOutlookCalendarSync,
9340
+ createPerBusinessSmsAdapter,
8575
9341
  createSchedulingApi,
8576
9342
  createScopedVisibility,
9343
+ createSendingDomainVerifier,
8577
9344
  createSingleOrganizationDirectory,
8578
9345
  createSingleOrganizationResolver,
8579
9346
  createStaffContext,
8580
9347
  createStripePaymentAdapter,
9348
+ createTelnyxSmsAdapter,
9349
+ createTextSettingsResolver,
9350
+ createTwilioSmsAdapter,
8581
9351
  decimalToCents,
8582
9352
  defaultCorsHeaders,
8583
9353
  getErrorCode,
8584
9354
  getErrorMessage,
8585
9355
  getErrorRef,
9356
+ handleTelnyxWebhook,
9357
+ handleTwilioWebhook,
8586
9358
  isCalendarVisibleInScope,
8587
9359
  isSchedulingServiceError,
8588
9360
  isSupportedCurrency,
8589
9361
  isTokenExpired,
9362
+ normalizePhoneNumber,
9363
+ normalizeSendingDomain,
8590
9364
  parsePagination,
8591
9365
  persistRefundOutcome,
8592
9366
  recordBalanceIntent,
8593
9367
  runCalendarRemoveWithoutBlocking,
8594
9368
  runCalendarSyncWithoutBlocking,
9369
+ verifyTelnyxSignature,
9370
+ verifyTwilioSignature,
8595
9371
  visibleCalendarIdsInScope
8596
9372
  });