@ordinatio/scheduling-api 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  import {
2
+ ApiKeySchema,
2
3
  BookingPageConfigSchema,
3
4
  BookingPageThemeSchema,
4
5
  BrandSchema,
@@ -28,6 +29,7 @@ import {
28
29
  SLOT_GRANULARITY_DEFAULT,
29
30
  SLOT_GRANULARITY_OPTIONS,
30
31
  TestRoutingFormSchema,
32
+ TextSettingsSchema,
31
33
  UpdateAppointmentCategorySchema,
32
34
  UpdateAppointmentTypeSchema,
33
35
  UpdateBookingPageSchema,
@@ -37,7 +39,7 @@ import {
37
39
  UpdatePackagePurchaseSchema,
38
40
  UpdateRoutingFormSchema,
39
41
  UpdateServicePackageSchema
40
- } from "./chunk-WZ5KO7IW.mjs";
42
+ } from "./chunk-X5BVCLX6.mjs";
41
43
 
42
44
  // src/create-api.ts
43
45
  import * as engine from "@ordinatio/scheduling";
@@ -53,6 +55,82 @@ function defaultCorsHeaders() {
53
55
  };
54
56
  }
55
57
 
58
+ // src/api-keys/api-key-host.ts
59
+ import { verifyApiKey } from "@ordinatio/scheduling";
60
+
61
+ // src/staff/simple-staff.ts
62
+ var DEFAULT_ADMIN_ROLES = ["OWNER", "ADMIN", "MANAGER"];
63
+ function createStaffContext(input) {
64
+ const adminRoles = (input.adminRoles ?? DEFAULT_ADMIN_ROLES).map((role) => role.toUpperCase());
65
+ const { db, organizationId } = input;
66
+ return {
67
+ userId: input.userId,
68
+ organizationId,
69
+ role: input.role,
70
+ isAdmin: adminRoles.includes(input.role.toUpperCase()),
71
+ schedulingEnabled: input.schedulingEnabled ?? true,
72
+ db,
73
+ visibleCalendars: async () => null,
74
+ visibleCalendarIds: async () => void 0,
75
+ canSeeCalendar: async (calendarId) => Boolean(await db.schedulingCalendar.findFirst({ where: { id: calendarId, organizationId }, select: { id: true } })),
76
+ canSeeAppointment: async (appointmentId) => Boolean(await db.appointment.findFirst({ where: { id: appointmentId, calendar: { organizationId } }, select: { id: true } })),
77
+ // The package has no client table, so there is no preference to read.
78
+ preferredLocationOf: async () => null
79
+ };
80
+ }
81
+ var BEARER = /^bearer\s+(\S+)$/i;
82
+ function createBearerStaffResolver(input) {
83
+ return {
84
+ async resolve(request) {
85
+ const token = BEARER.exec(request.headers.get("authorization") ?? "")?.[1];
86
+ if (!token) return null;
87
+ const person = await input.authenticate(token, request);
88
+ if (!person) return null;
89
+ return createStaffContext({
90
+ ...person,
91
+ db: await input.db(person),
92
+ adminRoles: input.adminRoles,
93
+ schedulingEnabled: input.schedulingEnabled ? await input.schedulingEnabled(person) : void 0
94
+ });
95
+ }
96
+ };
97
+ }
98
+
99
+ // src/api-keys/api-key-host.ts
100
+ var API_KEY_ROLE_PREFIX = "API_KEY_";
101
+ var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
102
+ function bearerKeyOf(request) {
103
+ const header = request.headers.get("authorization");
104
+ if (!header) return null;
105
+ const match = /^[Bb][Ee][Aa][Rr][Ee][Rr]\s+(osk_\S+)$/.exec(header.trim());
106
+ return match ? match[1] : null;
107
+ }
108
+ function contextOf(key, db, schedulingEnabled) {
109
+ return createStaffContext({
110
+ // The key, not the person who made it, is what the rate limit counts.
111
+ userId: `api-key:${key.id}`,
112
+ organizationId: key.organizationId,
113
+ role: `${API_KEY_ROLE_PREFIX}${key.access}`,
114
+ adminRoles: [`${API_KEY_ROLE_PREFIX}READ`, `${API_KEY_ROLE_PREFIX}FULL`],
115
+ schedulingEnabled,
116
+ db
117
+ });
118
+ }
119
+ async function hostForRequest(host, request, route) {
120
+ if (route.public || !host.apiKeys) return host;
121
+ const secret = bearerKeyOf(request);
122
+ if (secret === null) return host;
123
+ const db = await host.apiKeys.db();
124
+ const key = await verifyApiKey(db, secret);
125
+ if (!key) return Response.json({ error: "Unauthorized" }, { status: 401 });
126
+ if (route.personOnly) return Response.json({ error: "This needs a person signed in at a browser, not an API key" }, { status: 403 });
127
+ if (key.access === "READ" && !SAFE_METHODS.has(request.method.toUpperCase())) {
128
+ return Response.json({ error: "This API key is read-only" }, { status: 403 });
129
+ }
130
+ const context = contextOf(key, db, await host.schedulingEnabledFor(key.organizationId));
131
+ return { ...host, staff: { resolve: async () => context } };
132
+ }
133
+
56
134
  // src/availability/memory-availability-cache.ts
57
135
  var TTL_MS = 6e4;
58
136
  var DEFAULT_MAX_ENTRIES = 2e3;
@@ -1714,9 +1792,9 @@ function invalid(error) {
1714
1792
  details: error.issues.map((e) => ({ field: e.path.join("."), message: e.message }))
1715
1793
  }, { status: 400 });
1716
1794
  }
