@ordinatio/scheduling-api 0.5.1 → 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/CHANGELOG.md +18 -0
- package/README.md +89 -1
- package/dist/agent/index.d.mts +1 -1
- package/dist/agent/index.d.ts +1 -1
- package/dist/agent/index.js +77 -0
- package/dist/agent/index.mjs +77 -0
- package/dist/{chunk-WZ5KO7IW.mjs → chunk-IW6AN5WE.mjs} +10 -1
- package/dist/index.d.mts +308 -5
- package/dist/index.d.ts +308 -5
- package/dist/index.js +1095 -90
- package/dist/index.mjs +998 -26
- package/dist/{routes-CM-ezlv2.d.mts → routes-LaFljBCF.d.mts} +61 -2
- package/dist/{routes-CM-ezlv2.d.ts → routes-LaFljBCF.d.ts} +61 -2
- package/dist/schemas/index.d.mts +7 -1
- package/dist/schemas/index.d.ts +7 -1
- package/dist/schemas/index.js +10 -0
- package/dist/schemas/index.mjs +3 -1
- package/package.json +4 -3
package/dist/index.mjs
CHANGED
|
@@ -28,6 +28,7 @@ import {
|
|
|
28
28
|
SLOT_GRANULARITY_DEFAULT,
|
|
29
29
|
SLOT_GRANULARITY_OPTIONS,
|
|
30
30
|
TestRoutingFormSchema,
|
|
31
|
+
TextSettingsSchema,
|
|
31
32
|
UpdateAppointmentCategorySchema,
|
|
32
33
|
UpdateAppointmentTypeSchema,
|
|
33
34
|
UpdateBookingPageSchema,
|
|
@@ -37,7 +38,7 @@ import {
|
|
|
37
38
|
UpdatePackagePurchaseSchema,
|
|
38
39
|
UpdateRoutingFormSchema,
|
|
39
40
|
UpdateServicePackageSchema
|
|
40
|
-
} from "./chunk-
|
|
41
|
+
} from "./chunk-IW6AN5WE.mjs";
|
|
41
42
|
|
|
42
43
|
// src/create-api.ts
|
|
43
44
|
import * as engine from "@ordinatio/scheduling";
|
|
@@ -1714,9 +1715,9 @@ function invalid(error) {
|
|
|
1714
1715
|
details: error.issues.map((e) => ({ field: e.path.join("."), message: e.message }))
|
|
1715
1716
|
}, { status: 400 });
|
|
1716
1717
|
}
|
|
1717
|
-
function failure(
|
|
1718
|
+
function failure(label2, error, fallback) {
|
|
1718
1719
|
const ref = getErrorRef(error);
|
|
1719
|
-
console.error(`[${
|
|
1720
|
+
console.error(`[${label2}]`, ref, error instanceof Error ? error.message : error);
|
|
1720
1721
|
return Response.json({ error: getErrorMessage(error, fallback), ...ref && { ref } }, { status: 500 });
|
|
1721
1722
|
}
|
|
1722
1723
|
async function updateLocation(request, { host, params }) {
|
|
@@ -2472,16 +2473,16 @@ async function attemptLegRefund(payments, paymentIntentId, idempotencyKeySuffix,
|
|
|
2472
2473
|
return failedLeg(errorCode, logLabel, appointmentId, paymentIntentId, idempotencyKey, retriedAfterReplay, { error: result.error, message: result.error ?? result.code ?? "no reason given", requestId: result.requestId });
|
|
2473
2474
|
}
|
|
2474
2475
|
}
|
|
2475
|
-
function failedLeg(errorCode, logLabel, appointmentId, paymentIntentId, idempotencyKey, retriedAfterReplay,
|
|
2476
|
-
const diagnostic = schedError14(errorCode, { error:
|
|
2476
|
+
function failedLeg(errorCode, logLabel, appointmentId, paymentIntentId, idempotencyKey, retriedAfterReplay, failure4) {
|
|
2477
|
+
const diagnostic = schedError14(errorCode, { error: failure4.error, appointmentId, paymentIntentId });
|
|
2477
2478
|
console.error(
|
|
2478
2479
|
`[resolve-refund] ${logLabel} refund failed${retriedAfterReplay ? " (after a fresh-key re-attempt)" : ""} \u2014 manual refund may be required:`,
|
|
2479
2480
|
diagnostic.ref,
|
|
2480
2481
|
appointmentId,
|
|
2481
2482
|
paymentIntentId,
|
|
2482
|
-
`requestId=${
|
|
2483
|
+
`requestId=${failure4.requestId}`,
|
|
2483
2484
|
`idempotencyKey=${idempotencyKey}`,
|
|
2484
|
-
|
|
2485
|
+
failure4.message
|
|
2485
2486
|
);
|
|
2486
2487
|
return { succeeded: false, amountCents: null };
|
|
2487
2488
|
}
|
|
@@ -3472,24 +3473,24 @@ import { scheduleNotifications as scheduleNotifications4, queueStaffNotification
|
|
|
3472
3473
|
// src/recurring/failure-collector.ts
|
|
3473
3474
|
function createFailureCollector() {
|
|
3474
3475
|
const problems = /* @__PURE__ */ new Map();
|
|
3475
|
-
const record = (
|
|
3476
|
+
const record = (label2, error) => {
|
|
3476
3477
|
const message = error instanceof Error ? error.message : String(error);
|
|
3477
|
-
const key = `${
|
|
3478
|
+
const key = `${label2}\0${message}`;
|
|
3478
3479
|
const known = problems.get(key);
|
|
3479
3480
|
if (known) known.count += 1;
|
|
3480
|
-
else problems.set(key, { label, message, count: 1 });
|
|
3481
|
+
else problems.set(key, { label: label2, message, count: 1 });
|
|
3481
3482
|
};
|
|
3482
|
-
const attempt = async (
|
|
3483
|
+
const attempt = async (label2, work) => {
|
|
3483
3484
|
try {
|
|
3484
3485
|
await work();
|
|
3485
3486
|
return true;
|
|
3486
3487
|
} catch (error) {
|
|
3487
|
-
record(
|
|
3488
|
+
record(label2, error);
|
|
3488
3489
|
return false;
|
|
3489
3490
|
}
|
|
3490
3491
|
};
|
|
3491
3492
|
const lines = () => [...problems.values()].map(
|
|
3492
|
-
({ label, message, count }) => count === 1 ? `${
|
|
3493
|
+
({ label: label2, message, count }) => count === 1 ? `${label2} failed: ${message}` : `${label2} failed for ${count} visits: ${message}`
|
|
3493
3494
|
);
|
|
3494
3495
|
return { record, attempt, lines };
|
|
3495
3496
|
}
|
|
@@ -4039,9 +4040,9 @@ async function businessName(host, db, organizationId) {
|
|
|
4039
4040
|
|
|
4040
4041
|
// src/handlers/appointment-messages.ts
|
|
4041
4042
|
var NOT_FOUND4 = () => Response.json({ error: "Appointment not found" }, { status: 404 });
|
|
4042
|
-
function failure2(
|
|
4043
|
+
function failure2(label2, error, fallback) {
|
|
4043
4044
|
const ref = getErrorRef(error);
|
|
4044
|
-
console.error(`[${
|
|
4045
|
+
console.error(`[${label2}]`, ref, error instanceof Error ? error.message : error);
|
|
4045
4046
|
return Response.json({ error: getErrorMessage(error, fallback), ...ref && { ref } }, { status: 500 });
|
|
4046
4047
|
}
|
|
4047
4048
|
async function sendFollowup(request, { host, params }) {
|
|
@@ -6653,15 +6654,138 @@ async function deleteBrandRoute(request, { host }) {
|
|
|
6653
6654
|
}
|
|
6654
6655
|
}
|
|
6655
6656
|
|
|
6657
|
+
// src/handlers/admin-text-settings.ts
|
|
6658
|
+
import { deleteTextSettings, getTextSettings, saveTextSettings, SchedulingValidationError as SchedulingValidationError12 } from "@ordinatio/scheduling";
|
|
6659
|
+
var NOT_ENABLED4 = { error: "Text-message settings are not enabled on this server" };
|
|
6660
|
+
function failure3(error, fallback) {
|
|
6661
|
+
if (error instanceof SchedulingValidationError12) {
|
|
6662
|
+
const details = error.context.errors;
|
|
6663
|
+
return Response.json({ error: error.message, code: error.code, ref: getErrorRef(error), ...details ? { details } : {} }, { status: 400 });
|
|
6664
|
+
}
|
|
6665
|
+
console.error("[text-settings]", error);
|
|
6666
|
+
return Response.json({ error: fallback }, { status: 500 });
|
|
6667
|
+
}
|
|
6668
|
+
async function requireTextAdmin(host, request, options) {
|
|
6669
|
+
const staff = await requireAdminStaff(host, request, options);
|
|
6670
|
+
if (staff instanceof Response) return staff;
|
|
6671
|
+
if (!host.textMessages) return Response.json(NOT_ENABLED4, { status: 501 });
|
|
6672
|
+
return staff;
|
|
6673
|
+
}
|
|
6674
|
+
async function getTextSettingsRoute(request, { host }) {
|
|
6675
|
+
try {
|
|
6676
|
+
const staff = await requireTextAdmin(host, request, { action: "admin-text-settings-get", tier: "GENERAL" });
|
|
6677
|
+
if (staff instanceof Response) return staff;
|
|
6678
|
+
return Response.json({ settings: await getTextSettings(staff.db, staff.organizationId), providers: host.textMessages?.providers ?? ["TELNYX", "TWILIO"] });
|
|
6679
|
+
} catch (error) {
|
|
6680
|
+
return failure3(error, "Failed to read the text-message settings");
|
|
6681
|
+
}
|
|
6682
|
+
}
|
|
6683
|
+
async function saveTextSettingsRoute(request, { host }) {
|
|
6684
|
+
try {
|
|
6685
|
+
const staff = await requireTextAdmin(host, request, { action: "admin-text-settings-save", tier: "UPDATE" });
|
|
6686
|
+
if (staff instanceof Response) return staff;
|
|
6687
|
+
const validation = await parseBody(request, TextSettingsSchema);
|
|
6688
|
+
if (!validation.success) return validation.response;
|
|
6689
|
+
const settings = await saveTextSettings(staff.db, staff.organizationId, validation.data, { providers: host.textMessages?.providers });
|
|
6690
|
+
await host.activity.log(staff.db, {
|
|
6691
|
+
action: "scheduling.text_settings_saved",
|
|
6692
|
+
description: "changed the text-message settings",
|
|
6693
|
+
metadata: { provider: settings.provider, enabled: settings.enabled }
|
|
6694
|
+
});
|
|
6695
|
+
return Response.json({ settings });
|
|
6696
|
+
} catch (error) {
|
|
6697
|
+
return failure3(error, "Failed to save the text-message settings");
|
|
6698
|
+
}
|
|
6699
|
+
}
|
|
6700
|
+
async function deleteTextSettingsRoute(request, { host }) {
|
|
6701
|
+
try {
|
|
6702
|
+
const staff = await requireTextAdmin(host, request, { action: "admin-text-settings-delete", tier: "DELETE" });
|
|
6703
|
+
if (staff instanceof Response) return staff;
|
|
6704
|
+
const removed = await deleteTextSettings(staff.db, staff.organizationId);
|
|
6705
|
+
if (removed) await host.activity.log(staff.db, { action: "scheduling.text_settings_removed", description: "removed the text-message settings", metadata: {} });
|
|
6706
|
+
return Response.json({ removed });
|
|
6707
|
+
} catch (error) {
|
|
6708
|
+
return failure3(error, "Failed to remove the text-message settings");
|
|
6709
|
+
}
|
|
6710
|
+
}
|
|
6711
|
+
|
|
6712
|
+
// src/sending-domain/check-sending-domain.ts
|
|
6713
|
+
function recordsFor(records, domain) {
|
|
6714
|
+
return typeof records === "function" ? records(domain) : records;
|
|
6715
|
+
}
|
|
6716
|
+
var DOMAIN_PATTERN = /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;
|
|
6717
|
+
var NOT_FOUND_CODES = /* @__PURE__ */ new Set(["ENODATA", "ENOTFOUND"]);
|
|
6718
|
+
function normalizeSendingDomain(raw) {
|
|
6719
|
+
const domain = raw.trim().toLowerCase().replace(/\.$/, "");
|
|
6720
|
+
return DOMAIN_PATTERN.test(domain) ? domain : null;
|
|
6721
|
+
}
|
|
6722
|
+
function recordHost(record, domain) {
|
|
6723
|
+
return record.name === "@" ? domain : `${record.name}.${domain}`;
|
|
6724
|
+
}
|
|
6725
|
+
var clean = (value) => value.trim().replace(/\.$/, "").toLowerCase();
|
|
6726
|
+
function matches(record, published) {
|
|
6727
|
+
if (record.type === "CNAME") return clean(published) === clean(record.value);
|
|
6728
|
+
const fold = (value) => record.purpose === "dkim" ? value.trim() : value.trim().toLowerCase();
|
|
6729
|
+
if (record.match !== "contains") return fold(published) === fold(record.value);
|
|
6730
|
+
const terms = fold(published).split(/\s+/);
|
|
6731
|
+
return fold(record.value).split(/\s+/).every((term) => terms.includes(term));
|
|
6732
|
+
}
|
|
6733
|
+
async function lookUp(resolver, record, host) {
|
|
6734
|
+
if (record.type === "CNAME") return await resolver.resolveCname(host);
|
|
6735
|
+
return (await resolver.resolveTxt(host)).map((chunks) => chunks.join(""));
|
|
6736
|
+
}
|
|
6737
|
+
var label = { spf: "SPF", dkim: "DKIM", dmarc: "DMARC", other: "This" };
|
|
6738
|
+
async function checkRecord(resolver, record, domain) {
|
|
6739
|
+
const host = recordHost(record, domain);
|
|
6740
|
+
const who = label[record.purpose];
|
|
6741
|
+
try {
|
|
6742
|
+
const published = await lookUp(resolver, record, host);
|
|
6743
|
+
if (published.some((value) => matches(record, value))) {
|
|
6744
|
+
return { record, host, status: "found", message: `${who} record is in place.` };
|
|
6745
|
+
}
|
|
6746
|
+
const hint = published.length === 0 ? "is empty" : "does not match";
|
|
6747
|
+
return { record, host, status: "wrong", message: `${who} record at ${host} ${hint}. Replace it with the value shown.` };
|
|
6748
|
+
} catch (error) {
|
|
6749
|
+
const code = error?.code;
|
|
6750
|
+
if (code && NOT_FOUND_CODES.has(code)) {
|
|
6751
|
+
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.` };
|
|
6752
|
+
}
|
|
6753
|
+
return { record, host, status: "unknown", message: `${who} record could not be checked just now. Try again in a few minutes.` };
|
|
6754
|
+
}
|
|
6755
|
+
}
|
|
6756
|
+
async function checkSendingDomain(config, rawDomain) {
|
|
6757
|
+
const domain = normalizeSendingDomain(rawDomain);
|
|
6758
|
+
if (!domain) return { domain: rawDomain, verified: false, records: [] };
|
|
6759
|
+
const records = await Promise.all(recordsFor(config.records, domain).map((record) => checkRecord(config.resolver, record, domain)));
|
|
6760
|
+
const required = records.filter((check) => check.record.required !== false);
|
|
6761
|
+
const verified = required.length > 0 && required.every((check) => check.status === "found");
|
|
6762
|
+
return { domain, verified, records };
|
|
6763
|
+
}
|
|
6764
|
+
|
|
6765
|
+
// src/handlers/admin-brand-domain-check.ts
|
|
6766
|
+
async function checkSendingDomainRoute(request, { host }) {
|
|
6767
|
+
try {
|
|
6768
|
+
const staff = await requireBrandAdmin(host, request, { action: "admin-brand-domain-check", tier: "SETTINGS" });
|
|
6769
|
+
if (staff instanceof Response) return staff;
|
|
6770
|
+
const check = host.brand?.checkSendingDomain;
|
|
6771
|
+
if (!check) return Response.json({ error: "Sending-domain checking is not set up on this server" }, { status: 501 });
|
|
6772
|
+
const domain = normalizeSendingDomain(new URL(request.url).searchParams.get("domain") ?? "");
|
|
6773
|
+
if (!domain) return Response.json({ error: "Enter a domain such as mail.acme.com" }, { status: 400 });
|
|
6774
|
+
return Response.json({ check: await check.call(host.brand, domain, staff.organizationId) });
|
|
6775
|
+
} catch (error) {
|
|
6776
|
+
return brandErrorResponse(error, "Failed to check the sending domain");
|
|
6777
|
+
}
|
|
6778
|
+
}
|
|
6779
|
+
|
|
6656
6780
|
// src/handlers/admin-privacy.ts
|
|
6657
6781
|
import { eraseSubject, exportSubject, listPrivacyRequests, previewErase } from "@ordinatio/scheduling";
|
|
6658
6782
|
|
|
6659
6783
|
// src/privacy/privacy-http.ts
|
|
6660
|
-
import { SchedulingValidationError as
|
|
6661
|
-
var
|
|
6784
|
+
import { SchedulingValidationError as SchedulingValidationError13 } from "@ordinatio/scheduling";
|
|
6785
|
+
var NOT_ENABLED5 = { error: "Data export and erasure are not enabled on this server" };
|
|
6662
6786
|
var STATUS_BY_CODE3 = { SCHED_1300: 400, SCHED_1301: 409 };
|
|
6663
6787
|
function privacyErrorResponse(error, fallback) {
|
|
6664
|
-
if (error instanceof
|
|
6788
|
+
if (error instanceof SchedulingValidationError13) {
|
|
6665
6789
|
return Response.json(
|
|
6666
6790
|
{ error: error.message, code: error.code, ref: getErrorRef(error), details: error.context },
|
|
6667
6791
|
{ status: STATUS_BY_CODE3[error.code] ?? 400 }
|
|
@@ -6673,7 +6797,7 @@ function privacyErrorResponse(error, fallback) {
|
|
|
6673
6797
|
async function requirePrivacyAdmin(host, request, options) {
|
|
6674
6798
|
const staff = await requireAdminStaff(host, request, options);
|
|
6675
6799
|
if (staff instanceof Response) return staff;
|
|
6676
|
-
if (!host.privacy) return Response.json(
|
|
6800
|
+
if (!host.privacy) return Response.json(NOT_ENABLED5, { status: 501 });
|
|
6677
6801
|
return staff;
|
|
6678
6802
|
}
|
|
6679
6803
|
|
|
@@ -7291,6 +7415,31 @@ async function getPublicCalendar(request, { host }) {
|
|
|
7291
7415
|
}
|
|
7292
7416
|
}
|
|
7293
7417
|
|
|
7418
|
+
// src/handlers/calendars-active.ts
|
|
7419
|
+
async function listActiveCalendars(request, { host }) {
|
|
7420
|
+
try {
|
|
7421
|
+
const staff = await requireAdminStaff(host, request, {
|
|
7422
|
+
action: "admin-calendars-list",
|
|
7423
|
+
tier: "GENERAL",
|
|
7424
|
+
allowAnyRole: true,
|
|
7425
|
+
ignoreSchedulingSwitch: true
|
|
7426
|
+
});
|
|
7427
|
+
if (staff instanceof Response) return staff;
|
|
7428
|
+
const { db, organizationId } = staff;
|
|
7429
|
+
const visibility = await staff.visibleCalendars();
|
|
7430
|
+
const calendars = await db.schedulingCalendar.findMany({
|
|
7431
|
+
// organizationId comes last so a filter can never widen the list beyond this organization.
|
|
7432
|
+
where: { isActive: true, ...visibility, organizationId },
|
|
7433
|
+
select: { id: true, name: true, slug: true, staffName: true },
|
|
7434
|
+
orderBy: { name: "asc" }
|
|
7435
|
+
});
|
|
7436
|
+
return Response.json(calendars);
|
|
7437
|
+
} catch (error) {
|
|
7438
|
+
console.warn("[calendars/active]", error instanceof Error ? error.message : error);
|
|
7439
|
+
return Response.json({ error: "Failed to fetch calendars" }, { status: 500 });
|
|
7440
|
+
}
|
|
7441
|
+
}
|
|
7442
|
+
|
|
7294
7443
|
// src/handlers/type.ts
|
|
7295
7444
|
import { schedError as schedError31 } from "@ordinatio/scheduling";
|
|
7296
7445
|
|
|
@@ -7507,6 +7656,7 @@ var ROUTES = [
|
|
|
7507
7656
|
{ method: "GET", path: "/type", public: true, handler: getType },
|
|
7508
7657
|
{ method: "GET", path: "/appointment-types", public: true, handler: getAppointmentTypes },
|
|
7509
7658
|
{ method: "GET", path: "/calendars", public: true, handler: getPublicCalendar },
|
|
7659
|
+
{ method: "GET", path: "/calendars/active", public: false, handler: listActiveCalendars },
|
|
7510
7660
|
{ method: "GET", path: "/availability", public: true, handler: getAvailability },
|
|
7511
7661
|
{ method: "GET", path: "/availability/team", public: true, handler: getTeamAvailability },
|
|
7512
7662
|
{ method: "POST", path: "/appointments", public: true, handler: bookAppointmentRoute },
|
|
@@ -7567,6 +7717,10 @@ var ROUTES = [
|
|
|
7567
7717
|
{ method: "GET", path: "/admin/brand", public: false, handler: getBrandAdminRoute },
|
|
7568
7718
|
{ method: "PUT", path: "/admin/brand", public: false, handler: saveBrandRoute },
|
|
7569
7719
|
{ method: "DELETE", path: "/admin/brand", public: false, handler: deleteBrandRoute },
|
|
7720
|
+
{ method: "GET", path: "/admin/text-settings", public: false, handler: getTextSettingsRoute },
|
|
7721
|
+
{ method: "PUT", path: "/admin/text-settings", public: false, handler: saveTextSettingsRoute },
|
|
7722
|
+
{ method: "DELETE", path: "/admin/text-settings", public: false, handler: deleteTextSettingsRoute },
|
|
7723
|
+
{ method: "GET", path: "/admin/brand/sending-domain", public: false, handler: checkSendingDomainRoute },
|
|
7570
7724
|
{ method: "POST", path: "/admin/privacy/export", public: false, handler: exportPrivacyRoute },
|
|
7571
7725
|
{ method: "POST", path: "/admin/privacy/erase", public: false, handler: erasePrivacyRoute },
|
|
7572
7726
|
{ method: "GET", path: "/admin/privacy/requests", public: false, handler: listPrivacyRequestsRoute },
|
|
@@ -7661,6 +7815,7 @@ function createSchedulingApi(config) {
|
|
|
7661
7815
|
routingForms: config.host.routingForms ?? null,
|
|
7662
7816
|
privacy: config.host.privacy ?? null,
|
|
7663
7817
|
brand: config.host.brand ?? null,
|
|
7818
|
+
textMessages: config.host.textMessages ?? null,
|
|
7664
7819
|
icalUidDomain: config.host.icalUidDomain?.bind(config.host) ?? (() => null),
|
|
7665
7820
|
calendarSync: config.host.calendarSync ?? { upsertEvent: async () => ({}), removeEvent: async () => void 0 },
|
|
7666
7821
|
activity: config.host.activity ?? { log: async () => void 0, isOpen: async () => false, resolve: async () => void 0 },
|
|
@@ -7692,16 +7847,16 @@ function createSchedulingApi(config) {
|
|
|
7692
7847
|
const { pathname } = new URL(request.url);
|
|
7693
7848
|
if (pathname !== basePath && !pathname.startsWith(`${basePath}/`)) return notFound();
|
|
7694
7849
|
const relative = pathname.slice(basePath.length) || "/";
|
|
7695
|
-
const
|
|
7696
|
-
if (
|
|
7850
|
+
const matches2 = routes.map((route) => ({ route, params: matchPath(route.path, relative) })).filter((match) => match.params !== null);
|
|
7851
|
+
if (matches2.length === 0) return notFound();
|
|
7697
7852
|
const method = request.method.toUpperCase();
|
|
7698
|
-
if (method === "OPTIONS" &&
|
|
7853
|
+
if (method === "OPTIONS" && matches2.some((match) => match.route.public)) {
|
|
7699
7854
|
return new Response(null, { status: 204, headers: host.cors(request) });
|
|
7700
7855
|
}
|
|
7701
|
-
const hit =
|
|
7856
|
+
const hit = matches2.find((match) => match.route.method === method);
|
|
7702
7857
|
if (!hit) {
|
|
7703
|
-
const allowed = [...new Set(
|
|
7704
|
-
if (
|
|
7858
|
+
const allowed = [...new Set(matches2.map((match) => match.route.method))];
|
|
7859
|
+
if (matches2.some((match) => match.route.public)) allowed.push("OPTIONS");
|
|
7705
7860
|
return Response.json({ error: "Method not allowed" }, { status: 405, headers: { Allow: allowed.join(", ") } });
|
|
7706
7861
|
}
|
|
7707
7862
|
try {
|
|
@@ -7722,6 +7877,756 @@ function createSchedulingApi(config) {
|
|
|
7722
7877
|
return { routes, handle, handler };
|
|
7723
7878
|
}
|
|
7724
7879
|
|
|
7880
|
+
// src/payments/stripe/stripe-payments.ts
|
|
7881
|
+
var TWO_DECIMAL_CURRENCIES = ["usd", "eur", "gbp", "cad", "aud"];
|
|
7882
|
+
var REFUSAL_TYPES = ["StripeInvalidRequestError", "StripeCardError"];
|
|
7883
|
+
var IN_FLIGHT_CODES = ["idempotency_key_in_use", "lock_timeout"];
|
|
7884
|
+
function asStripeError(error) {
|
|
7885
|
+
if (typeof error !== "object" || error === null) return {};
|
|
7886
|
+
const shape = error;
|
|
7887
|
+
return shape.code === void 0 && shape.raw?.code !== void 0 ? { ...shape, code: shape.raw.code } : shape;
|
|
7888
|
+
}
|
|
7889
|
+
function isKeyMismatch(error) {
|
|
7890
|
+
return error.type === "StripeIdempotencyError" || error.raw?.type === "idempotency_error";
|
|
7891
|
+
}
|
|
7892
|
+
function isRefusal(error) {
|
|
7893
|
+
return error.type !== void 0 && REFUSAL_TYPES.includes(error.type);
|
|
7894
|
+
}
|
|
7895
|
+
function isReplayedFailure(error) {
|
|
7896
|
+
const header = Object.entries(error.headers ?? {}).find(([name]) => name.toLowerCase() === "idempotent-replayed");
|
|
7897
|
+
return header?.[1] === "true";
|
|
7898
|
+
}
|
|
7899
|
+
function isSupportedCurrency(currency) {
|
|
7900
|
+
return currency !== void 0 && TWO_DECIMAL_CURRENCIES.includes(currency.toLowerCase());
|
|
7901
|
+
}
|
|
7902
|
+
function toMinor(amount) {
|
|
7903
|
+
if (!Number.isFinite(amount) || amount <= 0) return null;
|
|
7904
|
+
const minor = Math.round(amount * 100);
|
|
7905
|
+
if (minor < 1 || !Number.isSafeInteger(minor)) return null;
|
|
7906
|
+
return Math.abs(amount * 100 - minor) < 1e-6 ? minor : null;
|
|
7907
|
+
}
|
|
7908
|
+
function toMajor(minor, currency) {
|
|
7909
|
+
return isSupportedCurrency(currency) ? minor / 100 : void 0;
|
|
7910
|
+
}
|
|
7911
|
+
function unsupportedCurrency(currency) {
|
|
7912
|
+
return `Currency ${currency.toUpperCase()} is not supported by this adapter (supported: ${TWO_DECIMAL_CURRENCIES.join(", ").toUpperCase()})`;
|
|
7913
|
+
}
|
|
7914
|
+
var BAD_AMOUNT = "amount must be greater than 0 and have at most 2 decimals";
|
|
7915
|
+
function createStripePaymentAdapter(client) {
|
|
7916
|
+
async function verifyPayment(paymentId) {
|
|
7917
|
+
let intent;
|
|
7918
|
+
try {
|
|
7919
|
+
intent = await client.paymentIntents.retrieve(paymentId, { expand: ["latest_charge"] });
|
|
7920
|
+
} catch (error) {
|
|
7921
|
+
if (asStripeError(error).code === "resource_missing") return { paid: false, status: "not_found" };
|
|
7922
|
+
throw error;
|
|
7923
|
+
}
|
|
7924
|
+
const charge = intent.latest_charge;
|
|
7925
|
+
const metadata = intent.metadata ?? {};
|
|
7926
|
+
const currency = intent.currency.toUpperCase();
|
|
7927
|
+
const amount = toMajor(intent.amount, intent.currency);
|
|
7928
|
+
if (intent.status === "succeeded" && (typeof charge !== "object" || charge === null)) {
|
|
7929
|
+
return { paid: false, amount, currency, status: "refund_state_unknown", metadata };
|
|
7930
|
+
}
|
|
7931
|
+
const refunded = typeof charge === "object" && charge !== null ? charge.amount_refunded ?? 0 : 0;
|
|
7932
|
+
const fullyRefunded = intent.status === "succeeded" && refunded >= intent.amount;
|
|
7933
|
+
return {
|
|
7934
|
+
paid: intent.status === "succeeded" && !fullyRefunded,
|
|
7935
|
+
amount,
|
|
7936
|
+
currency,
|
|
7937
|
+
status: fullyRefunded ? "refunded" : intent.status,
|
|
7938
|
+
metadata
|
|
7939
|
+
};
|
|
7940
|
+
}
|
|
7941
|
+
return {
|
|
7942
|
+
async charge(request) {
|
|
7943
|
+
const currency = request.currency.toLowerCase();
|
|
7944
|
+
if (!isSupportedCurrency(currency)) return { success: false, error: unsupportedCurrency(request.currency) };
|
|
7945
|
+
const amount = toMinor(request.amount);
|
|
7946
|
+
if (amount === null) return { success: false, error: BAD_AMOUNT };
|
|
7947
|
+
let intent;
|
|
7948
|
+
try {
|
|
7949
|
+
intent = await client.paymentIntents.create(
|
|
7950
|
+
{ amount, currency, ...request.metadata ? { metadata: request.metadata } : {} },
|
|
7951
|
+
request.idempotencyKey ? { idempotencyKey: request.idempotencyKey } : void 0
|
|
7952
|
+
);
|
|
7953
|
+
} catch (error) {
|
|
7954
|
+
const stripeError = asStripeError(error);
|
|
7955
|
+
if (stripeError.code && IN_FLIGHT_CODES.includes(stripeError.code)) return { success: false, code: "IN_PROGRESS", error: stripeError.message };
|
|
7956
|
+
if (isKeyMismatch(stripeError)) return { success: false, code: "KEY_REUSED", error: stripeError.message };
|
|
7957
|
+
if (isRefusal(stripeError)) return { success: false, error: stripeError.message };
|
|
7958
|
+
throw error;
|
|
7959
|
+
}
|
|
7960
|
+
let status = intent.status;
|
|
7961
|
+
if (request.idempotencyKey) {
|
|
7962
|
+
try {
|
|
7963
|
+
status = (await client.paymentIntents.retrieve(intent.id)).status;
|
|
7964
|
+
} catch (error) {
|
|
7965
|
+
throw new UnverifiedPaymentError(intent.id, error);
|
|
7966
|
+
}
|
|
7967
|
+
if (status === "canceled") return { success: false, code: "CANCELED", error: "the payment saved for this key was canceled; retry with a new key" };
|
|
7968
|
+
}
|
|
7969
|
+
return {
|
|
7970
|
+
success: true,
|
|
7971
|
+
paymentId: intent.id,
|
|
7972
|
+
status: status === "succeeded" ? "SUCCEEDED" : "REQUIRES_ACTION",
|
|
7973
|
+
clientSecret: intent.client_secret ?? void 0
|
|
7974
|
+
};
|
|
7975
|
+
},
|
|
7976
|
+
verify: verifyPayment,
|
|
7977
|
+
async refund(paymentId, options = {}) {
|
|
7978
|
+
let amountMinor;
|
|
7979
|
+
if (options.amount !== void 0) {
|
|
7980
|
+
if (!options.idempotencyKey) return { success: false, error: "a partial refund needs an idempotencyKey" };
|
|
7981
|
+
const minor = toMinor(options.amount);
|
|
7982
|
+
if (minor === null) return { success: false, error: BAD_AMOUNT };
|
|
7983
|
+
amountMinor = minor;
|
|
7984
|
+
const check = await verifyPayment(paymentId);
|
|
7985
|
+
if (check.status === "not_found") return { success: false, error: "unknown payment" };
|
|
7986
|
+
if (!isSupportedCurrency(check.currency)) return { success: false, error: unsupportedCurrency(check.currency ?? "unknown") };
|
|
7987
|
+
}
|
|
7988
|
+
try {
|
|
7989
|
+
const refund = await client.refunds.create(
|
|
7990
|
+
{ payment_intent: paymentId, ...amountMinor !== void 0 ? { amount: amountMinor } : {} },
|
|
7991
|
+
options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : void 0
|
|
7992
|
+
);
|
|
7993
|
+
const amount = toMajor(refund.amount, refund.currency);
|
|
7994
|
+
if (refund.status === "succeeded") return { success: true, refundId: refund.id, amount, status: "SUCCEEDED" };
|
|
7995
|
+
if (refund.status === "pending" || refund.status === "requires_action") {
|
|
7996
|
+
return { success: true, refundId: refund.id, amount, status: "PENDING" };
|
|
7997
|
+
}
|
|
7998
|
+
return { success: false, refundId: refund.id, error: `Stripe refund ${refund.status ?? "unknown"}` };
|
|
7999
|
+
} catch (error) {
|
|
8000
|
+
const stripeError = asStripeError(error);
|
|
8001
|
+
const requestId = stripeError.requestId;
|
|
8002
|
+
if (stripeError.code === "charge_already_refunded") return { success: false, error: stripeError.message, code: "ALREADY_REFUNDED", requestId };
|
|
8003
|
+
if (stripeError.code && IN_FLIGHT_CODES.includes(stripeError.code)) return { success: false, error: stripeError.message, code: "IN_PROGRESS", requestId };
|
|
8004
|
+
if (stripeError.code === "resource_missing") return { success: false, error: "unknown payment", requestId };
|
|
8005
|
+
if (isKeyMismatch(stripeError)) return { success: false, error: stripeError.message, code: "KEY_REUSED", requestId };
|
|
8006
|
+
if (isRefusal(stripeError)) {
|
|
8007
|
+
return { success: false, error: stripeError.message, requestId, ...isReplayedFailure(stripeError) ? { code: "REPLAYED_FAILURE" } : {} };
|
|
8008
|
+
}
|
|
8009
|
+
if (isReplayedFailure(stripeError)) return { success: false, error: stripeError.message, requestId, code: "REPLAYED_FAILURE" };
|
|
8010
|
+
throw error;
|
|
8011
|
+
}
|
|
8012
|
+
}
|
|
8013
|
+
};
|
|
8014
|
+
}
|
|
8015
|
+
|
|
8016
|
+
// src/payments/stripe/stripe-test-key.ts
|
|
8017
|
+
function assertStripeTestKey(raw) {
|
|
8018
|
+
const key = raw?.trim();
|
|
8019
|
+
if (!key) throw new Error("STRIPE_SECRET_KEY is not set");
|
|
8020
|
+
if (!key.startsWith("sk_test_")) throw new Error("STRIPE_SECRET_KEY is not a test-mode secret key (it must start with sk_test_)");
|
|
8021
|
+
return key;
|
|
8022
|
+
}
|
|
8023
|
+
|
|
8024
|
+
// src/sending-domain/create-sending-domain-verifier.ts
|
|
8025
|
+
function createSendingDomainVerifier(config) {
|
|
8026
|
+
const check = (domain) => checkSendingDomain(config, domain);
|
|
8027
|
+
return {
|
|
8028
|
+
isSendingDomainVerified: async (domain) => (await check(domain)).verified,
|
|
8029
|
+
check,
|
|
8030
|
+
instructions: (rawDomain) => {
|
|
8031
|
+
const domain = normalizeSendingDomain(rawDomain);
|
|
8032
|
+
return domain ? recordsFor(config.records, domain).map((record) => ({ record, host: recordHost(record, domain) })) : [];
|
|
8033
|
+
}
|
|
8034
|
+
};
|
|
8035
|
+
}
|
|
8036
|
+
|
|
8037
|
+
// src/sms/sms-common.ts
|
|
8038
|
+
var SmsSendError = class extends Error {
|
|
8039
|
+
constructor(message, retryable, outcomeUnknown, status, code) {
|
|
8040
|
+
super(message);
|
|
8041
|
+
this.retryable = retryable;
|
|
8042
|
+
this.outcomeUnknown = outcomeUnknown;
|
|
8043
|
+
this.status = status;
|
|
8044
|
+
this.code = code;
|
|
8045
|
+
this.name = "SmsSendError";
|
|
8046
|
+
}
|
|
8047
|
+
};
|
|
8048
|
+
function normalizePhoneNumber(raw) {
|
|
8049
|
+
const digits = raw.trim().replace(/[\s().-]/g, "");
|
|
8050
|
+
if (/^\+[1-9]\d{7,14}$/.test(digits)) return digits;
|
|
8051
|
+
if (/^\d{10}$/.test(digits)) return `+1${digits}`;
|
|
8052
|
+
if (/^1\d{10}$/.test(digits)) return `+${digits}`;
|
|
8053
|
+
return null;
|
|
8054
|
+
}
|
|
8055
|
+
function readHeader(headers, name) {
|
|
8056
|
+
if (typeof headers.get === "function") return headers.get(name) ?? void 0;
|
|
8057
|
+
const found = Object.entries(headers).find(([key]) => key.toLowerCase() === name);
|
|
8058
|
+
const value = found?.[1];
|
|
8059
|
+
return Array.isArray(value) ? value[0] : value;
|
|
8060
|
+
}
|
|
8061
|
+
var STOP_WORDS = ["STOP", "STOPALL", "UNSUBSCRIBE", "END", "QUIT"];
|
|
8062
|
+
var START_WORDS = ["START", "UNSTOP"];
|
|
8063
|
+
function classifyReply(text) {
|
|
8064
|
+
const word = text.trim().toUpperCase().replace(/[.!?,]+$/, "");
|
|
8065
|
+
return STOP_WORDS.includes(word) ? "opt-out" : START_WORDS.includes(word) ? "opt-in" : "reply";
|
|
8066
|
+
}
|
|
8067
|
+
|
|
8068
|
+
// src/telnyx/telnyx-sms.ts
|
|
8069
|
+
var TELNYX_MESSAGES_URL = "https://api.telnyx.com/v2/messages";
|
|
8070
|
+
var DEFAULT_TIMEOUT_MS = 1e4;
|
|
8071
|
+
var OPTED_OUT_CODE = "40300";
|
|
8072
|
+
function firstError(body) {
|
|
8073
|
+
const error = body?.errors?.[0];
|
|
8074
|
+
if (!error) return { text: "no detail given" };
|
|
8075
|
+
return { code: error.code === void 0 ? void 0 : String(error.code), text: error.detail ?? error.title ?? "no detail given" };
|
|
8076
|
+
}
|
|
8077
|
+
function createTelnyxSmsAdapter(config) {
|
|
8078
|
+
const apiKey = typeof config.apiKey === "string" ? config.apiKey.trim() : "";
|
|
8079
|
+
if (!apiKey) throw new Error("createTelnyxSmsAdapter needs an apiKey");
|
|
8080
|
+
const profileId = config.messagingProfileId?.trim() || void 0;
|
|
8081
|
+
const from = config.from ? normalizePhoneNumber(config.from) : null;
|
|
8082
|
+
if (config.from && !from) throw new Error('createTelnyxSmsAdapter: "from" must be a phone number such as +13135550100');
|
|
8083
|
+
if (!from && !profileId) throw new Error('createTelnyxSmsAdapter needs a sending number ("from"), a messagingProfileId, or both');
|
|
8084
|
+
const doFetch = config.fetch ?? fetch;
|
|
8085
|
+
const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
8086
|
+
return {
|
|
8087
|
+
async send(message) {
|
|
8088
|
+
if (message.channel !== "SMS") return { status: "SKIPPED", reason: "The Telnyx adapter only sends text messages" };
|
|
8089
|
+
const to = normalizePhoneNumber(message.to);
|
|
8090
|
+
if (!to) return { status: "SKIPPED", reason: "The recipient is not a valid phone number" };
|
|
8091
|
+
if (!message.body.trim()) return { status: "SKIPPED", reason: "The message is empty" };
|
|
8092
|
+
const controller = new AbortController();
|
|
8093
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
8094
|
+
let response;
|
|
8095
|
+
let body;
|
|
8096
|
+
try {
|
|
8097
|
+
response = await doFetch(TELNYX_MESSAGES_URL, {
|
|
8098
|
+
method: "POST",
|
|
8099
|
+
headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
|
|
8100
|
+
body: JSON.stringify({
|
|
8101
|
+
to,
|
|
8102
|
+
text: message.body,
|
|
8103
|
+
type: "SMS",
|
|
8104
|
+
...from ? { from } : {},
|
|
8105
|
+
...profileId ? { messaging_profile_id: profileId } : {}
|
|
8106
|
+
}),
|
|
8107
|
+
signal: controller.signal
|
|
8108
|
+
});
|
|
8109
|
+
body = await response.json().catch((error) => {
|
|
8110
|
+
if (controller.signal.aborted) throw error;
|
|
8111
|
+
return null;
|
|
8112
|
+
});
|
|
8113
|
+
} catch (error) {
|
|
8114
|
+
const reason = controller.signal.aborted ? `timed out after ${timeoutMs} ms` : error instanceof Error ? error.message : String(error);
|
|
8115
|
+
throw new SmsSendError(`Telnyx could not be reached (${reason}); the message may or may not have been sent`, true, true);
|
|
8116
|
+
} finally {
|
|
8117
|
+
clearTimeout(timer);
|
|
8118
|
+
}
|
|
8119
|
+
if (response.ok) {
|
|
8120
|
+
const id = body?.data?.id;
|
|
8121
|
+
return id ? { status: "SENT", id } : { status: "SENT" };
|
|
8122
|
+
}
|
|
8123
|
+
const { code, text } = firstError(body);
|
|
8124
|
+
if (code === OPTED_OUT_CODE) return { status: "SKIPPED", reason: "The recipient opted out of text messages" };
|
|
8125
|
+
const serverFault = response.status >= 500;
|
|
8126
|
+
const retryable = response.status === 429 || serverFault;
|
|
8127
|
+
throw new SmsSendError(
|
|
8128
|
+
`Telnyx refused the message (HTTP ${response.status}${code ? `, code ${code}` : ""}): ${text}`,
|
|
8129
|
+
retryable,
|
|
8130
|
+
serverFault,
|
|
8131
|
+
response.status,
|
|
8132
|
+
code
|
|
8133
|
+
);
|
|
8134
|
+
}
|
|
8135
|
+
};
|
|
8136
|
+
}
|
|
8137
|
+
|
|
8138
|
+
// src/telnyx/telnyx-inbound.ts
|
|
8139
|
+
import { createPublicKey, verify } from "crypto";
|
|
8140
|
+
var ED25519_SPKI_PREFIX = Buffer.from("302a300506032b6570032100", "hex");
|
|
8141
|
+
var DEFAULT_TOLERANCE_SECONDS = 300;
|
|
8142
|
+
function verifyTelnyxSignature(rawBody, headers, options) {
|
|
8143
|
+
const signature = readHeader(headers, "telnyx-signature-ed25519");
|
|
8144
|
+
const timestamp = readHeader(headers, "telnyx-timestamp");
|
|
8145
|
+
if (!signature || !timestamp || !/^\d+$/.test(timestamp)) return false;
|
|
8146
|
+
const nowSeconds = Math.floor((options.now?.() ?? /* @__PURE__ */ new Date()).getTime() / 1e3);
|
|
8147
|
+
if (Math.abs(nowSeconds - Number(timestamp)) > (options.toleranceSeconds ?? DEFAULT_TOLERANCE_SECONDS)) return false;
|
|
8148
|
+
try {
|
|
8149
|
+
const raw = Buffer.from(options.publicKey.trim(), "base64");
|
|
8150
|
+
if (raw.length !== 32) return false;
|
|
8151
|
+
const key = createPublicKey({ key: Buffer.concat([ED25519_SPKI_PREFIX, raw]), format: "der", type: "spki" });
|
|
8152
|
+
return verify(null, Buffer.from(`${timestamp}|${rawBody}`), key, Buffer.from(signature, "base64"));
|
|
8153
|
+
} catch {
|
|
8154
|
+
return false;
|
|
8155
|
+
}
|
|
8156
|
+
}
|
|
8157
|
+
function handleTelnyxWebhook(rawBody, headers, options) {
|
|
8158
|
+
if (!verifyTelnyxSignature(rawBody, headers, options)) return { ok: false, status: 401, reason: "The signature is missing, wrong or too old" };
|
|
8159
|
+
let parsed;
|
|
8160
|
+
try {
|
|
8161
|
+
const value = JSON.parse(rawBody);
|
|
8162
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return { ok: false, status: 400, reason: "The body is not an event" };
|
|
8163
|
+
parsed = value;
|
|
8164
|
+
} catch {
|
|
8165
|
+
return { ok: false, status: 400, reason: "The body is not JSON" };
|
|
8166
|
+
}
|
|
8167
|
+
const eventType = parsed.data?.event_type ?? "";
|
|
8168
|
+
const payload = parsed.data?.payload;
|
|
8169
|
+
const id = payload?.id;
|
|
8170
|
+
const to = payload?.to?.[0]?.phone_number;
|
|
8171
|
+
if (eventType === "message.received") {
|
|
8172
|
+
const from = payload?.from?.phone_number;
|
|
8173
|
+
if (!id || !from || !to) return { ok: false, status: 400, reason: "The message is missing its id or phone numbers" };
|
|
8174
|
+
const text = typeof payload?.text === "string" ? payload.text : "";
|
|
8175
|
+
const type = classifyReply(text);
|
|
8176
|
+
return { ok: true, event: { type, id, from, to, text } };
|
|
8177
|
+
}
|
|
8178
|
+
if (eventType === "message.finalized" || eventType === "message.sent") {
|
|
8179
|
+
if (!id || !to) return { ok: false, status: 400, reason: "The delivery report is missing its id or number" };
|
|
8180
|
+
const status = payload?.to?.[0]?.status;
|
|
8181
|
+
if (eventType === "message.sent" || status !== "delivered" && status !== "delivery_failed" && status !== "sending_failed") {
|
|
8182
|
+
return { ok: true, event: { type: "ignored", eventType } };
|
|
8183
|
+
}
|
|
8184
|
+
const errorCode = payload?.errors?.[0]?.code;
|
|
8185
|
+
return {
|
|
8186
|
+
ok: true,
|
|
8187
|
+
event: { type: "delivery", id, to, status: status === "delivered" ? "delivered" : "failed", ...errorCode === void 0 ? {} : { errorCode: String(errorCode) } }
|
|
8188
|
+
};
|
|
8189
|
+
}
|
|
8190
|
+
return { ok: true, event: { type: "ignored", eventType } };
|
|
8191
|
+
}
|
|
8192
|
+
|
|
8193
|
+
// src/twilio/twilio-sms.ts
|
|
8194
|
+
var DEFAULT_TIMEOUT_MS2 = 1e4;
|
|
8195
|
+
var OPTED_OUT_CODE2 = "21610";
|
|
8196
|
+
function createTwilioSmsAdapter(config) {
|
|
8197
|
+
const accountSid = typeof config.accountSid === "string" ? config.accountSid.trim() : "";
|
|
8198
|
+
const authToken = typeof config.authToken === "string" ? config.authToken.trim() : "";
|
|
8199
|
+
if (!accountSid || !authToken) throw new Error("createTwilioSmsAdapter needs an accountSid and an authToken");
|
|
8200
|
+
const serviceSid = config.messagingServiceSid?.trim() || void 0;
|
|
8201
|
+
const from = config.from ? normalizePhoneNumber(config.from) : null;
|
|
8202
|
+
if (config.from && !from) throw new Error('createTwilioSmsAdapter: "from" must be a phone number such as +13135550100');
|
|
8203
|
+
if (!from && !serviceSid) throw new Error('createTwilioSmsAdapter needs a sending number ("from") or a messagingServiceSid');
|
|
8204
|
+
const doFetch = config.fetch ?? fetch;
|
|
8205
|
+
const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
|
|
8206
|
+
const url = `https://api.twilio.com/2010-04-01/Accounts/${encodeURIComponent(accountSid)}/Messages.json`;
|
|
8207
|
+
const authorization = `Basic ${Buffer.from(`${accountSid}:${authToken}`).toString("base64")}`;
|
|
8208
|
+
return {
|
|
8209
|
+
async send(message) {
|
|
8210
|
+
if (message.channel !== "SMS") return { status: "SKIPPED", reason: "The Twilio adapter only sends text messages" };
|
|
8211
|
+
const to = normalizePhoneNumber(message.to);
|
|
8212
|
+
if (!to) return { status: "SKIPPED", reason: "The recipient is not a valid phone number" };
|
|
8213
|
+
if (!message.body.trim()) return { status: "SKIPPED", reason: "The message is empty" };
|
|
8214
|
+
const form = new URLSearchParams({ To: to, Body: message.body });
|
|
8215
|
+
if (from) form.set("From", from);
|
|
8216
|
+
else if (serviceSid) form.set("MessagingServiceSid", serviceSid);
|
|
8217
|
+
const controller = new AbortController();
|
|
8218
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
8219
|
+
let response;
|
|
8220
|
+
let body;
|
|
8221
|
+
try {
|
|
8222
|
+
response = await doFetch(url, {
|
|
8223
|
+
method: "POST",
|
|
8224
|
+
headers: { Authorization: authorization, "Content-Type": "application/x-www-form-urlencoded" },
|
|
8225
|
+
body: form.toString(),
|
|
8226
|
+
signal: controller.signal
|
|
8227
|
+
});
|
|
8228
|
+
body = await response.json().catch((error2) => {
|
|
8229
|
+
if (controller.signal.aborted) throw error2;
|
|
8230
|
+
return null;
|
|
8231
|
+
});
|
|
8232
|
+
} catch (error2) {
|
|
8233
|
+
const reason = controller.signal.aborted ? `timed out after ${timeoutMs} ms` : error2 instanceof Error ? error2.message : String(error2);
|
|
8234
|
+
throw new SmsSendError(`Twilio could not be reached (${reason}); the message may or may not have been sent`, true, true);
|
|
8235
|
+
} finally {
|
|
8236
|
+
clearTimeout(timer);
|
|
8237
|
+
}
|
|
8238
|
+
if (response.ok) {
|
|
8239
|
+
const id = body?.sid;
|
|
8240
|
+
return id ? { status: "SENT", id } : { status: "SENT" };
|
|
8241
|
+
}
|
|
8242
|
+
const error = body ?? {};
|
|
8243
|
+
const code = error.code === void 0 ? void 0 : String(error.code);
|
|
8244
|
+
if (code === OPTED_OUT_CODE2) return { status: "SKIPPED", reason: "The recipient opted out of text messages" };
|
|
8245
|
+
const serverFault = response.status >= 500;
|
|
8246
|
+
throw new SmsSendError(
|
|
8247
|
+
`Twilio refused the message (HTTP ${response.status}${code ? `, code ${code}` : ""}): ${error.message ?? "no detail given"}`,
|
|
8248
|
+
response.status === 429 || serverFault,
|
|
8249
|
+
serverFault,
|
|
8250
|
+
response.status,
|
|
8251
|
+
code
|
|
8252
|
+
);
|
|
8253
|
+
}
|
|
8254
|
+
};
|
|
8255
|
+
}
|
|
8256
|
+
|
|
8257
|
+
// src/twilio/twilio-inbound.ts
|
|
8258
|
+
import { createHmac, timingSafeEqual } from "crypto";
|
|
8259
|
+
function expectedSignature(params, options) {
|
|
8260
|
+
const keys = [...new Set(params.keys())].sort();
|
|
8261
|
+
const signed = keys.reduce((text, key) => text + key + params.getAll(key).join(""), options.url);
|
|
8262
|
+
return createHmac("sha1", options.authToken.trim()).update(signed).digest("base64");
|
|
8263
|
+
}
|
|
8264
|
+
function verifyTwilioSignature(rawBody, headers, options) {
|
|
8265
|
+
const given = readHeader(headers, "x-twilio-signature");
|
|
8266
|
+
if (!given || !options.authToken.trim()) return false;
|
|
8267
|
+
const expected = Buffer.from(expectedSignature(new URLSearchParams(rawBody), options));
|
|
8268
|
+
const actual = Buffer.from(given);
|
|
8269
|
+
return expected.length === actual.length && timingSafeEqual(expected, actual);
|
|
8270
|
+
}
|
|
8271
|
+
function handleTwilioWebhook(rawBody, headers, options) {
|
|
8272
|
+
if (!verifyTwilioSignature(rawBody, headers, options)) return { ok: false, status: 401, reason: "The signature is missing or wrong" };
|
|
8273
|
+
const params = new URLSearchParams(rawBody);
|
|
8274
|
+
const id = params.get("MessageSid") ?? params.get("SmsSid");
|
|
8275
|
+
const from = params.get("From");
|
|
8276
|
+
const to = params.get("To");
|
|
8277
|
+
if (params.has("MessageStatus") && !params.has("Body")) {
|
|
8278
|
+
const status = params.get("MessageStatus") ?? "";
|
|
8279
|
+
if (!id || !to) return { ok: false, status: 400, reason: "The status report is missing its id or number" };
|
|
8280
|
+
if (status !== "delivered" && status !== "undelivered" && status !== "failed") return { ok: true, event: { type: "ignored", eventType: `status.${status}` } };
|
|
8281
|
+
const errorCode = params.get("ErrorCode");
|
|
8282
|
+
return { ok: true, event: { type: "delivery", id, to, status: status === "delivered" ? "delivered" : "failed", ...errorCode ? { errorCode } : {} } };
|
|
8283
|
+
}
|
|
8284
|
+
if (params.has("Body")) {
|
|
8285
|
+
if (!id || !from || !to) return { ok: false, status: 400, reason: "The message is missing its id or phone numbers" };
|
|
8286
|
+
const text = params.get("Body") ?? "";
|
|
8287
|
+
return { ok: true, event: { type: classifyReply(text), id, from, to, text } };
|
|
8288
|
+
}
|
|
8289
|
+
return { ok: true, event: { type: "ignored", eventType: "unknown" } };
|
|
8290
|
+
}
|
|
8291
|
+
|
|
8292
|
+
// src/sms/per-business-sms.ts
|
|
8293
|
+
var DEFAULT_ADAPTER_TTL_MS = 5 * 6e4;
|
|
8294
|
+
var DEFAULT_NO_NUMBER_TTL_MS = 6e4;
|
|
8295
|
+
function createPerBusinessSmsAdapter(options) {
|
|
8296
|
+
const adapterTtl = options.adapterTtlMs ?? DEFAULT_ADAPTER_TTL_MS;
|
|
8297
|
+
const noNumberTtl = options.noNumberTtlMs ?? DEFAULT_NO_NUMBER_TTL_MS;
|
|
8298
|
+
const now = options.now ?? Date.now;
|
|
8299
|
+
const kept = /* @__PURE__ */ new Map();
|
|
8300
|
+
function adapterFor(organizationId) {
|
|
8301
|
+
const existing = kept.get(organizationId);
|
|
8302
|
+
if (existing && (existing.expiresAt === null || existing.expiresAt > now())) return existing.lookup;
|
|
8303
|
+
const entry = { lookup: Promise.resolve(options.resolve(organizationId)), expiresAt: null };
|
|
8304
|
+
kept.set(organizationId, entry);
|
|
8305
|
+
entry.lookup.then(
|
|
8306
|
+
(adapter) => {
|
|
8307
|
+
entry.expiresAt = now() + (adapter ? adapterTtl : noNumberTtl);
|
|
8308
|
+
},
|
|
8309
|
+
// A failed lookup is not kept; only this entry is removed, not a newer one.
|
|
8310
|
+
() => {
|
|
8311
|
+
if (kept.get(organizationId) === entry) kept.delete(organizationId);
|
|
8312
|
+
}
|
|
8313
|
+
);
|
|
8314
|
+
return entry.lookup;
|
|
8315
|
+
}
|
|
8316
|
+
return {
|
|
8317
|
+
async send(message) {
|
|
8318
|
+
if (message.channel !== "SMS") return { status: "SKIPPED", reason: "This adapter only sends text messages" };
|
|
8319
|
+
if (!message.organizationId) {
|
|
8320
|
+
return { status: "SKIPPED", reason: "The message names no business, so there is no number to send from (run the sender with organization: true)" };
|
|
8321
|
+
}
|
|
8322
|
+
const adapter = await adapterFor(message.organizationId);
|
|
8323
|
+
if (!adapter) return { status: "SKIPPED", reason: "This business has no text-message number set up" };
|
|
8324
|
+
return adapter.send(message);
|
|
8325
|
+
},
|
|
8326
|
+
forget(organizationId) {
|
|
8327
|
+
kept.delete(organizationId);
|
|
8328
|
+
}
|
|
8329
|
+
};
|
|
8330
|
+
}
|
|
8331
|
+
|
|
8332
|
+
// src/sms/text-settings-resolver.ts
|
|
8333
|
+
import { getTextSettings as getTextSettings2 } from "@ordinatio/scheduling";
|
|
8334
|
+
function createTextSettingsResolver(options) {
|
|
8335
|
+
return async (organizationId) => {
|
|
8336
|
+
const settings = await getTextSettings2(await options.db(organizationId), organizationId);
|
|
8337
|
+
if (!settings || !settings.enabled) return null;
|
|
8338
|
+
try {
|
|
8339
|
+
if (settings.provider === "TELNYX" && options.telnyx?.apiKey?.trim()) {
|
|
8340
|
+
return createTelnyxSmsAdapter({ ...options.telnyx, from: settings.fromNumber, fetch: options.fetch });
|
|
8341
|
+
}
|
|
8342
|
+
if (settings.provider === "TWILIO" && options.twilio?.accountSid?.trim() && options.twilio.authToken?.trim()) {
|
|
8343
|
+
return createTwilioSmsAdapter({ ...options.twilio, from: settings.fromNumber, fetch: options.fetch });
|
|
8344
|
+
}
|
|
8345
|
+
} catch (error) {
|
|
8346
|
+
console.error(`[text-settings] could not build the ${settings.provider} sender for organization ${organizationId}:`, error instanceof Error ? error.message : error);
|
|
8347
|
+
return null;
|
|
8348
|
+
}
|
|
8349
|
+
if (settings.provider === "TELNYX" || settings.provider === "TWILIO") {
|
|
8350
|
+
console.error(`[text-settings] organization ${organizationId} chose ${settings.provider}, but this server has no usable ${settings.provider} account`);
|
|
8351
|
+
}
|
|
8352
|
+
return null;
|
|
8353
|
+
};
|
|
8354
|
+
}
|
|
8355
|
+
|
|
8356
|
+
// src/outlook-sync/outlook-config.ts
|
|
8357
|
+
var BLOCKED_TYPE_SLUG = "blocked";
|
|
8358
|
+
var GRAPH_BASE = "https://graph.microsoft.com/v1.0";
|
|
8359
|
+
var MICROSOFT_TOKEN_ENDPOINT = "https://login.microsoftonline.com/common/oauth2/v2.0/token";
|
|
8360
|
+
var OUTLOOK_CALENDAR_SCOPE = "https://graph.microsoft.com/Calendars.ReadWrite offline_access";
|
|
8361
|
+
function problem(config, message, context) {
|
|
8362
|
+
config.onProblem?.(message, context);
|
|
8363
|
+
}
|
|
8364
|
+
|
|
8365
|
+
// src/outlook-sync/outlook-access-token.ts
|
|
8366
|
+
var REFRESH_MARGIN_MS = 5 * 60 * 1e3;
|
|
8367
|
+
async function getOutlookAccessToken(config, calendarId) {
|
|
8368
|
+
const calendar = await config.db.schedulingCalendar.findUnique({
|
|
8369
|
+
where: { id: calendarId },
|
|
8370
|
+
select: {
|
|
8371
|
+
outlookCalendarId: true,
|
|
8372
|
+
outlookAccessToken: true,
|
|
8373
|
+
outlookRefreshToken: true,
|
|
8374
|
+
outlookTokenExpiresAt: true
|
|
8375
|
+
}
|
|
8376
|
+
});
|
|
8377
|
+
if (!calendar?.outlookCalendarId || !calendar.outlookRefreshToken) return null;
|
|
8378
|
+
const now = (config.now ?? (() => /* @__PURE__ */ new Date()))();
|
|
8379
|
+
const stillValid = calendar.outlookAccessToken && calendar.outlookTokenExpiresAt && calendar.outlookTokenExpiresAt.getTime() - now.getTime() >= REFRESH_MARGIN_MS;
|
|
8380
|
+
if (stillValid) return calendar.outlookAccessToken;
|
|
8381
|
+
try {
|
|
8382
|
+
const response = await (config.fetch ?? fetch)(MICROSOFT_TOKEN_ENDPOINT, {
|
|
8383
|
+
method: "POST",
|
|
8384
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
8385
|
+
body: new URLSearchParams({
|
|
8386
|
+
client_id: config.clientId.trim(),
|
|
8387
|
+
client_secret: config.clientSecret.trim(),
|
|
8388
|
+
refresh_token: calendar.outlookRefreshToken,
|
|
8389
|
+
grant_type: "refresh_token",
|
|
8390
|
+
scope: OUTLOOK_CALENDAR_SCOPE
|
|
8391
|
+
})
|
|
8392
|
+
});
|
|
8393
|
+
if (!response.ok) throw new Error(`Token refresh HTTP ${response.status}`);
|
|
8394
|
+
const data = await response.json();
|
|
8395
|
+
if (!data.access_token || typeof data.expires_in !== "number") throw new Error("Token refresh answered without a token");
|
|
8396
|
+
await config.db.schedulingCalendar.update({
|
|
8397
|
+
where: { id: calendarId },
|
|
8398
|
+
data: {
|
|
8399
|
+
outlookAccessToken: data.access_token,
|
|
8400
|
+
outlookRefreshToken: data.refresh_token ?? calendar.outlookRefreshToken,
|
|
8401
|
+
outlookTokenExpiresAt: new Date(now.getTime() + data.expires_in * 1e3)
|
|
8402
|
+
}
|
|
8403
|
+
});
|
|
8404
|
+
return data.access_token;
|
|
8405
|
+
} catch (error) {
|
|
8406
|
+
problem(config, "Outlook token refresh failed; the calendar must be reconnected", {
|
|
8407
|
+
calendarId,
|
|
8408
|
+
error: error instanceof Error ? error.message : String(error)
|
|
8409
|
+
});
|
|
8410
|
+
return null;
|
|
8411
|
+
}
|
|
8412
|
+
}
|
|
8413
|
+
|
|
8414
|
+
// src/outlook-sync/outlook-push.ts
|
|
8415
|
+
async function pushAppointmentToOutlook(config, appointmentId) {
|
|
8416
|
+
const appointment = await config.db.appointment.findUnique({
|
|
8417
|
+
where: { id: appointmentId },
|
|
8418
|
+
include: {
|
|
8419
|
+
type: { select: { name: true, slug: true } },
|
|
8420
|
+
calendar: { select: { id: true, outlookCalendarId: true } }
|
|
8421
|
+
}
|
|
8422
|
+
});
|
|
8423
|
+
if (!appointment?.calendar.outlookCalendarId) return null;
|
|
8424
|
+
if (appointment.type.slug === BLOCKED_TYPE_SLUG) return null;
|
|
8425
|
+
const accessToken = await getOutlookAccessToken(config, appointment.calendarId);
|
|
8426
|
+
if (!accessToken) return null;
|
|
8427
|
+
const body = {
|
|
8428
|
+
subject: `${appointment.type.name} \u2014 ${appointment.clientName}`,
|
|
8429
|
+
body: {
|
|
8430
|
+
contentType: "text",
|
|
8431
|
+
content: [
|
|
8432
|
+
`Service: ${appointment.type.name}`,
|
|
8433
|
+
`Duration: ${appointment.duration} min`,
|
|
8434
|
+
appointment.clientPhone ? `Phone: ${appointment.clientPhone}` : "",
|
|
8435
|
+
appointment.clientEmail ? `Email: ${appointment.clientEmail}` : ""
|
|
8436
|
+
].filter(Boolean).join("\n")
|
|
8437
|
+
},
|
|
8438
|
+
// UTC on both sides so the event lands at the stored instant whatever zone the Outlook calendar uses.
|
|
8439
|
+
start: { dateTime: appointment.startTime.toISOString(), timeZone: "UTC" },
|
|
8440
|
+
end: { dateTime: appointment.endTime.toISOString(), timeZone: "UTC" }
|
|
8441
|
+
};
|
|
8442
|
+
const calendarUrl = `${GRAPH_BASE}/me/calendars/${encodeURIComponent(appointment.calendar.outlookCalendarId)}/events`;
|
|
8443
|
+
const isUpdate = Boolean(appointment.outlookEventId);
|
|
8444
|
+
const method = isUpdate ? "PATCH" : "POST";
|
|
8445
|
+
const url = isUpdate ? `${calendarUrl}/${encodeURIComponent(appointment.outlookEventId)}` : calendarUrl;
|
|
8446
|
+
const response = await (config.fetch ?? fetch)(url, {
|
|
8447
|
+
method,
|
|
8448
|
+
headers: { Authorization: `Bearer ${accessToken}`, "Content-Type": "application/json" },
|
|
8449
|
+
body: JSON.stringify(body)
|
|
8450
|
+
});
|
|
8451
|
+
if (!response.ok) throw new Error(`Outlook ${method} event failed with HTTP ${response.status}`);
|
|
8452
|
+
const created = await response.json();
|
|
8453
|
+
if (!isUpdate && created.id) {
|
|
8454
|
+
try {
|
|
8455
|
+
await config.db.appointment.update({ where: { id: appointmentId }, data: { outlookEventId: created.id } });
|
|
8456
|
+
} catch (error) {
|
|
8457
|
+
const removed = await (config.fetch ?? fetch)(`${calendarUrl}/${encodeURIComponent(created.id)}`, {
|
|
8458
|
+
method: "DELETE",
|
|
8459
|
+
headers: { Authorization: `Bearer ${accessToken}` }
|
|
8460
|
+
}).then((r) => r.ok || r.status === 404, () => false);
|
|
8461
|
+
if (!removed) problem(config, "An Outlook event was created but its id could not be saved or the event removed", { appointmentId });
|
|
8462
|
+
throw error;
|
|
8463
|
+
}
|
|
8464
|
+
}
|
|
8465
|
+
return created.id ?? appointment.outlookEventId ?? null;
|
|
8466
|
+
}
|
|
8467
|
+
async function deleteOutlookEvent(config, appointmentId) {
|
|
8468
|
+
const appointment = await config.db.appointment.findUnique({
|
|
8469
|
+
where: { id: appointmentId },
|
|
8470
|
+
select: { outlookEventId: true, calendarId: true, calendar: { select: { outlookCalendarId: true } }, type: { select: { slug: true } } }
|
|
8471
|
+
});
|
|
8472
|
+
if (!appointment?.outlookEventId || !appointment.calendar.outlookCalendarId) return;
|
|
8473
|
+
if (appointment.type.slug === BLOCKED_TYPE_SLUG) return;
|
|
8474
|
+
const accessToken = await getOutlookAccessToken(config, appointment.calendarId);
|
|
8475
|
+
if (!accessToken) return;
|
|
8476
|
+
const response = await (config.fetch ?? fetch)(
|
|
8477
|
+
`${GRAPH_BASE}/me/calendars/${encodeURIComponent(appointment.calendar.outlookCalendarId)}/events/${encodeURIComponent(appointment.outlookEventId)}`,
|
|
8478
|
+
{ method: "DELETE", headers: { Authorization: `Bearer ${accessToken}` } }
|
|
8479
|
+
);
|
|
8480
|
+
if (!response.ok && response.status !== 404) throw new Error(`Outlook DELETE event failed with HTTP ${response.status}`);
|
|
8481
|
+
await config.db.appointment.update({ where: { id: appointmentId }, data: { outlookEventId: null } });
|
|
8482
|
+
}
|
|
8483
|
+
|
|
8484
|
+
// src/outlook-sync/outlook-pull.ts
|
|
8485
|
+
var MAX_PAGES = 200;
|
|
8486
|
+
var withZone = (dateTime) => dateTime.endsWith("Z") ? dateTime : `${dateTime}Z`;
|
|
8487
|
+
async function pullChangesFromOutlook(config, hooks, calendarId) {
|
|
8488
|
+
return pullOnce(config, hooks, calendarId, { isRestart: false, skipWindowCheck: false });
|
|
8489
|
+
}
|
|
8490
|
+
async function pullOnce(config, hooks, calendarId, mode) {
|
|
8491
|
+
const { isRestart } = mode;
|
|
8492
|
+
const { db } = config;
|
|
8493
|
+
const calendar = await db.schedulingCalendar.findUnique({ where: { id: calendarId } });
|
|
8494
|
+
if (!calendar?.outlookCalendarId) return { synced: 0 };
|
|
8495
|
+
const now = (config.now ?? (() => /* @__PURE__ */ new Date()))();
|
|
8496
|
+
const windowIsStale = calendar.lastSyncAt != null && calendar.lastSyncAt.getUTCMonth() !== now.getUTCMonth();
|
|
8497
|
+
if (calendar.outlookSyncToken && windowIsStale && !isRestart && !mode.skipWindowCheck) {
|
|
8498
|
+
if (!await getOutlookAccessToken(config, calendarId)) return { synced: 0 };
|
|
8499
|
+
const drained = await pullOnce(config, hooks, calendarId, { isRestart: false, skipWindowCheck: true });
|
|
8500
|
+
const fresh = await pullOnce(config, hooks, calendarId, { isRestart: true, skipWindowCheck: true, ignoreSavedLink: true });
|
|
8501
|
+
return { synced: drained.synced + fresh.synced };
|
|
8502
|
+
}
|
|
8503
|
+
const accessToken = await getOutlookAccessToken(config, calendarId);
|
|
8504
|
+
if (!accessToken) return { synced: 0 };
|
|
8505
|
+
const headers = { Authorization: `Bearer ${accessToken}`, Prefer: 'outlook.timezone="UTC"' };
|
|
8506
|
+
const horizon = new Date(now);
|
|
8507
|
+
horizon.setUTCFullYear(horizon.getUTCFullYear() + 1);
|
|
8508
|
+
const firstUrl = `${GRAPH_BASE}/me/calendars/${encodeURIComponent(calendar.outlookCalendarId)}/calendarView/delta?startDateTime=${now.toISOString()}&endDateTime=${horizon.toISOString()}`;
|
|
8509
|
+
let url = mode.ignoreSavedLink ? firstUrl : calendar.outlookSyncToken ?? firstUrl;
|
|
8510
|
+
let deltaLink = null;
|
|
8511
|
+
let synced = 0;
|
|
8512
|
+
let unhandled = null;
|
|
8513
|
+
let blockedType = null;
|
|
8514
|
+
for (let pageNumber = 0; url; pageNumber++) {
|
|
8515
|
+
if (pageNumber >= MAX_PAGES) throw new Error("Outlook delta query returned more pages than expected");
|
|
8516
|
+
if (!url.startsWith(`${GRAPH_BASE}/`)) throw new Error("Outlook delta link does not point at Microsoft Graph");
|
|
8517
|
+
const response = await (config.fetch ?? fetch)(url, { headers });
|
|
8518
|
+
if (response.status === 410) {
|
|
8519
|
+
if (isRestart) throw new Error("Outlook delta query was refused with HTTP 410 on a fresh start");
|
|
8520
|
+
problem(config, "Outlook delta link expired; starting a full sync", { calendarId });
|
|
8521
|
+
await db.schedulingCalendar.update({ where: { id: calendarId }, data: { outlookSyncToken: null } });
|
|
8522
|
+
return pullOnce(config, hooks, calendarId, { isRestart: true, skipWindowCheck: true });
|
|
8523
|
+
}
|
|
8524
|
+
if (!response.ok) throw new Error(`Outlook delta query failed with HTTP ${response.status}`);
|
|
8525
|
+
const page = await response.json();
|
|
8526
|
+
for (const event of page.value) {
|
|
8527
|
+
if (!event.id) continue;
|
|
8528
|
+
const existing = await db.appointment.findFirst({ where: { outlookEventId: event.id, calendarId } });
|
|
8529
|
+
if (event["@removed"]) {
|
|
8530
|
+
if (existing && existing.status !== "CANCELLED") {
|
|
8531
|
+
try {
|
|
8532
|
+
if (await hooks.cancelAppointment(existing.id)) synced++;
|
|
8533
|
+
else unhandled ??= new Error(`The host did not cancel appointment ${existing.id}`);
|
|
8534
|
+
} catch (error) {
|
|
8535
|
+
unhandled ??= error instanceof Error ? error : new Error(String(error));
|
|
8536
|
+
problem(config, "Cancelling an appointment deleted in Outlook failed", { appointmentId: existing.id, error: unhandled.message });
|
|
8537
|
+
}
|
|
8538
|
+
}
|
|
8539
|
+
continue;
|
|
8540
|
+
}
|
|
8541
|
+
if (!event.start?.dateTime || !event.end?.dateTime) continue;
|
|
8542
|
+
const startTime = new Date(withZone(event.start.dateTime));
|
|
8543
|
+
const endTime = new Date(withZone(event.end.dateTime));
|
|
8544
|
+
if (Number.isNaN(startTime.getTime()) || Number.isNaN(endTime.getTime()) || endTime <= startTime) continue;
|
|
8545
|
+
const duration = Math.round((endTime.getTime() - startTime.getTime()) / 6e4);
|
|
8546
|
+
if (existing) {
|
|
8547
|
+
if (existing.status === "CANCELLED") continue;
|
|
8548
|
+
const moved = existing.startTime.getTime() !== startTime.getTime() || existing.endTime.getTime() !== endTime.getTime();
|
|
8549
|
+
if (!moved) continue;
|
|
8550
|
+
try {
|
|
8551
|
+
await hooks.onAppointmentMoved?.({ appointmentId: existing.id, organizationId: calendar.organizationId, startTime, endTime });
|
|
8552
|
+
await db.appointment.update({ where: { id: existing.id }, data: { startTime, endTime, duration } });
|
|
8553
|
+
} catch (error) {
|
|
8554
|
+
unhandled ??= error instanceof Error ? error : new Error(String(error));
|
|
8555
|
+
problem(config, "Saving a time changed in Outlook failed", { appointmentId: existing.id, error: unhandled.message });
|
|
8556
|
+
continue;
|
|
8557
|
+
}
|
|
8558
|
+
synced++;
|
|
8559
|
+
continue;
|
|
8560
|
+
}
|
|
8561
|
+
blockedType ??= await findOrCreateBlockedType(config, calendar.organizationId);
|
|
8562
|
+
await db.appointment.create({
|
|
8563
|
+
data: {
|
|
8564
|
+
calendarId,
|
|
8565
|
+
typeId: blockedType.id,
|
|
8566
|
+
startTime,
|
|
8567
|
+
endTime,
|
|
8568
|
+
duration,
|
|
8569
|
+
timezone: calendar.timezone,
|
|
8570
|
+
status: "CONFIRMED",
|
|
8571
|
+
clientName: event.subject || "Blocked",
|
|
8572
|
+
clientEmail: "",
|
|
8573
|
+
outlookEventId: event.id
|
|
8574
|
+
}
|
|
8575
|
+
});
|
|
8576
|
+
synced++;
|
|
8577
|
+
}
|
|
8578
|
+
deltaLink = page["@odata.deltaLink"] ?? null;
|
|
8579
|
+
url = page["@odata.nextLink"] ?? "";
|
|
8580
|
+
}
|
|
8581
|
+
if (unhandled) throw unhandled;
|
|
8582
|
+
if (deltaLink) {
|
|
8583
|
+
const isDrain = mode.skipWindowCheck && !isRestart;
|
|
8584
|
+
await db.schedulingCalendar.update({
|
|
8585
|
+
where: { id: calendarId },
|
|
8586
|
+
data: isDrain ? { outlookSyncToken: deltaLink } : { outlookSyncToken: deltaLink, lastSyncAt: now }
|
|
8587
|
+
});
|
|
8588
|
+
}
|
|
8589
|
+
return { synced };
|
|
8590
|
+
}
|
|
8591
|
+
async function findOrCreateBlockedType(config, organizationId) {
|
|
8592
|
+
const find = () => config.db.appointmentType.findFirst({ where: { slug: BLOCKED_TYPE_SLUG, organizationId } });
|
|
8593
|
+
const found = await find();
|
|
8594
|
+
if (found) return found;
|
|
8595
|
+
try {
|
|
8596
|
+
return await config.db.appointmentType.create({
|
|
8597
|
+
data: {
|
|
8598
|
+
name: "Blocked",
|
|
8599
|
+
slug: BLOCKED_TYPE_SLUG,
|
|
8600
|
+
duration: 60,
|
|
8601
|
+
color: "#6B7280",
|
|
8602
|
+
isActive: false,
|
|
8603
|
+
// never offered for booking
|
|
8604
|
+
organizationId
|
|
8605
|
+
}
|
|
8606
|
+
});
|
|
8607
|
+
} catch (error) {
|
|
8608
|
+
const raced = await find();
|
|
8609
|
+
if (raced) return raced;
|
|
8610
|
+
throw error;
|
|
8611
|
+
}
|
|
8612
|
+
}
|
|
8613
|
+
|
|
8614
|
+
// src/outlook-sync/create-outlook-calendar-sync.ts
|
|
8615
|
+
function createOutlookCalendarSync(config, hooks) {
|
|
8616
|
+
return {
|
|
8617
|
+
adapter: {
|
|
8618
|
+
async upsertEvent(event) {
|
|
8619
|
+
const externalId = await pushAppointmentToOutlook(config, event.appointmentId);
|
|
8620
|
+
return externalId ? { externalId } : {};
|
|
8621
|
+
},
|
|
8622
|
+
async removeEvent(ref) {
|
|
8623
|
+
await deleteOutlookEvent(config, ref.appointmentId);
|
|
8624
|
+
}
|
|
8625
|
+
},
|
|
8626
|
+
pull: async (calendarId) => await pullChangesFromOutlook(config, hooks, calendarId)
|
|
8627
|
+
};
|
|
8628
|
+
}
|
|
8629
|
+
|
|
7725
8630
|
// src/staff/simple-staff.ts
|
|
7726
8631
|
var DEFAULT_ADMIN_ROLES = ["OWNER", "ADMIN", "MANAGER"];
|
|
7727
8632
|
function createStaffContext(input) {
|
|
@@ -7760,6 +8665,47 @@ function createBearerStaffResolver(input) {
|
|
|
7760
8665
|
};
|
|
7761
8666
|
}
|
|
7762
8667
|
|
|
8668
|
+
// src/staff/staff-scope.ts
|
|
8669
|
+
function isCalendarVisibleInScope(calendarUserId, scope) {
|
|
8670
|
+
if (calendarUserId === null) return true;
|
|
8671
|
+
if (scope.mode === "unrestricted") return true;
|
|
8672
|
+
return scope.visibleUserIds.includes(calendarUserId);
|
|
8673
|
+
}
|
|
8674
|
+
function calendarVisibilityFilter(scope) {
|
|
8675
|
+
if (scope.mode === "unrestricted") return void 0;
|
|
8676
|
+
return { OR: [{ userId: { in: scope.visibleUserIds } }, { userId: null }] };
|
|
8677
|
+
}
|
|
8678
|
+
async function visibleCalendarIdsInScope(db, scope) {
|
|
8679
|
+
if (scope.mode === "unrestricted") return void 0;
|
|
8680
|
+
const calendars = await db.schedulingCalendar.findMany({
|
|
8681
|
+
where: { userId: { in: scope.visibleUserIds } },
|
|
8682
|
+
select: { id: true }
|
|
8683
|
+
});
|
|
8684
|
+
return calendars.map((calendar) => calendar.id);
|
|
8685
|
+
}
|
|
8686
|
+
async function canSeeCalendarInScope(db, calendarId, scope) {
|
|
8687
|
+
const [resolved, calendar] = await Promise.all([
|
|
8688
|
+
scope,
|
|
8689
|
+
db.schedulingCalendar.findUnique({ where: { id: calendarId }, select: { userId: true } })
|
|
8690
|
+
]);
|
|
8691
|
+
return calendar != null && isCalendarVisibleInScope(calendar.userId, resolved);
|
|
8692
|
+
}
|
|
8693
|
+
async function canSeeAppointmentInScope(db, appointmentId, scope) {
|
|
8694
|
+
const [resolved, appointment] = await Promise.all([
|
|
8695
|
+
scope,
|
|
8696
|
+
db.appointment.findUnique({ where: { id: appointmentId }, select: { calendar: { select: { userId: true } } } })
|
|
8697
|
+
]);
|
|
8698
|
+
return appointment != null && isCalendarVisibleInScope(appointment.calendar.userId, resolved);
|
|
8699
|
+
}
|
|
8700
|
+
function createScopedVisibility(db, getScope) {
|
|
8701
|
+
return {
|
|
8702
|
+
visibleCalendars: async () => calendarVisibilityFilter(await getScope()) ?? null,
|
|
8703
|
+
visibleCalendarIds: async () => await visibleCalendarIdsInScope(db, await getScope()),
|
|
8704
|
+
canSeeCalendar: async (calendarId) => await canSeeCalendarInScope(db, calendarId, getScope()),
|
|
8705
|
+
canSeeAppointment: async (appointmentId) => await canSeeAppointmentInScope(db, appointmentId, getScope())
|
|
8706
|
+
};
|
|
8707
|
+
}
|
|
8708
|
+
|
|
7763
8709
|
// src/node/node-listener.ts
|
|
7764
8710
|
var CONNECTION_HEADERS = ["host", "connection", "content-length", "transfer-encoding", "keep-alive", "upgrade"];
|
|
7765
8711
|
var PROXY_HEADERS = ["x-forwarded-for", "x-real-ip"];
|
|
@@ -7869,9 +8815,12 @@ export {
|
|
|
7869
8815
|
RouteClientSchema,
|
|
7870
8816
|
SLOT_GRANULARITY_DEFAULT,
|
|
7871
8817
|
SLOT_GRANULARITY_OPTIONS,
|
|
8818
|
+
SmsSendError,
|
|
7872
8819
|
TERMINAL_SUCCESS_STATUSES,
|
|
7873
8820
|
TOKEN_TTL_DAYS,
|
|
8821
|
+
SmsSendError as TelnyxSendError,
|
|
7874
8822
|
TestRoutingFormSchema,
|
|
8823
|
+
TextSettingsSchema,
|
|
7875
8824
|
UnverifiedPaymentError,
|
|
7876
8825
|
UpdateAppointmentCategorySchema,
|
|
7877
8826
|
UpdateAppointmentTypeSchema,
|
|
@@ -7882,7 +8831,13 @@ export {
|
|
|
7882
8831
|
UpdatePackagePurchaseSchema,
|
|
7883
8832
|
UpdateRoutingFormSchema,
|
|
7884
8833
|
UpdateServicePackageSchema,
|
|
8834
|
+
assertStripeTestKey,
|
|
7885
8835
|
attemptLegRefund,
|
|
8836
|
+
calendarVisibilityFilter,
|
|
8837
|
+
canSeeAppointmentInScope,
|
|
8838
|
+
canSeeCalendarInScope,
|
|
8839
|
+
checkSendingDomain,
|
|
8840
|
+
classifyReply,
|
|
7886
8841
|
createBalanceIntent,
|
|
7887
8842
|
createBearerStaffResolver,
|
|
7888
8843
|
createMemoryAvailabilityCache,
|
|
@@ -7891,20 +8846,37 @@ export {
|
|
|
7891
8846
|
createNoBalancePaymentControl,
|
|
7892
8847
|
createNoPaymentAdapter,
|
|
7893
8848
|
createNodeListener,
|
|
8849
|
+
createOutlookCalendarSync,
|
|
8850
|
+
createPerBusinessSmsAdapter,
|
|
7894
8851
|
createSchedulingApi,
|
|
8852
|
+
createScopedVisibility,
|
|
8853
|
+
createSendingDomainVerifier,
|
|
7895
8854
|
createSingleOrganizationDirectory,
|
|
7896
8855
|
createSingleOrganizationResolver,
|
|
7897
8856
|
createStaffContext,
|
|
8857
|
+
createStripePaymentAdapter,
|
|
8858
|
+
createTelnyxSmsAdapter,
|
|
8859
|
+
createTextSettingsResolver,
|
|
8860
|
+
createTwilioSmsAdapter,
|
|
7898
8861
|
decimalToCents,
|
|
7899
8862
|
defaultCorsHeaders,
|
|
7900
8863
|
getErrorCode,
|
|
7901
8864
|
getErrorMessage,
|
|
7902
8865
|
getErrorRef,
|
|
8866
|
+
handleTelnyxWebhook,
|
|
8867
|
+
handleTwilioWebhook,
|
|
8868
|
+
isCalendarVisibleInScope,
|
|
7903
8869
|
isSchedulingServiceError,
|
|
8870
|
+
isSupportedCurrency,
|
|
7904
8871
|
isTokenExpired,
|
|
8872
|
+
normalizePhoneNumber,
|
|
8873
|
+
normalizeSendingDomain,
|
|
7905
8874
|
parsePagination,
|
|
7906
8875
|
persistRefundOutcome,
|
|
7907
8876
|
recordBalanceIntent,
|
|
7908
8877
|
runCalendarRemoveWithoutBlocking,
|
|
7909
|
-
runCalendarSyncWithoutBlocking
|
|
8878
|
+
runCalendarSyncWithoutBlocking,
|
|
8879
|
+
verifyTelnyxSignature,
|
|
8880
|
+
verifyTwilioSignature,
|
|
8881
|
+
visibleCalendarIdsInScope
|
|
7910
8882
|
};
|