1717
- function failure(label, error, fallback) {
1795
+ function failure(label2, error, fallback) {
1718
1796
  const ref = getErrorRef(error);
1719
- console.error(`[${label}]`, ref, error instanceof Error ? error.message : error);
1797
+ console.error(`[${label2}]`, ref, error instanceof Error ? error.message : error);
1720
1798
  return Response.json({ error: getErrorMessage(error, fallback), ...ref && { ref } }, { status: 500 });
1721
1799
  }
1722
1800
  async function updateLocation(request, { host, params }) {
@@ -2472,16 +2550,16 @@ async function attemptLegRefund(payments, paymentIntentId, idempotencyKeySuffix,
2472
2550
  return failedLeg(errorCode, logLabel, appointmentId, paymentIntentId, idempotencyKey, retriedAfterReplay, { error: result.error, message: result.error ?? result.code ?? "no reason given", requestId: result.requestId });
2473
2551
  }
2474
2552
  }
2475
- function failedLeg(errorCode, logLabel, appointmentId, paymentIntentId, idempotencyKey, retriedAfterReplay, failure3) {
2476
- const diagnostic = schedError14(errorCode, { error: failure3.error, appointmentId, paymentIntentId });
2553
+ function failedLeg(errorCode, logLabel, appointmentId, paymentIntentId, idempotencyKey, retriedAfterReplay, failure5) {
2554
+ const diagnostic = schedError14(errorCode, { error: failure5.error, appointmentId, paymentIntentId });
2477
2555
  console.error(
2478
2556
  `[resolve-refund] ${logLabel} refund failed${retriedAfterReplay ? " (after a fresh-key re-attempt)" : ""} \u2014 manual refund may be required:`,
2479
2557
  diagnostic.ref,
2480
2558
  appointmentId,
2481
2559
  paymentIntentId,
2482
- `requestId=${failure3.requestId}`,
2560
+ `requestId=${failure5.requestId}`,
2483
2561
  `idempotencyKey=${idempotencyKey}`,
2484
- failure3.message
2562
+ failure5.message
2485
2563
  );
2486
2564
  return { succeeded: false, amountCents: null };
2487
2565
  }
@@ -3472,24 +3550,24 @@ import { scheduleNotifications as scheduleNotifications4, queueStaffNotification
3472
3550
  // src/recurring/failure-collector.ts
3473
3551
  function createFailureCollector() {
3474
3552
  const problems = /* @__PURE__ */ new Map();
3475
- const record = (label, error) => {
3553
+ const record = (label2, error) => {
3476
3554
  const message = error instanceof Error ? error.message : String(error);
3477
- const key = `${label}\0${message}`;
3555
+ const key = `${label2}\0${message}`;
3478
3556
  const known = problems.get(key);
3479
3557
  if (known) known.count += 1;
3480
- else problems.set(key, { label, message, count: 1 });
3558
+ else problems.set(key, { label: label2, message, count: 1 });
3481
3559
  };
3482
- const attempt = async (label, work) => {
3560
+ const attempt = async (label2, work) => {
3483
3561
  try {
3484
3562
  await work();
3485
3563
  return true;
3486
3564
  } catch (error) {
3487
- record(label, error);
3565
+ record(label2, error);
3488
3566
  return false;
3489
3567
  }
3490
3568
  };
3491
3569
  const lines = () => [...problems.values()].map(
3492
- ({ label, message, count }) => count === 1 ? `${label} failed: ${message}` : `${label} failed for ${count} visits: ${message}`
3570
+ ({ label: label2, message, count }) => count === 1 ? `${label2} failed: ${message}` : `${label2} failed for ${count} visits: ${message}`
3493
3571
  );
3494
3572
  return { record, attempt, lines };
3495
3573
  }
@@ -4039,9 +4117,9 @@ async function businessName(host, db, organizationId) {
4039
4117
 
4040
4118
  // src/handlers/appointment-messages.ts
4041
4119
  var NOT_FOUND4 = () => Response.json({ error: "Appointment not found" }, { status: 404 });
4042
- function failure2(label, error, fallback) {
4120
+ function failure2(label2, error, fallback) {
4043
4121
  const ref = getErrorRef(error);
4044
- console.error(`[${label}]`, ref, error instanceof Error ? error.message : error);
4122
+ console.error(`[${label2}]`, ref, error instanceof Error ? error.message : error);
4045
4123
  return Response.json({ error: getErrorMessage(error, fallback), ...ref && { ref } }, { status: 500 });
4046
4124
  }
4047
4125
  async function sendFollowup(request, { host, params }) {
@@ -6653,15 +6731,192 @@ async function deleteBrandRoute(request, { host }) {
6653
6731
  }
6654
6732
  }
6655
6733
 
6734
+ // src/handlers/admin-api-keys.ts
6735
+ import { createApiKey, listApiKeys, revokeApiKey, SchedulingValidationError as SchedulingValidationError12 } from "@ordinatio/scheduling";
6736
+ var NOT_ENABLED4 = { error: "API keys are not enabled on this server" };
6737
+ function failure3(error, fallback) {
6738
+ if (error instanceof SchedulingValidationError12) {
6739
+ const details = error.context.errors;
6740
+ return Response.json({ error: error.message, code: error.code, ref: getErrorRef(error), ...details ? { details } : {} }, { status: 400 });
6741
+ }
6742
+ console.error("[api-keys]", error);
6743
+ return Response.json({ error: fallback }, { status: 500 });
6744
+ }
6745
+ async function requireKeyAdmin(host, request, options) {
6746
+ const staff = await requireAdminStaff(host, request, options);
6747
+ if (staff instanceof Response) return staff;
6748
+ if (!host.apiKeys) return Response.json(NOT_ENABLED4, { status: 501 });
6749
+ if (staff.role.startsWith(API_KEY_ROLE_PREFIX)) return Response.json({ error: "API keys are managed by a signed-in person, not with an API key" }, { status: 403 });
6750
+ return staff;
6751
+ }
6752
+ async function listApiKeysRoute(request, { host }) {
6753
+ try {
6754
+ const staff = await requireKeyAdmin(host, request, { action: "admin-api-keys-list", tier: "GENERAL" });
6755
+ if (staff instanceof Response) return staff;
6756
+ return Response.json({ keys: await listApiKeys(staff.db, staff.organizationId) });
6757
+ } catch (error) {
6758
+ return failure3(error, "Failed to list the API keys");
6759
+ }
6760
+ }
6761
+ async function createApiKeyRoute(request, { host }) {
6762
+ try {
6763
+ const staff = await requireKeyAdmin(host, request, { action: "admin-api-keys-create", tier: "SETTINGS" });
6764
+ if (staff instanceof Response) return staff;
6765
+ const validation = await parseBody(request, ApiKeySchema);
6766
+ if (!validation.success) return validation.response;
6767
+ const { key, view } = await createApiKey(staff.db, staff.organizationId, validation.data, staff.userId);
6768
+ await host.activity.log(staff.db, { action: "scheduling.api_key_created", description: `made the API key "${view.name}"`, metadata: { keyId: view.id, access: view.access } }).catch((error) => {
6769
+ console.error("[api-keys] could not record the new key in the activity log", error);
6770
+ });
6771
+ return Response.json({ key, apiKey: view }, { status: 201, headers: { "Cache-Control": "no-store" } });
6772
+ } catch (error) {
6773
+ return failure3(error, "Failed to make the API key");
6774
+ }
6775
+ }
6776
+ async function revokeApiKeyRoute(request, { host, params }) {
6777
+ try {
6778
+ const staff = await requireKeyAdmin(host, request, { action: "admin-api-keys-revoke", tier: "DELETE" });
6779
+ if (staff instanceof Response) return staff;
6780
+ const revoked = await revokeApiKey(staff.db, staff.organizationId, params.id);
6781
+ if (revoked) await host.activity.log(staff.db, { action: "scheduling.api_key_revoked", description: "revoked an API key", metadata: { keyId: params.id } });
6782
+ return Response.json({ revoked });
6783
+ } catch (error) {
6784
+ return failure3(error, "Failed to revoke the API key");
6785
+ }
6786
+ }
6787
+
6788
+ // src/handlers/admin-text-settings.ts
6789
+ import { deleteTextSettings, getTextSettings, saveTextSettings, SchedulingValidationError as SchedulingValidationError13 } from "@ordinatio/scheduling";
6790
+ var NOT_ENABLED5 = { error: "Text-message settings are not enabled on this server" };
6791
+ function failure4(error, fallback) {
6792
+ if (error instanceof SchedulingValidationError13) {
6793
+ const details = error.context.errors;
6794
+ return Response.json({ error: error.message, code: error.code, ref: getErrorRef(error), ...details ? { details } : {} }, { status: 400 });
6795
+ }
6796
+ console.error("[text-settings]", error);
6797
+ return Response.json({ error: fallback }, { status: 500 });
6798
+ }
6799
+ async function requireTextAdmin(host, request, options) {
6800
+ const staff = await requireAdminStaff(host, request, options);
6801
+ if (staff instanceof Response) return staff;
6802
+ if (!host.textMessages) return Response.json(NOT_ENABLED5, { status: 501 });
6803
+ return staff;
6804
+ }
6805
+ async function getTextSettingsRoute(request, { host }) {
6806
+ try {
6807
+ const staff = await requireTextAdmin(host, request, { action: "admin-text-settings-get", tier: "GENERAL" });
6808
+ if (staff instanceof Response) return staff;
6809
+ return Response.json({ settings: await getTextSettings(staff.db, staff.organizationId), providers: host.textMessages?.providers ?? ["TELNYX", "TWILIO"] });
6810
+ } catch (error) {
6811
+ return failure4(error, "Failed to read the text-message settings");
6812
+ }
6813
+ }
6814
+ async function saveTextSettingsRoute(request, { host }) {
6815
+ try {
6816
+ const staff = await requireTextAdmin(host, request, { action: "admin-text-settings-save", tier: "UPDATE" });
6817
+ if (staff instanceof Response) return staff;
6818
+ const validation = await parseBody(request, TextSettingsSchema);
6819
+ if (!validation.success) return validation.response;
6820
+ const settings = await saveTextSettings(staff.db, staff.organizationId, validation.data, { providers: host.textMessages?.providers });
6821
+ await host.activity.log(staff.db, {
6822
+ action: "scheduling.text_settings_saved",
6823
+ description: "changed the text-message settings",
6824
+ metadata: { provider: settings.provider, enabled: settings.enabled }
6825
+ });
6826
+ return Response.json({ settings });
6827
+ } catch (error) {
6828
+ return failure4(error, "Failed to save the text-message settings");
6829
+ }
6830
+ }
6831
+ async function deleteTextSettingsRoute(request, { host }) {
6832
+ try {
6833
+ const staff = await requireTextAdmin(host, request, { action: "admin-text-settings-delete", tier: "DELETE" });
6834
+ if (staff instanceof Response) return staff;
6835
+ const removed = await deleteTextSettings(staff.db, staff.organizationId);
6836
+ if (removed) await host.activity.log(staff.db, { action: "scheduling.text_settings_removed", description: "removed the text-message settings", metadata: {} });
6837
+ return Response.json({ removed });
6838
+ } catch (error) {
6839
+ return failure4(error, "Failed to remove the text-message settings");
6840
+ }
6841
+ }
6842
+
6843
+ // src/sending-domain/check-sending-domain.ts
6844
+ function recordsFor(records, domain) {
6845
+ return typeof records === "function" ? records(domain) : records;
6846
+ }
6847
+ var DOMAIN_PATTERN = /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;
6848
+ var NOT_FOUND_CODES = /* @__PURE__ */ new Set(["ENODATA", "ENOTFOUND"]);
6849
+ function normalizeSendingDomain(raw) {
6850
+ const domain = raw.trim().toLowerCase().replace(/\.$/, "");
6851
+ return DOMAIN_PATTERN.test(domain) ? domain : null;
6852
+ }
6853
+ function recordHost(record, domain) {
6854
+ return record.name === "@" ? domain : `${record.name}.${domain}`;
6855
+ }
6856
+ var clean = (value) => value.trim().replace(/\.$/, "").toLowerCase();
6857
+ function matches(record, published) {
6858
+ if (record.type === "CNAME") return clean(published) === clean(record.value);
6859
+ const fold = (value) => record.purpose === "dkim" ? value.trim() : value.trim().toLowerCase();
6860
+ if (record.match !== "contains") return fold(published) === fold(record.value);
6861
+ const terms = fold(published).split(/\s+/);
6862
+ return fold(record.value).split(/\s+/).every((term) => terms.includes(term));
6863
+ }
6864
+ async function lookUp(resolver, record, host) {
6865
+ if (record.type === "CNAME") return await resolver.resolveCname(host);
6866
+ return (await resolver.resolveTxt(host)).map((chunks) => chunks.join(""));
6867
+ }
6868
+ var label = { spf: "SPF", dkim: "DKIM", dmarc: "DMARC", other: "This" };
6869
+ async function checkRecord(resolver, record, domain) {
6870
+ const host = recordHost(record, domain);
6871
+ const who = label[record.purpose];
6872
+ try {
6873
+ const published = await lookUp(resolver, record, host);
6874
+ if (published.some((value) => matches(record, value))) {
6875
+ return { record, host, status: "found", message: `${who} record is in place.` };
6876
+ }
6877
+ const hint = published.length === 0 ? "is empty" : "does not match";
6878
+ return { record, host, status: "wrong", message: `${who} record at ${host} ${hint}. Replace it with the value shown.` };
6879
+ } catch (error) {
6880
+ const code = error?.code;
6881
+ if (code && NOT_FOUND_CODES.has(code)) {
6882
+ 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.` };
6883
+ }
6884
+ return { record, host, status: "unknown", message: `${who} record could not be checked just now. Try again in a few minutes.` };
6885
+ }
6886
+ }
6887
+ async function checkSendingDomain(config, rawDomain) {
6888
+ const domain = normalizeSendingDomain(rawDomain);
6889
+ if (!domain) return { domain: rawDomain, verified: false, records: [] };
6890
+ const records = await Promise.all(recordsFor(config.records, domain).map((record) => checkRecord(config.resolver, record, domain)));
6891
+ const required = records.filter((check) => check.record.required !== false);
6892
+ const verified = required.length > 0 && required.every((check) => check.status === "found");
6893
+ return { domain, verified, records };
6894
+ }
6895
+
6896
+ // src/handlers/admin-brand-domain-check.ts
6897
+ async function checkSendingDomainRoute(request, { host }) {
6898
+ try {
6899
+ const staff = await requireBrandAdmin(host, request, { action: "admin-brand-domain-check", tier: "SETTINGS" });
6900
+ if (staff instanceof Response) return staff;
6901
+ const check = host.brand?.checkSendingDomain;
6902
+ if (!check) return Response.json({ error: "Sending-domain checking is not set up on this server" }, { status: 501 });
6903
+ const domain = normalizeSendingDomain(new URL(request.url).searchParams.get("domain") ?? "");
6904
+ if (!domain) return Response.json({ error: "Enter a domain such as mail.acme.com" }, { status: 400 });
6905
+ return Response.json({ check: await check.call(host.brand, domain, staff.organizationId) });
6906
+ } catch (error) {
6907
+ return brandErrorResponse(error, "Failed to check the sending domain");
6908
+ }
6909
+ }
6910
+
6656
6911
  // src/handlers/admin-privacy.ts
6657
6912
  import { eraseSubject, exportSubject, listPrivacyRequests, previewErase } from "@ordinatio/scheduling";
6658
6913
 
6659
6914
  // src/privacy/privacy-http.ts
6660
- import { SchedulingValidationError as SchedulingValidationError12 } from "@ordinatio/scheduling";
6661
- var NOT_ENABLED4 = { error: "Data export and erasure are not enabled on this server" };
6915
+ import { SchedulingValidationError as SchedulingValidationError14 } from "@ordinatio/scheduling";
6916
+ var NOT_ENABLED6 = { error: "Data export and erasure are not enabled on this server" };
6662
6917
  var STATUS_BY_CODE3 = { SCHED_1300: 400, SCHED_1301: 409 };
6663
6918
  function privacyErrorResponse(error, fallback) {
6664
- if (error instanceof SchedulingValidationError12) {
6919
+ if (error instanceof SchedulingValidationError14) {
6665
6920
  return Response.json(
6666
6921
  { error: error.message, code: error.code, ref: getErrorRef(error), details: error.context },
6667
6922
  { status: STATUS_BY_CODE3[error.code] ?? 400 }
@@ -6673,7 +6928,7 @@ function privacyErrorResponse(error, fallback) {
6673
6928
  async function requirePrivacyAdmin(host, request, options) {
6674
6929
  const staff = await requireAdminStaff(host, request, options);
6675
6930
  if (staff instanceof Response) return staff;
6676
- if (!host.privacy) return Response.json(NOT_ENABLED4, { status: 501 });
6931
+ if (!host.privacy) return Response.json(NOT_ENABLED6, { status: 501 });
6677
6932
  return staff;
6678
6933
  }
6679
6934
 
@@ -7593,6 +7848,13 @@ var ROUTES = [
7593
7848
  { method: "GET", path: "/admin/brand", public: false, handler: getBrandAdminRoute },
7594
7849
  { method: "PUT", path: "/admin/brand", public: false, handler: saveBrandRoute },
7595
7850
  { method: "DELETE", path: "/admin/brand", public: false, handler: deleteBrandRoute },
7851
+ { method: "GET", path: "/admin/text-settings", public: false, handler: getTextSettingsRoute },
7852
+ { method: "PUT", path: "/admin/text-settings", public: false, handler: saveTextSettingsRoute },
7853
+ { method: "DELETE", path: "/admin/text-settings", public: false, handler: deleteTextSettingsRoute },
7854
+ { method: "GET", path: "/admin/api-keys", public: false, handler: listApiKeysRoute },
7855
+ { method: "POST", path: "/admin/api-keys", public: false, handler: createApiKeyRoute },
7856
+ { method: "DELETE", path: "/admin/api-keys/[id]", public: false, handler: revokeApiKeyRoute },
7857
+ { method: "GET", path: "/admin/brand/sending-domain", public: false, handler: checkSendingDomainRoute },
7596
7858
  { method: "POST", path: "/admin/privacy/export", public: false, handler: exportPrivacyRoute },
7597
7859
  { method: "POST", path: "/admin/privacy/erase", public: false, handler: erasePrivacyRoute },
7598
7860
  { method: "GET", path: "/admin/privacy/requests", public: false, handler: listPrivacyRequestsRoute },
@@ -7626,11 +7888,11 @@ var ROUTES = [
7626
7888
  { method: "POST", path: "/appointments/[id]/followup", public: false, handler: sendFollowup },
7627
7889
  { method: "POST", path: "/appointments/[id]/remind", public: false, handler: sendReminder },
7628
7890
  { method: "POST", path: "/appointments/[id]/cancel", public: false, handler: cancelByStaff },
7629
- { method: "GET", path: "/calendars/connect-google", public: false, handler: startGoogleConnection },
7630
- { method: "POST", path: "/calendars/connect-google", public: false, handler: setGoogleCalendar },
7631
- { method: "GET", path: "/calendars/connect-google/callback", public: false, handler: finishGoogleConnection },
7632
- { method: "GET", path: "/calendars/connect-outlook", public: false, handler: startOutlookConnection },
7633
- { method: "GET", path: "/calendars/connect-outlook/callback", public: false, handler: finishOutlookConnection },
7891
+ { method: "GET", path: "/calendars/connect-google", public: false, personOnly: true, handler: startGoogleConnection },
7892
+ { method: "POST", path: "/calendars/connect-google", public: false, personOnly: true, handler: setGoogleCalendar },
7893
+ { method: "GET", path: "/calendars/connect-google/callback", public: false, personOnly: true, handler: finishGoogleConnection },
7894
+ { method: "GET", path: "/calendars/connect-outlook", public: false, personOnly: true, handler: startOutlookConnection },
7895
+ { method: "GET", path: "/calendars/connect-outlook/callback", public: false, personOnly: true, handler: finishOutlookConnection },
7634
7896
  { method: "POST", path: "/appointments/[id]/cancel-sync", public: false, handler: cancelFromCalendarSync },
7635
7897
  { method: "POST", path: "/appointments/[id]/approve", public: false, handler: approveOrReject },
7636
7898
  { method: "POST", path: "/appointments/[id]/reschedule", public: false, handler: rescheduleByStaff },
@@ -7687,6 +7949,8 @@ function createSchedulingApi(config) {
7687
7949
  routingForms: config.host.routingForms ?? null,
7688
7950
  privacy: config.host.privacy ?? null,
7689
7951
  brand: config.host.brand ?? null,
7952
+ textMessages: config.host.textMessages ?? null,
7953
+ apiKeys: config.host.apiKeys ?? null,
7690
7954
  icalUidDomain: config.host.icalUidDomain?.bind(config.host) ?? (() => null),
7691
7955
  calendarSync: config.host.calendarSync ?? { upsertEvent: async () => ({}), removeEvent: async () => void 0 },
7692
7956
  activity: config.host.activity ?? { log: async () => void 0, isOpen: async () => false, resolve: async () => void 0 },
@@ -7714,24 +7978,34 @@ function createSchedulingApi(config) {
7714
7978
  cors: config.host.cors?.bind(config.host) ?? defaultCorsHeaders
7715
7979
  };
7716
7980
  host.events = withWebhooks(withWaitlist(config.host.events ?? { emit: async () => void 0 }, host), host);
7981
+ async function hostForRoute(route, request) {
7982
+ try {
7983
+ return await hostForRequest(host, request, route);
7984
+ } catch (error) {
7985
+ console.error("[scheduling-api] could not check the API key:", error);
7986
+ return Response.json({ error: "Internal error" }, { status: 500 });
7987
+ }
7988
+ }
7717
7989
  async function handle(request) {
7718
7990
  const { pathname } = new URL(request.url);
7719
7991
  if (pathname !== basePath && !pathname.startsWith(`${basePath}/`)) return notFound();
7720
7992
  const relative = pathname.slice(basePath.length) || "/";
7721
- const matches = routes.map((route) => ({ route, params: matchPath(route.path, relative) })).filter((match) => match.params !== null);
7722
- if (matches.length === 0) return notFound();
7993
+ const matches2 = routes.map((route) => ({ route, params: matchPath(route.path, relative) })).filter((match) => match.params !== null);
7994
+ if (matches2.length === 0) return notFound();
7723
7995
  const method = request.method.toUpperCase();
7724
- if (method === "OPTIONS" && matches.some((match) => match.route.public)) {
7996
+ if (method === "OPTIONS" && matches2.some((match) => match.route.public)) {
7725
7997
  return new Response(null, { status: 204, headers: host.cors(request) });
7726
7998
  }
7727
- const hit = matches.find((match) => match.route.method === method);
7999
+ const hit = matches2.find((match) => match.route.method === method);
7728
8000
  if (!hit) {
7729
- const allowed = [...new Set(matches.map((match) => match.route.method))];
7730
- if (matches.some((match) => match.route.public)) allowed.push("OPTIONS");
8001
+ const allowed = [...new Set(matches2.map((match) => match.route.method))];
8002
+ if (matches2.some((match) => match.route.public)) allowed.push("OPTIONS");
7731
8003
  return Response.json({ error: "Method not allowed" }, { status: 405, headers: { Allow: allowed.join(", ") } });
7732
8004
  }
7733
8005
  try {
7734
- return await hit.route.handler(request, { host, params: hit.params });
8006
+ const runHost = await hostForRoute(hit.route, request);
8007
+ if (runHost instanceof Response) return runHost;
8008
+ return await hit.route.handler(request, { host: runHost, params: hit.params });
7735
8009
  } catch (error) {
7736
8010
  console.error("[scheduling-api] unhandled error:", error);
7737
8011
  return Response.json({ error: "Internal error" }, { status: 500 });
@@ -7742,7 +8016,9 @@ function createSchedulingApi(config) {
7742
8016
  if (!route) throw new Error(`No route ${method} ${path}`);
7743
8017
  return async (request, context) => {
7744
8018
  const params = await context?.params ?? {};
7745
- return route.handler(request, { host, params });
8019
+ const runHost = await hostForRoute(route, request);
8020
+ if (runHost instanceof Response) return runHost;
8021
+ return route.handler(request, { host: runHost, params });
7746
8022
  };
7747
8023
  }
7748
8024
  return { routes, handle, handler };
@@ -7892,41 +8168,609 @@ function assertStripeTestKey(raw) {
7892
8168
  return key;
7893
8169
  }
7894
8170
 
7895
- // src/staff/simple-staff.ts
7896
- var DEFAULT_ADMIN_ROLES = ["OWNER", "ADMIN", "MANAGER"];
7897
- function createStaffContext(input) {
7898
- const adminRoles = (input.adminRoles ?? DEFAULT_ADMIN_ROLES).map((role) => role.toUpperCase());
7899
- const { db, organizationId } = input;
8171
+ // src/sending-domain/create-sending-domain-verifier.ts
8172
+ function createSendingDomainVerifier(config) {
8173
+ const check = (domain) => checkSendingDomain(config, domain);
7900
8174
  return {
7901
- userId: input.userId,
7902
- organizationId,
7903
- role: input.role,
7904
- isAdmin: adminRoles.includes(input.role.toUpperCase()),
7905
- schedulingEnabled: input.schedulingEnabled ?? true,
7906
- db,
7907
- visibleCalendars: async () => null,
7908
- visibleCalendarIds: async () => void 0,
7909
- canSeeCalendar: async (calendarId) => Boolean(await db.schedulingCalendar.findFirst({ where: { id: calendarId, organizationId }, select: { id: true } })),
7910
- canSeeAppointment: async (appointmentId) => Boolean(await db.appointment.findFirst({ where: { id: appointmentId, calendar: { organizationId } }, select: { id: true } })),
7911
- // The package has no client table, so there is no preference to read.
7912
- preferredLocationOf: async () => null
8175
+ isSendingDomainVerified: async (domain) => (await check(domain)).verified,
8176
+ check,
8177
+ instructions: (rawDomain) => {
8178
+ const domain = normalizeSendingDomain(rawDomain);
8179
+ return domain ? recordsFor(config.records, domain).map((record) => ({ record, host: recordHost(record, domain) })) : [];
8180
+ }
7913
8181
  };
7914
8182
  }
7915
- var BEARER = /^bearer\s+(\S+)$/i;
7916
- function createBearerStaffResolver(input) {
8183
+
8184
+ // src/sms/sms-common.ts
8185
+ var SmsSendError = class extends Error {
8186
+ constructor(message, retryable, outcomeUnknown, status, code) {
8187
+ super(message);
8188
+ this.retryable = retryable;
8189
+ this.outcomeUnknown = outcomeUnknown;
8190
+ this.status = status;
8191
+ this.code = code;
8192
+ this.name = "SmsSendError";
8193
+ }
8194
+ };
8195
+ function normalizePhoneNumber(raw) {
8196
+ const digits = raw.trim().replace(/[\s().-]/g, "");
8197
+ if (/^\+[1-9]\d{7,14}$/.test(digits)) return digits;
8198
+ if (/^\d{10}$/.test(digits)) return `+1${digits}`;
8199
+ if (/^1\d{10}$/.test(digits)) return `+${digits}`;
8200
+ return null;
8201
+ }
8202
+ function readHeader(headers, name) {
8203
+ if (typeof headers.get === "function") return headers.get(name) ?? void 0;
8204
+ const found = Object.entries(headers).find(([key]) => key.toLowerCase() === name);
8205
+ const value = found?.[1];
8206
+ return Array.isArray(value) ? value[0] : value;
8207
+ }
8208
+ var STOP_WORDS = ["STOP", "STOPALL", "UNSUBSCRIBE", "END", "QUIT"];
8209
+ var START_WORDS = ["START", "UNSTOP"];
8210
+ function classifyReply(text) {
8211
+ const word = text.trim().toUpperCase().replace(/[.!?,]+$/, "");
8212
+ return STOP_WORDS.includes(word) ? "opt-out" : START_WORDS.includes(word) ? "opt-in" : "reply";
8213
+ }
8214
+
8215
+ // src/telnyx/telnyx-sms.ts
8216
+ var TELNYX_MESSAGES_URL = "https://api.telnyx.com/v2/messages";
8217
+ var DEFAULT_TIMEOUT_MS = 1e4;
8218
+ var OPTED_OUT_CODE = "40300";
8219
+ function firstError(body) {
8220
+ const error = body?.errors?.[0];
8221
+ if (!error) return { text: "no detail given" };
8222
+ return { code: error.code === void 0 ? void 0 : String(error.code), text: error.detail ?? error.title ?? "no detail given" };
8223
+ }
8224
+ function createTelnyxSmsAdapter(config) {
8225
+ const apiKey = typeof config.apiKey === "string" ? config.apiKey.trim() : "";
8226
+ if (!apiKey) throw new Error("createTelnyxSmsAdapter needs an apiKey");
8227
+ const profileId = config.messagingProfileId?.trim() || void 0;
8228
+ const from = config.from ? normalizePhoneNumber(config.from) : null;
8229
+ if (config.from && !from) throw new Error('createTelnyxSmsAdapter: "from" must be a phone number such as +13135550100');
8230
+ if (!from && !profileId) throw new Error('createTelnyxSmsAdapter needs a sending number ("from"), a messagingProfileId, or both');
8231
+ const doFetch = config.fetch ?? fetch;
8232
+ const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
7917
8233
  return {
7918
- async resolve(request) {
7919
- const token = BEARER.exec(request.headers.get("authorization") ?? "")?.[1];
7920
- if (!token) return null;
7921
- const person = await input.authenticate(token, request);
7922
- if (!person) return null;
7923
- return createStaffContext({
7924
- ...person,
7925
- db: await input.db(person),
7926
- adminRoles: input.adminRoles,
7927
- schedulingEnabled: input.schedulingEnabled ? await input.schedulingEnabled(person) : void 0
8234
+ async send(message) {
8235
+ if (message.channel !== "SMS") return { status: "SKIPPED", reason: "The Telnyx adapter only sends text messages" };
8236
+ const to = normalizePhoneNumber(message.to);
8237
+ if (!to) return { status: "SKIPPED", reason: "The recipient is not a valid phone number" };
8238
+ if (!message.body.trim()) return { status: "SKIPPED", reason: "The message is empty" };
8239
+ const controller = new AbortController();
8240
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
8241
+ let response;
8242
+ let body;
8243
+ try {
8244
+ response = await doFetch(TELNYX_MESSAGES_URL, {
8245
+ method: "POST",
8246
+ headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
8247
+ body: JSON.stringify({
8248
+ to,
8249
+ text: message.body,
8250
+ type: "SMS",
8251
+ ...from ? { from } : {},
8252
+ ...profileId ? { messaging_profile_id: profileId } : {}
8253
+ }),
8254
+ signal: controller.signal
8255
+ });
8256
+ body = await response.json().catch((error) => {
8257
+ if (controller.signal.aborted) throw error;
8258
+ return null;
8259
+ });
8260
+ } catch (error) {
8261
+ const reason = controller.signal.aborted ? `timed out after ${timeoutMs} ms` : error instanceof Error ? error.message : String(error);
8262
+ throw new SmsSendError(`Telnyx could not be reached (${reason}); the message may or may not have been sent`, true, true);
8263
+ } finally {
8264
+ clearTimeout(timer);
8265
+ }
8266
+ if (response.ok) {
8267
+ const id = body?.data?.id;
8268
+ return id ? { status: "SENT", id } : { status: "SENT" };
8269
+ }
8270
+ const { code, text } = firstError(body);
8271
+ if (code === OPTED_OUT_CODE) return { status: "SKIPPED", reason: "The recipient opted out of text messages" };
8272
+ const serverFault = response.status >= 500;
8273
+ const retryable = response.status === 429 || serverFault;
8274
+ throw new SmsSendError(
8275
+ `Telnyx refused the message (HTTP ${response.status}${code ? `, code ${code}` : ""}): ${text}`,
8276
+ retryable,
8277
+ serverFault,
8278
+ response.status,
8279
+ code
8280
+ );
8281
+ }
8282
+ };
8283
+ }
8284
+
8285
+ // src/telnyx/telnyx-inbound.ts
8286
+ import { createPublicKey, verify } from "crypto";
8287
+ var ED25519_SPKI_PREFIX = Buffer.from("302a300506032b6570032100", "hex");
8288
+ var DEFAULT_TOLERANCE_SECONDS = 300;
8289
+ function verifyTelnyxSignature(rawBody, headers, options) {
8290
+ const signature = readHeader(headers, "telnyx-signature-ed25519");
8291
+ const timestamp = readHeader(headers, "telnyx-timestamp");
8292
+ if (!signature || !timestamp || !/^\d+$/.test(timestamp)) return false;
8293
+ const nowSeconds = Math.floor((options.now?.() ?? /* @__PURE__ */ new Date()).getTime() / 1e3);
8294
+ if (Math.abs(nowSeconds - Number(timestamp)) > (options.toleranceSeconds ?? DEFAULT_TOLERANCE_SECONDS)) return false;
8295
+ try {
8296
+ const raw = Buffer.from(options.publicKey.trim(), "base64");
8297
+ if (raw.length !== 32) return false;
8298
+ const key = createPublicKey({ key: Buffer.concat([ED25519_SPKI_PREFIX, raw]), format: "der", type: "spki" });
8299
+ return verify(null, Buffer.from(`${timestamp}|${rawBody}`), key, Buffer.from(signature, "base64"));
8300
+ } catch {
8301
+ return false;
8302
+ }
8303
+ }
8304
+ function handleTelnyxWebhook(rawBody, headers, options) {
8305
+ if (!verifyTelnyxSignature(rawBody, headers, options)) return { ok: false, status: 401, reason: "The signature is missing, wrong or too old" };
8306
+ let parsed;
8307
+ try {
8308
+ const value = JSON.parse(rawBody);
8309
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return { ok: false, status: 400, reason: "The body is not an event" };
8310
+ parsed = value;
8311
+ } catch {
8312
+ return { ok: false, status: 400, reason: "The body is not JSON" };
8313
+ }
8314
+ const eventType = parsed.data?.event_type ?? "";
8315
+ const payload = parsed.data?.payload;
8316
+ const id = payload?.id;
8317
+ const to = payload?.to?.[0]?.phone_number;
8318
+ if (eventType === "message.received") {
8319
+ const from = payload?.from?.phone_number;
8320
+ if (!id || !from || !to) return { ok: false, status: 400, reason: "The message is missing its id or phone numbers" };
8321
+ const text = typeof payload?.text === "string" ? payload.text : "";
8322
+ const type = classifyReply(text);
8323
+ return { ok: true, event: { type, id, from, to, text } };
8324
+ }
8325
+ if (eventType === "message.finalized" || eventType === "message.sent") {
8326
+ if (!id || !to) return { ok: false, status: 400, reason: "The delivery report is missing its id or number" };
8327
+ const status = payload?.to?.[0]?.status;
8328
+ if (eventType === "message.sent" || status !== "delivered" && status !== "delivery_failed" && status !== "sending_failed") {
8329
+ return { ok: true, event: { type: "ignored", eventType } };
8330
+ }
8331
+ const errorCode = payload?.errors?.[0]?.code;
8332
+ return {
8333
+ ok: true,
8334
+ event: { type: "delivery", id, to, status: status === "delivered" ? "delivered" : "failed", ...errorCode === void 0 ? {} : { errorCode: String(errorCode) } }
8335
+ };
8336
+ }
8337
+ return { ok: true, event: { type: "ignored", eventType } };
8338
+ }
8339
+
8340
+ // src/twilio/twilio-sms.ts
8341
+ var DEFAULT_TIMEOUT_MS2 = 1e4;
8342
+ var OPTED_OUT_CODE2 = "21610";
8343
+ function createTwilioSmsAdapter(config) {
8344
+ const accountSid = typeof config.accountSid === "string" ? config.accountSid.trim() : "";
8345
+ const authToken = typeof config.authToken === "string" ? config.authToken.trim() : "";
8346
+ if (!accountSid || !authToken) throw new Error("createTwilioSmsAdapter needs an accountSid and an authToken");
8347
+ const serviceSid = config.messagingServiceSid?.trim() || void 0;
8348
+ const from = config.from ? normalizePhoneNumber(config.from) : null;
8349
+ if (config.from && !from) throw new Error('createTwilioSmsAdapter: "from" must be a phone number such as +13135550100');
8350
+ if (!from && !serviceSid) throw new Error('createTwilioSmsAdapter needs a sending number ("from") or a messagingServiceSid');
8351
+ const doFetch = config.fetch ?? fetch;
8352
+ const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
8353
+ const url = `https://api.twilio.com/2010-04-01/Accounts/${encodeURIComponent(accountSid)}/Messages.json`;
8354
+ const authorization = `Basic ${Buffer.from(`${accountSid}:${authToken}`).toString("base64")}`;
8355
+ return {
8356
+ async send(message) {
8357
+ if (message.channel !== "SMS") return { status: "SKIPPED", reason: "The Twilio adapter only sends text messages" };
8358
+ const to = normalizePhoneNumber(message.to);
8359
+ if (!to) return { status: "SKIPPED", reason: "The recipient is not a valid phone number" };
8360
+ if (!message.body.trim()) return { status: "SKIPPED", reason: "The message is empty" };
8361
+ const form = new URLSearchParams({ To: to, Body: message.body });
8362
+ if (from) form.set("From", from);
8363
+ else if (serviceSid) form.set("MessagingServiceSid", serviceSid);
8364
+ const controller = new AbortController();
8365
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
8366
+ let response;
8367
+ let body;
8368
+ try {
8369
+ response = await doFetch(url, {
8370
+ method: "POST",
8371
+ headers: { Authorization: authorization, "Content-Type": "application/x-www-form-urlencoded" },
8372
+ body: form.toString(),
8373
+ signal: controller.signal
8374
+ });
8375
+ body = await response.json().catch((error2) => {
8376
+ if (controller.signal.aborted) throw error2;
8377
+ return null;
8378
+ });
8379
+ } catch (error2) {
8380
+ const reason = controller.signal.aborted ? `timed out after ${timeoutMs} ms` : error2 instanceof Error ? error2.message : String(error2);
8381
+ throw new SmsSendError(`Twilio could not be reached (${reason}); the message may or may not have been sent`, true, true);
8382
+ } finally {
8383
+ clearTimeout(timer);
8384
+ }
8385
+ if (response.ok) {
8386
+ const id = body?.sid;
8387
+ return id ? { status: "SENT", id } : { status: "SENT" };
8388
+ }
8389
+ const error = body ?? {};
8390
+ const code = error.code === void 0 ? void 0 : String(error.code);
8391
+ if (code === OPTED_OUT_CODE2) return { status: "SKIPPED", reason: "The recipient opted out of text messages" };
8392
+ const serverFault = response.status >= 500;
8393
+ throw new SmsSendError(
8394
+ `Twilio refused the message (HTTP ${response.status}${code ? `, code ${code}` : ""}): ${error.message ?? "no detail given"}`,
8395
+ response.status === 429 || serverFault,
8396
+ serverFault,
8397
+ response.status,
8398
+ code
8399
+ );
8400
+ }
8401
+ };
8402
+ }
8403
+
8404
+ // src/twilio/twilio-inbound.ts
8405
+ import { createHmac, timingSafeEqual } from "crypto";
8406
+ function expectedSignature(params, options) {
8407
+ const keys = [...new Set(params.keys())].sort();
8408
+ const signed = keys.reduce((text, key) => text + key + params.getAll(key).join(""), options.url);
8409
+ return createHmac("sha1", options.authToken.trim()).update(signed).digest("base64");
8410
+ }
8411
+ function verifyTwilioSignature(rawBody, headers, options) {
8412
+ const given = readHeader(headers, "x-twilio-signature");
8413
+ if (!given || !options.authToken.trim()) return false;
8414
+ const expected = Buffer.from(expectedSignature(new URLSearchParams(rawBody), options));
8415
+ const actual = Buffer.from(given);
8416
+ return expected.length === actual.length && timingSafeEqual(expected, actual);
8417
+ }
8418
+ function handleTwilioWebhook(rawBody, headers, options) {
8419
+ if (!verifyTwilioSignature(rawBody, headers, options)) return { ok: false, status: 401, reason: "The signature is missing or wrong" };
8420
+ const params = new URLSearchParams(rawBody);
8421
+ const id = params.get("MessageSid") ?? params.get("SmsSid");
8422
+ const from = params.get("From");
8423
+ const to = params.get("To");
8424
+ if (params.has("MessageStatus") && !params.has("Body")) {
8425
+ const status = params.get("MessageStatus") ?? "";
8426
+ if (!id || !to) return { ok: false, status: 400, reason: "The status report is missing its id or number" };
8427
+ if (status !== "delivered" && status !== "undelivered" && status !== "failed") return { ok: true, event: { type: "ignored", eventType: `status.${status}` } };
8428
+ const errorCode = params.get("ErrorCode");
8429
+ return { ok: true, event: { type: "delivery", id, to, status: status === "delivered" ? "delivered" : "failed", ...errorCode ? { errorCode } : {} } };
8430
+ }
8431
+ if (params.has("Body")) {
8432
+ if (!id || !from || !to) return { ok: false, status: 400, reason: "The message is missing its id or phone numbers" };
8433
+ const text = params.get("Body") ?? "";
8434
+ return { ok: true, event: { type: classifyReply(text), id, from, to, text } };
8435
+ }
8436
+ return { ok: true, event: { type: "ignored", eventType: "unknown" } };
8437
+ }
8438
+
8439
+ // src/sms/per-business-sms.ts
8440
+ var DEFAULT_ADAPTER_TTL_MS = 5 * 6e4;
8441
+ var DEFAULT_NO_NUMBER_TTL_MS = 6e4;
8442
+ function createPerBusinessSmsAdapter(options) {
8443
+ const adapterTtl = options.adapterTtlMs ?? DEFAULT_ADAPTER_TTL_MS;
8444
+ const noNumberTtl = options.noNumberTtlMs ?? DEFAULT_NO_NUMBER_TTL_MS;
8445
+ const now = options.now ?? Date.now;
8446
+ const kept = /* @__PURE__ */ new Map();
8447
+ function adapterFor(organizationId) {
8448
+ const existing = kept.get(organizationId);
8449
+ if (existing && (existing.expiresAt === null || existing.expiresAt > now())) return existing.lookup;
8450
+ const entry = { lookup: Promise.resolve(options.resolve(organizationId)), expiresAt: null };
8451
+ kept.set(organizationId, entry);
8452
+ entry.lookup.then(
8453
+ (adapter) => {
8454
+ entry.expiresAt = now() + (adapter ? adapterTtl : noNumberTtl);
8455
+ },
8456
+ // A failed lookup is not kept; only this entry is removed, not a newer one.
8457
+ () => {
8458
+ if (kept.get(organizationId) === entry) kept.delete(organizationId);
8459
+ }
8460
+ );
8461
+ return entry.lookup;
8462
+ }
8463
+ return {
8464
+ async send(message) {
8465
+ if (message.channel !== "SMS") return { status: "SKIPPED", reason: "This adapter only sends text messages" };
8466
+ if (!message.organizationId) {
8467
+ return { status: "SKIPPED", reason: "The message names no business, so there is no number to send from (run the sender with organization: true)" };
8468
+ }
8469
+ const adapter = await adapterFor(message.organizationId);
8470
+ if (!adapter) return { status: "SKIPPED", reason: "This business has no text-message number set up" };
8471
+ return adapter.send(message);
8472
+ },
8473
+ forget(organizationId) {
8474
+ kept.delete(organizationId);
8475
+ }
8476
+ };
8477
+ }
8478
+
8479
+ // src/sms/text-settings-resolver.ts
8480
+ import { getTextSettings as getTextSettings2 } from "@ordinatio/scheduling";
8481
+ function createTextSettingsResolver(options) {
8482
+ return async (organizationId) => {
8483
+ const settings = await getTextSettings2(await options.db(organizationId), organizationId);
8484
+ if (!settings || !settings.enabled) return null;
8485
+ try {
8486
+ if (settings.provider === "TELNYX" && options.telnyx?.apiKey?.trim()) {
8487
+ return createTelnyxSmsAdapter({ ...options.telnyx, from: settings.fromNumber, fetch: options.fetch });
8488
+ }
8489
+ if (settings.provider === "TWILIO" && options.twilio?.accountSid?.trim() && options.twilio.authToken?.trim()) {
8490
+ return createTwilioSmsAdapter({ ...options.twilio, from: settings.fromNumber, fetch: options.fetch });
8491
+ }
8492
+ } catch (error) {
8493
+ console.error(`[text-settings] could not build the ${settings.provider} sender for organization ${organizationId}:`, error instanceof Error ? error.message : error);
8494
+ return null;
8495
+ }
8496
+ if (settings.provider === "TELNYX" || settings.provider === "TWILIO") {
8497
+ console.error(`[text-settings] organization ${organizationId} chose ${settings.provider}, but this server has no usable ${settings.provider} account`);
8498
+ }
8499
+ return null;
8500
+ };
8501
+ }
8502
+
8503
+ // src/outlook-sync/outlook-config.ts
8504
+ var BLOCKED_TYPE_SLUG = "blocked";
8505
+ var GRAPH_BASE = "https://graph.microsoft.com/v1.0";
8506
+ var MICROSOFT_TOKEN_ENDPOINT = "https://login.microsoftonline.com/common/oauth2/v2.0/token";
8507
+ var OUTLOOK_CALENDAR_SCOPE = "https://graph.microsoft.com/Calendars.ReadWrite offline_access";
8508
+ function problem(config, message, context) {
8509
+ config.onProblem?.(message, context);
8510
+ }
8511
+
8512
+ // src/outlook-sync/outlook-access-token.ts
8513
+ var REFRESH_MARGIN_MS = 5 * 60 * 1e3;
8514
+ async function getOutlookAccessToken(config, calendarId) {
8515
+ const calendar = await config.db.schedulingCalendar.findUnique({
8516
+ where: { id: calendarId },
8517
+ select: {
8518
+ outlookCalendarId: true,
8519
+ outlookAccessToken: true,
8520
+ outlookRefreshToken: true,
8521
+ outlookTokenExpiresAt: true
8522
+ }
8523
+ });
8524
+ if (!calendar?.outlookCalendarId || !calendar.outlookRefreshToken) return null;
8525
+ const now = (config.now ?? (() => /* @__PURE__ */ new Date()))();
8526
+ const stillValid = calendar.outlookAccessToken && calendar.outlookTokenExpiresAt && calendar.outlookTokenExpiresAt.getTime() - now.getTime() >= REFRESH_MARGIN_MS;
8527
+ if (stillValid) return calendar.outlookAccessToken;
8528
+ try {
8529
+ const response = await (config.fetch ?? fetch)(MICROSOFT_TOKEN_ENDPOINT, {
8530
+ method: "POST",
8531
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
8532
+ body: new URLSearchParams({
8533
+ client_id: config.clientId.trim(),
8534
+ client_secret: config.clientSecret.trim(),
8535
+ refresh_token: calendar.outlookRefreshToken,
8536
+ grant_type: "refresh_token",
8537
+ scope: OUTLOOK_CALENDAR_SCOPE
8538
+ })
8539
+ });
8540
+ if (!response.ok) throw new Error(`Token refresh HTTP ${response.status}`);
8541
+ const data = await response.json();
8542
+ if (!data.access_token || typeof data.expires_in !== "number") throw new Error("Token refresh answered without a token");
8543
+ await config.db.schedulingCalendar.update({
8544
+ where: { id: calendarId },
8545
+ data: {
8546
+ outlookAccessToken: data.access_token,
8547
+ outlookRefreshToken: data.refresh_token ?? calendar.outlookRefreshToken,
8548
+ outlookTokenExpiresAt: new Date(now.getTime() + data.expires_in * 1e3)
8549
+ }
8550
+ });
8551
+ return data.access_token;
8552
+ } catch (error) {
8553
+ problem(config, "Outlook token refresh failed; the calendar must be reconnected", {
8554
+ calendarId,
8555
+ error: error instanceof Error ? error.message : String(error)
8556
+ });
8557
+ return null;
8558
+ }
8559
+ }
8560
+
8561
+ // src/outlook-sync/outlook-push.ts
8562
+ async function pushAppointmentToOutlook(config, appointmentId) {
8563
+ const appointment = await config.db.appointment.findUnique({
8564
+ where: { id: appointmentId },
8565
+ include: {
8566
+ type: { select: { name: true, slug: true } },
8567
+ calendar: { select: { id: true, outlookCalendarId: true } }
8568
+ }
8569
+ });
8570
+ if (!appointment?.calendar.outlookCalendarId) return null;
8571
+ if (appointment.type.slug === BLOCKED_TYPE_SLUG) return null;
8572
+ const accessToken = await getOutlookAccessToken(config, appointment.calendarId);
8573
+ if (!accessToken) return null;
8574
+ const body = {
8575
+ subject: `${appointment.type.name} \u2014 ${appointment.clientName}`,
8576
+ body: {
8577
+ contentType: "text",
8578
+ content: [
8579
+ `Service: ${appointment.type.name}`,
8580
+ `Duration: ${appointment.duration} min`,
8581
+ appointment.clientPhone ? `Phone: ${appointment.clientPhone}` : "",
8582
+ appointment.clientEmail ? `Email: ${appointment.clientEmail}` : ""
8583
+ ].filter(Boolean).join("\n")
8584
+ },
8585
+ // UTC on both sides so the event lands at the stored instant whatever zone the Outlook calendar uses.
8586
+ start: { dateTime: appointment.startTime.toISOString(), timeZone: "UTC" },
8587
+ end: { dateTime: appointment.endTime.toISOString(), timeZone: "UTC" }
8588
+ };
8589
+ const calendarUrl = `${GRAPH_BASE}/me/calendars/${encodeURIComponent(appointment.calendar.outlookCalendarId)}/events`;
8590
+ const isUpdate = Boolean(appointment.outlookEventId);
8591
+ const method = isUpdate ? "PATCH" : "POST";
8592
+ const url = isUpdate ? `${calendarUrl}/${encodeURIComponent(appointment.outlookEventId)}` : calendarUrl;
8593
+ const response = await (config.fetch ?? fetch)(url, {
8594
+ method,
8595
+ headers: { Authorization: `Bearer ${accessToken}`, "Content-Type": "application/json" },
8596
+ body: JSON.stringify(body)
8597
+ });
8598
+ if (!response.ok) throw new Error(`Outlook ${method} event failed with HTTP ${response.status}`);
8599
+ const created = await response.json();
8600
+ if (!isUpdate && created.id) {
8601
+ try {
8602
+ await config.db.appointment.update({ where: { id: appointmentId }, data: { outlookEventId: created.id } });
8603
+ } catch (error) {
8604
+ const removed = await (config.fetch ?? fetch)(`${calendarUrl}/${encodeURIComponent(created.id)}`, {
8605
+ method: "DELETE",
8606
+ headers: { Authorization: `Bearer ${accessToken}` }
8607
+ }).then((r) => r.ok || r.status === 404, () => false);
8608
+ if (!removed) problem(config, "An Outlook event was created but its id could not be saved or the event removed", { appointmentId });
8609
+ throw error;
8610
+ }
8611
+ }
8612
+ return created.id ?? appointment.outlookEventId ?? null;
8613
+ }
8614
+ async function deleteOutlookEvent(config, appointmentId) {
8615
+ const appointment = await config.db.appointment.findUnique({
8616
+ where: { id: appointmentId },
8617
+ select: { outlookEventId: true, calendarId: true, calendar: { select: { outlookCalendarId: true } }, type: { select: { slug: true } } }
8618
+ });
8619
+ if (!appointment?.outlookEventId || !appointment.calendar.outlookCalendarId) return;
8620
+ if (appointment.type.slug === BLOCKED_TYPE_SLUG) return;
8621
+ const accessToken = await getOutlookAccessToken(config, appointment.calendarId);
8622
+ if (!accessToken) return;
8623
+ const response = await (config.fetch ?? fetch)(
8624
+ `${GRAPH_BASE}/me/calendars/${encodeURIComponent(appointment.calendar.outlookCalendarId)}/events/${encodeURIComponent(appointment.outlookEventId)}`,
8625
+ { method: "DELETE", headers: { Authorization: `Bearer ${accessToken}` } }
8626
+ );
8627
+ if (!response.ok && response.status !== 404) throw new Error(`Outlook DELETE event failed with HTTP ${response.status}`);
8628
+ await config.db.appointment.update({ where: { id: appointmentId }, data: { outlookEventId: null } });
8629
+ }
8630
+
8631
+ // src/outlook-sync/outlook-pull.ts
8632
+ var MAX_PAGES = 200;
8633
+ var withZone = (dateTime) => dateTime.endsWith("Z") ? dateTime : `${dateTime}Z`;
8634
+ async function pullChangesFromOutlook(config, hooks, calendarId) {
8635
+ return pullOnce(config, hooks, calendarId, { isRestart: false, skipWindowCheck: false });
8636
+ }
8637
+ async function pullOnce(config, hooks, calendarId, mode) {
8638
+ const { isRestart } = mode;
8639
+ const { db } = config;
8640
+ const calendar = await db.schedulingCalendar.findUnique({ where: { id: calendarId } });
8641
+ if (!calendar?.outlookCalendarId) return { synced: 0 };
8642
+ const now = (config.now ?? (() => /* @__PURE__ */ new Date()))();
8643
+ const windowIsStale = calendar.lastSyncAt != null && calendar.lastSyncAt.getUTCMonth() !== now.getUTCMonth();
8644
+ if (calendar.outlookSyncToken && windowIsStale && !isRestart && !mode.skipWindowCheck) {
8645
+ if (!await getOutlookAccessToken(config, calendarId)) return { synced: 0 };
8646
+ const drained = await pullOnce(config, hooks, calendarId, { isRestart: false, skipWindowCheck: true });
8647
+ const fresh = await pullOnce(config, hooks, calendarId, { isRestart: true, skipWindowCheck: true, ignoreSavedLink: true });
8648
+ return { synced: drained.synced + fresh.synced };
8649
+ }
8650
+ const accessToken = await getOutlookAccessToken(config, calendarId);
8651
+ if (!accessToken) return { synced: 0 };
8652
+ const headers = { Authorization: `Bearer ${accessToken}`, Prefer: 'outlook.timezone="UTC"' };
8653
+ const horizon = new Date(now);
8654
+ horizon.setUTCFullYear(horizon.getUTCFullYear() + 1);
8655
+ const firstUrl = `${GRAPH_BASE}/me/calendars/${encodeURIComponent(calendar.outlookCalendarId)}/calendarView/delta?startDateTime=${now.toISOString()}&endDateTime=${horizon.toISOString()}`;
8656
+ let url = mode.ignoreSavedLink ? firstUrl : calendar.outlookSyncToken ?? firstUrl;
8657
+ let deltaLink = null;
8658
+ let synced = 0;
8659
+ let unhandled = null;
8660
+ let blockedType = null;
8661
+ for (let pageNumber = 0; url; pageNumber++) {
8662
+ if (pageNumber >= MAX_PAGES) throw new Error("Outlook delta query returned more pages than expected");
8663
+ if (!url.startsWith(`${GRAPH_BASE}/`)) throw new Error("Outlook delta link does not point at Microsoft Graph");
8664
+ const response = await (config.fetch ?? fetch)(url, { headers });
8665
+ if (response.status === 410) {
8666
+ if (isRestart) throw new Error("Outlook delta query was refused with HTTP 410 on a fresh start");
8667
+ problem(config, "Outlook delta link expired; starting a full sync", { calendarId });
8668
+ await db.schedulingCalendar.update({ where: { id: calendarId }, data: { outlookSyncToken: null } });
8669
+ return pullOnce(config, hooks, calendarId, { isRestart: true, skipWindowCheck: true });
8670
+ }
8671
+ if (!response.ok) throw new Error(`Outlook delta query failed with HTTP ${response.status}`);
8672
+ const page = await response.json();
8673
+ for (const event of page.value) {
8674
+ if (!event.id) continue;
8675
+ const existing = await db.appointment.findFirst({ where: { outlookEventId: event.id, calendarId } });
8676
+ if (event["@removed"]) {
8677
+ if (existing && existing.status !== "CANCELLED") {
8678
+ try {
8679
+ if (await hooks.cancelAppointment(existing.id)) synced++;
8680
+ else unhandled ??= new Error(`The host did not cancel appointment ${existing.id}`);
8681
+ } catch (error) {
8682
+ unhandled ??= error instanceof Error ? error : new Error(String(error));
8683
+ problem(config, "Cancelling an appointment deleted in Outlook failed", { appointmentId: existing.id, error: unhandled.message });
8684
+ }
8685
+ }
8686
+ continue;
8687
+ }
8688
+ if (!event.start?.dateTime || !event.end?.dateTime) continue;
8689
+ const startTime = new Date(withZone(event.start.dateTime));
8690
+ const endTime = new Date(withZone(event.end.dateTime));
8691
+ if (Number.isNaN(startTime.getTime()) || Number.isNaN(endTime.getTime()) || endTime <= startTime) continue;
8692
+ const duration = Math.round((endTime.getTime() - startTime.getTime()) / 6e4);
8693
+ if (existing) {
8694
+ if (existing.status === "CANCELLED") continue;
8695
+ const moved = existing.startTime.getTime() !== startTime.getTime() || existing.endTime.getTime() !== endTime.getTime();
8696
+ if (!moved) continue;
8697
+ try {
8698
+ await hooks.onAppointmentMoved?.({ appointmentId: existing.id, organizationId: calendar.organizationId, startTime, endTime });
8699
+ await db.appointment.update({ where: { id: existing.id }, data: { startTime, endTime, duration } });
8700
+ } catch (error) {
8701
+ unhandled ??= error instanceof Error ? error : new Error(String(error));
8702
+ problem(config, "Saving a time changed in Outlook failed", { appointmentId: existing.id, error: unhandled.message });
8703
+ continue;
8704
+ }
8705
+ synced++;
8706
+ continue;
8707
+ }
8708
+ blockedType ??= await findOrCreateBlockedType(config, calendar.organizationId);
8709
+ await db.appointment.create({
8710
+ data: {
8711
+ calendarId,
8712
+ typeId: blockedType.id,
8713
+ startTime,
8714
+ endTime,
8715
+ duration,
8716
+ timezone: calendar.timezone,
8717
+ status: "CONFIRMED",
8718
+ clientName: event.subject || "Blocked",
8719
+ clientEmail: "",
8720
+ outlookEventId: event.id
8721
+ }
7928
8722
  });
8723
+ synced++;
7929
8724
  }
8725
+ deltaLink = page["@odata.deltaLink"] ?? null;
8726
+ url = page["@odata.nextLink"] ?? "";
8727
+ }
8728
+ if (unhandled) throw unhandled;
8729
+ if (deltaLink) {
8730
+ const isDrain = mode.skipWindowCheck && !isRestart;
8731
+ await db.schedulingCalendar.update({
8732
+ where: { id: calendarId },
8733
+ data: isDrain ? { outlookSyncToken: deltaLink } : { outlookSyncToken: deltaLink, lastSyncAt: now }
8734
+ });
8735
+ }
8736
+ return { synced };
8737
+ }
8738
+ async function findOrCreateBlockedType(config, organizationId) {
8739
+ const find = () => config.db.appointmentType.findFirst({ where: { slug: BLOCKED_TYPE_SLUG, organizationId } });
8740
+ const found = await find();
8741
+ if (found) return found;
8742
+ try {
8743
+ return await config.db.appointmentType.create({
8744
+ data: {
8745
+ name: "Blocked",
8746
+ slug: BLOCKED_TYPE_SLUG,
8747
+ duration: 60,
8748
+ color: "#6B7280",
8749
+ isActive: false,
8750
+ // never offered for booking
8751
+ organizationId
8752
+ }
8753
+ });
8754
+ } catch (error) {
8755
+ const raced = await find();
8756
+ if (raced) return raced;
8757
+ throw error;
8758
+ }
8759
+ }
8760
+
8761
+ // src/outlook-sync/create-outlook-calendar-sync.ts
8762
+ function createOutlookCalendarSync(config, hooks) {
8763
+ return {
8764
+ adapter: {
8765
+ async upsertEvent(event) {
8766
+ const externalId = await pushAppointmentToOutlook(config, event.appointmentId);
8767
+ return externalId ? { externalId } : {};
8768
+ },
8769
+ async removeEvent(ref) {
8770
+ await deleteOutlookEvent(config, ref.appointmentId);
8771
+ }
8772
+ },
8773
+ pull: async (calendarId) => await pullChangesFromOutlook(config, hooks, calendarId)
7930
8774
  };
7931
8775
  }
7932
8776
 
@@ -8044,6 +8888,7 @@ function createNodeListener(api, options) {
8044
8888
  }
8045
8889
  export {
8046
8890
  ALL_REFUND_STATUSES,
8891
+ ApiKeySchema,
8047
8892
  BALANCE_APPOINTMENT_SELECT,
8048
8893
  BALANCE_BLOCKED_APPOINTMENT_STATUS,
8049
8894
  BALANCE_REQUIRED_PAYMENT_STATUS,
@@ -8080,9 +8925,12 @@ export {
8080
8925
  RouteClientSchema,
8081
8926
  SLOT_GRANULARITY_DEFAULT,
8082
8927
  SLOT_GRANULARITY_OPTIONS,
8928
+ SmsSendError,
8083
8929
  TERMINAL_SUCCESS_STATUSES,
8084
8930
  TOKEN_TTL_DAYS,
8931
+ SmsSendError as TelnyxSendError,
8085
8932
  TestRoutingFormSchema,
8933
+ TextSettingsSchema,
8086
8934
  UnverifiedPaymentError,
8087
8935
  UpdateAppointmentCategorySchema,
8088
8936
  UpdateAppointmentTypeSchema,
@@ -8095,9 +8943,12 @@ export {
8095
8943
  UpdateServicePackageSchema,
8096
8944
  assertStripeTestKey,
8097
8945
  attemptLegRefund,
8946
+ bearerKeyOf,
8098
8947
  calendarVisibilityFilter,
8099
8948
  canSeeAppointmentInScope,
8100
8949
  canSeeCalendarInScope,
8950
+ checkSendingDomain,
8951
+ classifyReply,
8101
8952
  createBalanceIntent,
8102
8953
  createBearerStaffResolver,
8103
8954
  createMemoryAvailabilityCache,
@@ -8106,25 +8957,37 @@ export {
8106
8957
  createNoBalancePaymentControl,
8107
8958
  createNoPaymentAdapter,
8108
8959
  createNodeListener,
8960
+ createOutlookCalendarSync,
8961
+ createPerBusinessSmsAdapter,
8109
8962
  createSchedulingApi,
8110
8963
  createScopedVisibility,
8964
+ createSendingDomainVerifier,
8111
8965
  createSingleOrganizationDirectory,
8112
8966
  createSingleOrganizationResolver,
8113
8967
  createStaffContext,
8114
8968
  createStripePaymentAdapter,
8969
+ createTelnyxSmsAdapter,
8970
+ createTextSettingsResolver,
8971
+ createTwilioSmsAdapter,
8115
8972
  decimalToCents,
8116
8973
  defaultCorsHeaders,
8117
8974
  getErrorCode,
8118
8975
  getErrorMessage,
8119
8976
  getErrorRef,
8977
+ handleTelnyxWebhook,
8978
+ handleTwilioWebhook,
8120
8979
  isCalendarVisibleInScope,
8121
8980
  isSchedulingServiceError,
8122
8981
  isSupportedCurrency,
8123
8982
  isTokenExpired,
8983
+ normalizePhoneNumber,
8984
+ normalizeSendingDomain,
8124
8985
  parsePagination,
8125
8986
  persistRefundOutcome,
8126
8987
  recordBalanceIntent,
8127
8988
  runCalendarRemoveWithoutBlocking,
8128
8989
  runCalendarSyncWithoutBlocking,
8990
+ verifyTelnyxSignature,
8991
+ verifyTwilioSignature,
8129
8992
  visibleCalendarIdsInScope
8130
8993
  };