@ordinatio/scheduling 0.2.0 → 0.3.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
@@ -902,6 +902,92 @@ var GROUP_SCOPE_ERRORS = {
902
902
  }
903
903
  };
904
904
 
905
+ // src/errors/registry-webhooks.ts
906
+ var WEBHOOK_ERRORS = {
907
+ SCHED_1000: {
908
+ code: "SCHED_1000",
909
+ file: "webhooks/endpoints.ts",
910
+ function: "createWebhookEndpoint",
911
+ severity: "warning",
912
+ recoverable: true,
913
+ description: "The webhook address is not allowed",
914
+ diagnosis: [
915
+ "The address must be a full https:// address with no user name or password",
916
+ "Addresses that point at this machine or a private network are refused",
917
+ "For local development only, the host can allow insecure targets"
918
+ ]
919
+ },
920
+ SCHED_1001: {
921
+ code: "SCHED_1001",
922
+ file: "webhooks/endpoints.ts",
923
+ function: "createWebhookEndpoint",
924
+ severity: "warning",
925
+ recoverable: true,
926
+ description: "The webhook event list is empty or names an event that does not exist",
927
+ diagnosis: [
928
+ 'Send at least one event name, or "*" for every event',
929
+ "Valid names: appointment.booked, appointment.rescheduled, appointment.cancelled, appointment.no_show, reminder.sent"
930
+ ]
931
+ },
932
+ SCHED_1002: {
933
+ code: "SCHED_1002",
934
+ file: "webhooks/endpoints.ts",
935
+ function: "createWebhookEndpoint",
936
+ severity: "warning",
937
+ recoverable: true,
938
+ description: "The organization already has the maximum number of webhook endpoints",
939
+ diagnosis: ["Remove an endpoint that is no longer used, then add the new one"]
940
+ },
941
+ SCHED_1003: {
942
+ code: "SCHED_1003",
943
+ file: "webhooks/endpoints.ts",
944
+ function: "webhook endpoint lookup",
945
+ severity: "warning",
946
+ recoverable: true,
947
+ description: "Webhook endpoint not found for this organization",
948
+ diagnosis: [
949
+ "Check the endpoint id",
950
+ "The endpoint may belong to another organization or may have been removed"
951
+ ]
952
+ },
953
+ SCHED_1004: {
954
+ code: "SCHED_1004",
955
+ file: "webhooks/deliveries.ts",
956
+ function: "retryWebhookDelivery",
957
+ severity: "warning",
958
+ recoverable: true,
959
+ description: "Webhook delivery not found, or it is not in the dead-letter list",
960
+ diagnosis: [
961
+ "Only a delivery that ran out of tries can be retried by hand",
962
+ "A delivery still waiting for its next try will be sent on its own"
963
+ ]
964
+ },
965
+ SCHED_1005: {
966
+ code: "SCHED_1005",
967
+ file: "webhooks/attempt.ts",
968
+ function: "attemptDelivery",
969
+ severity: "warning",
970
+ recoverable: false,
971
+ description: "The webhook was not sent because its target is not allowed",
972
+ diagnosis: [
973
+ "The address, or the address its name resolves to, is on a private or local network",
974
+ "Remove the endpoint and add one that points at a public address"
975
+ ]
976
+ },
977
+ SCHED_1006: {
978
+ code: "SCHED_1006",
979
+ file: "webhooks/enqueue.ts",
980
+ function: "enqueueWebhookEvent",
981
+ severity: "error",
982
+ recoverable: true,
983
+ description: "A webhook event could not be queued; the booking itself was saved",
984
+ diagnosis: [
985
+ "Check that the webhook tables exist (run the package migrations)",
986
+ "Check the database connection"
987
+ ]
988
+ }
989
+ };
990
+
905
991
  // src/errors/registry.ts
906
992
  var SCHEDULING_ERRORS = {
907
993
  ...CALENDARS_AVAILABILITY_ERRORS,
@@ -911,7 +997,8 @@ var SCHEDULING_ERRORS = {
911
997
  ...NOTIFICATION_MANAGE_ERRORS,
912
998
  ...RECURRING_MISC_ERRORS,
913
999
  ...PUBLIC_DIRECTORY_ERRORS,
914
- ...GROUP_SCOPE_ERRORS
1000
+ ...GROUP_SCOPE_ERRORS,
1001
+ ...WEBHOOK_ERRORS
915
1002
  };
916
1003
 
917
1004
  // src/errors/diagnostic-error.ts
@@ -2166,13 +2253,133 @@ function buildNotificationContext(appointment, baseUrl) {
2166
2253
  }
2167
2254
 
2168
2255
  // src/notifications/process-pending-notifications.ts
2169
- import { randomUUID } from "crypto";
2256
+ import { randomUUID as randomUUID2 } from "crypto";
2170
2257
  import { Prisma as Prisma6 } from "@prisma/client";
2258
+
2259
+ // src/webhooks/events.ts
2260
+ import { randomUUID } from "crypto";
2261
+ var WEBHOOK_EVENT_TYPES = [
2262
+ "appointment.booked",
2263
+ "appointment.rescheduled",
2264
+ "appointment.cancelled",
2265
+ "appointment.no_show",
2266
+ "reminder.sent"
2267
+ ];
2268
+ var WEBHOOK_TEST_EVENT = "webhook.test";
2269
+ var ALL_EVENTS = "*";
2270
+ function isWebhookEventType(value) {
2271
+ return typeof value === "string" && WEBHOOK_EVENT_TYPES.includes(value);
2272
+ }
2273
+ function normalizeEventTypes(input) {
2274
+ if (!Array.isArray(input) || input.length === 0) return null;
2275
+ if (input.includes(ALL_EVENTS)) return input.length === 1 ? [ALL_EVENTS] : null;
2276
+ if (!input.every(isWebhookEventType)) return null;
2277
+ return [...new Set(input)];
2278
+ }
2279
+ function buildEnvelope(args) {
2280
+ return {
2281
+ id: args.eventId ?? `evt_${randomUUID()}`,
2282
+ type: args.type,
2283
+ createdAt: args.now.toISOString(),
2284
+ organizationId: args.organizationId,
2285
+ data: args.data
2286
+ };
2287
+ }
2288
+
2289
+ // src/webhooks/enqueue.ts
2290
+ async function appointmentWebhookData(db, organizationId, appointmentId) {
2291
+ const row = await db.appointment.findUnique({
2292
+ where: { id: appointmentId },
2293
+ select: {
2294
+ id: true,
2295
+ status: true,
2296
+ startTime: true,
2297
+ endTime: true,
2298
+ duration: true,
2299
+ timezone: true,
2300
+ clientName: true,
2301
+ clientEmail: true,
2302
+ clientPhone: true,
2303
+ clientId: true,
2304
+ cancelledAt: true,
2305
+ cancelledBy: true,
2306
+ cancelReason: true,
2307
+ rescheduledFrom: true,
2308
+ rescheduleCount: true,
2309
+ calendarId: true,
2310
+ typeId: true,
2311
+ calendar: { select: { name: true, organizationId: true } },
2312
+ type: { select: { name: true } }
2313
+ }
2314
+ });
2315
+ if (!row || row.calendar.organizationId !== null && row.calendar.organizationId !== organizationId) {
2316
+ return { appointment: { id: appointmentId } };
2317
+ }
2318
+ const { calendar, type, ...rest } = row;
2319
+ return { appointment: { ...rest, calendarName: calendar.name, typeName: type.name } };
2320
+ }
2321
+ async function enqueueWebhookEvent(db, input) {
2322
+ const now = input.now ?? /* @__PURE__ */ new Date();
2323
+ const endpoints = await db.webhookEndpoint.findMany({
2324
+ where: {
2325
+ organizationId: input.organizationId,
2326
+ isActive: true,
2327
+ OR: [{ eventTypes: { has: input.type } }, { eventTypes: { has: ALL_EVENTS } }]
2328
+ },
2329
+ select: { id: true }
2330
+ });
2331
+ if (endpoints.length === 0) return { queued: 0 };
2332
+ const envelope = buildEnvelope({ organizationId: input.organizationId, type: input.type, data: input.data, eventId: input.eventId, now });
2333
+ const body = JSON.stringify(envelope);
2334
+ const created = await db.webhookDelivery.createMany({
2335
+ data: endpoints.map((endpoint) => ({
2336
+ organizationId: input.organizationId,
2337
+ endpointId: endpoint.id,
2338
+ eventId: envelope.id,
2339
+ eventType: input.type,
2340
+ body,
2341
+ nextAttemptAt: now
2342
+ })),
2343
+ skipDuplicates: true
2344
+ });
2345
+ return { queued: created.count };
2346
+ }
2347
+ async function enqueueAppointmentWebhook(db, input) {
2348
+ try {
2349
+ const data = { ...await appointmentWebhookData(db, input.organizationId, input.appointmentId), ...input.extra };
2350
+ await enqueueWebhookEvent(db, { organizationId: input.organizationId, type: input.type, data, eventId: input.eventId });
2351
+ } catch (error) {
2352
+ const diagnostic = schedError("SCHED_1006", { organizationId: input.organizationId, type: input.type, appointmentId: input.appointmentId, error });
2353
+ console.error(`[webhooks] ${diagnostic.ref} could not queue ${input.type}:`, error);
2354
+ }
2355
+ }
2356
+ async function enqueueReminderSent(db, notification) {
2357
+ try {
2358
+ const appointment = await db.appointment.findUnique({
2359
+ where: { id: notification.appointmentId },
2360
+ select: { calendar: { select: { organizationId: true } } }
2361
+ });
2362
+ const organizationId = appointment?.calendar.organizationId;
2363
+ if (!organizationId) return;
2364
+ await enqueueAppointmentWebhook(db, {
2365
+ organizationId,
2366
+ type: "reminder.sent",
2367
+ appointmentId: notification.appointmentId,
2368
+ extra: { reminder: { channel: notification.channel, trigger: notification.trigger } },
2369
+ eventId: `reminder_${notification.id}`
2370
+ });
2371
+ } catch (error) {
2372
+ const diagnostic = schedError("SCHED_1006", { appointmentId: notification.appointmentId, error });
2373
+ console.error(`[webhooks] ${diagnostic.ref} could not queue reminder.sent:`, error);
2374
+ }
2375
+ }
2376
+
2377
+ // src/notifications/process-pending-notifications.ts
2171
2378
  async function processPendingNotifications(db, sender, options) {
2172
2379
  const batchSize = options?.batchSize ?? 20;
2173
2380
  const maxRetries = options?.retry?.maxRetries ?? 3;
2174
2381
  const baseBackoff = options?.retry?.baseBackoffMinutes ?? 5;
2175
- const workerId = options?.workerId ?? randomUUID();
2382
+ const workerId = options?.workerId ?? randomUUID2();
2176
2383
  const staleThresholdMs = options?.staleThresholdMs ?? 5 * 6e4;
2177
2384
  const now = /* @__PURE__ */ new Date();
2178
2385
  const staleThreshold = new Date(now.getTime() - staleThresholdMs);
@@ -2234,6 +2441,9 @@ async function processPendingNotifications(db, sender, options) {
2234
2441
  data: { status: "SENT", sentAt: /* @__PURE__ */ new Date() }
2235
2442
  });
2236
2443
  sent++;
2444
+ if (options?.webhooks && notification.trigger.startsWith("REMINDER_")) {
2445
+ await enqueueReminderSent(db, notification);
2446
+ }
2237
2447
  }
2238
2448
  } catch (error) {
2239
2449
  const errorMsg = error instanceof Error ? error.message : "Unknown error";
@@ -3027,6 +3237,7 @@ var DASHBOARD_INCLUDE = {
3027
3237
  calendar: { select: { name: true, staffName: true } }
3028
3238
  };
3029
3239
  var PAGE_SIZE = 20;
3240
+ var UPCOMING_LIMIT = 50;
3030
3241
  var DEFAULT_DASHBOARD_TIMEZONE = "America/Detroit";
3031
3242
  function preciseDayEnd(truncatedEnd) {
3032
3243
  return new Date(truncatedEnd.getTime() + 59e3);
@@ -3077,7 +3288,9 @@ async function getAppointmentDashboard(db, query = {}) {
3077
3288
  weekTotal,
3078
3289
  weekCancelled,
3079
3290
  historyAppointments,
3080
- historyTotal
3291
+ historyTotal,
3292
+ upcomingAppointments,
3293
+ upcomingTotal
3081
3294
  ] = await Promise.all([
3082
3295
  db.appointment.findMany({
3083
3296
  where: withCalendarVisibility({
@@ -3114,12 +3327,29 @@ async function getAppointmentDashboard(db, query = {}) {
3114
3327
  skip: (page - 1) * pageSize,
3115
3328
  take: pageSize
3116
3329
  }),
3117
- db.appointment.count({ where: scopedHistoryWhere })
3330
+ db.appointment.count({ where: scopedHistoryWhere }),
3331
+ db.appointment.findMany({
3332
+ where: withCalendarVisibility({
3333
+ startTime: { gt: weekEnd },
3334
+ status: { not: "CANCELLED" }
3335
+ }, visibleCalendarIds),
3336
+ include: DASHBOARD_INCLUDE,
3337
+ orderBy: { startTime: "asc" },
3338
+ take: UPCOMING_LIMIT
3339
+ }),
3340
+ db.appointment.count({
3341
+ where: withCalendarVisibility({
3342
+ startTime: { gt: weekEnd },
3343
+ status: { not: "CANCELLED" }
3344
+ }, visibleCalendarIds)
3345
+ })
3118
3346
  ]);
3119
3347
  return {
3120
3348
  today: todayAppointments.map(mapToDashboardItem),
3121
3349
  week: weekAppointments.map(mapToDashboardItem),
3122
3350
  history: historyAppointments.map(mapToDashboardItem),
3351
+ upcoming: upcomingAppointments.map(mapToDashboardItem),
3352
+ upcomingTotal,
3123
3353
  stats: {
3124
3354
  todayTotal,
3125
3355
  todayConfirmed: todayTotal - todayCancelled,
@@ -3776,15 +4006,412 @@ async function getTeamAvailableSlots(db, query, _getSlots = getAvailableSlots) {
3776
4006
  timezone: query.timezone ?? firstResult?.timezone ?? "UTC"
3777
4007
  };
3778
4008
  }
4009
+
4010
+ // src/webhooks/signature.ts
4011
+ import { createHmac, randomBytes, timingSafeEqual } from "crypto";
4012
+ var SIGNATURE_HEADER = "x-scheduling-signature";
4013
+ function generateWebhookSecret() {
4014
+ return `whsec_${randomBytes(32).toString("base64url")}`;
4015
+ }
4016
+ function mac(secret, timestamp, body) {
4017
+ return createHmac("sha256", secret).update(`${timestamp}.${body}`).digest("hex");
4018
+ }
4019
+ function signWebhook(args) {
4020
+ const timestamp = Math.floor(args.now.getTime() / 1e3);
4021
+ return `t=${timestamp},v1=${mac(args.secret, timestamp, args.body)}`;
4022
+ }
4023
+ function verifyWebhookSignature(args) {
4024
+ if (!args.header) return false;
4025
+ let timestamp = null;
4026
+ const candidates = [];
4027
+ for (const part of args.header.split(",")) {
4028
+ const [key, value] = part.trim().split("=");
4029
+ if (key === "t" && /^\d{1,12}$/.test(value ?? "")) timestamp = Number(value);
4030
+ if (key === "v1" && value) candidates.push(value);
4031
+ }
4032
+ if (timestamp === null || candidates.length === 0) return false;
4033
+ const tolerance = args.toleranceSeconds ?? 300;
4034
+ const nowSeconds = Math.floor((args.now ?? /* @__PURE__ */ new Date()).getTime() / 1e3);
4035
+ if (Math.abs(nowSeconds - timestamp) > tolerance) return false;
4036
+ const expected = Buffer.from(mac(args.secret, timestamp, args.body), "hex");
4037
+ return candidates.some((candidate) => {
4038
+ const given = Buffer.from(candidate, "hex");
4039
+ return given.length === expected.length && timingSafeEqual(given, expected);
4040
+ });
4041
+ }
4042
+
4043
+ // src/webhooks/url-policy.ts
4044
+ import { isIP } from "net";
4045
+ function v4Parts(ip) {
4046
+ return ip.split(".").map(Number);
4047
+ }
4048
+ function isPrivateV4(ip) {
4049
+ const [a, b, c] = v4Parts(ip);
4050
+ return a === 0 || a === 10 || a === 127 || a === 100 && b >= 64 && b <= 127 || a === 169 && b === 254 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 0 && c === 0 || a === 192 && b === 168 || a === 198 && (b === 18 || b === 19) || a >= 224;
4051
+ }
4052
+ function v6Groups(ip) {
4053
+ let text = ip.toLowerCase().replace(/^\[|\]$/g, "").split("%")[0];
4054
+ const tail = /(\d+\.\d+\.\d+\.\d+)$/.exec(text);
4055
+ if (tail) {
4056
+ const [a, b, c, d] = v4Parts(tail[1]);
4057
+ text = text.slice(0, -tail[1].length) + (a << 8 | b).toString(16) + ":" + (c << 8 | d).toString(16);
4058
+ }
4059
+ const halves = text.split("::");
4060
+ if (halves.length > 2) return null;
4061
+ const head = halves[0] ? halves[0].split(":") : [];
4062
+ const rest = halves.length === 2 && halves[1] ? halves[1].split(":") : [];
4063
+ const missing = 8 - head.length - rest.length;
4064
+ if (halves.length === 1 ? missing !== 0 : missing < 1) return null;
4065
+ const groups = [...head, ...Array(halves.length === 2 ? missing : 0).fill("0"), ...rest].map((g) => parseInt(g, 16));
4066
+ return groups.length === 8 && groups.every((g) => Number.isInteger(g) && g >= 0 && g <= 65535) ? groups : null;
4067
+ }
4068
+ function isPrivateV6(ip) {
4069
+ const g = v6Groups(ip);
4070
+ if (!g) return true;
4071
+ const allZeroUpTo = (n) => g.slice(0, n).every((x) => x === 0);
4072
+ if (allZeroUpTo(7) && g[7] <= 1) return true;
4073
+ if (allZeroUpTo(5) && g[5] === 65535) return isPrivateV4(`${g[6] >> 8}.${g[6] & 255}.${g[7] >> 8}.${g[7] & 255}`);
4074
+ if (allZeroUpTo(6)) return isPrivateV4(`${g[6] >> 8}.${g[6] & 255}.${g[7] >> 8}.${g[7] & 255}`);
4075
+ if (g[0] === 100 && g[1] === 65435) return isPrivateV4(`${g[6] >> 8}.${g[6] & 255}.${g[7] >> 8}.${g[7] & 255}`);
4076
+ return (g[0] & 65024) === 64512 || (g[0] & 65472) === 65152 || (g[0] & 65280) === 65280;
4077
+ }
4078
+ function isPrivateAddress(ip) {
4079
+ const bare = ip.replace(/^\[|\]$/g, "");
4080
+ const kind = isIP(bare);
4081
+ if (kind === 4) return isPrivateV4(bare);
4082
+ if (kind === 6) return isPrivateV6(bare);
4083
+ return true;
4084
+ }
4085
+ var LOCAL_NAME = /(^|\.)(localhost|local|internal|localdomain|home\.arpa)$/;
4086
+ function checkWebhookUrl(raw, options = {}) {
4087
+ let url;
4088
+ try {
4089
+ url = new URL(raw);
4090
+ } catch {
4091
+ return { ok: false, reason: "The address is not a valid web address" };
4092
+ }
4093
+ const insecure = options.allowInsecureTargets === true;
4094
+ if (url.protocol !== "https:" && !(insecure && url.protocol === "http:")) {
4095
+ return { ok: false, reason: "The address must start with https://" };
4096
+ }
4097
+ if (url.username || url.password) {
4098
+ return { ok: false, reason: "The address must not contain a user name or password" };
4099
+ }
4100
+ if (!insecure) {
4101
+ const host = url.hostname.replace(/^\[|\]$/g, "").replace(/\.$/, "");
4102
+ if (LOCAL_NAME.test(host.toLowerCase()) || isIP(host) !== 0 && isPrivateAddress(host)) {
4103
+ return { ok: false, reason: "The address points at a private or local network" };
4104
+ }
4105
+ if (!host.includes(".") && isIP(host) === 0) {
4106
+ return { ok: false, reason: "The address must be a public name with a domain" };
4107
+ }
4108
+ }
4109
+ return { ok: true, url };
4110
+ }
4111
+
4112
+ // src/webhooks/transport.ts
4113
+ import dns from "dns";
4114
+ import http from "http";
4115
+ import https from "https";
4116
+ var BlockedTargetError = class extends Error {
4117
+ constructor(hostname) {
4118
+ super(`Refused to connect to ${hostname}: it resolves to a private or local address`);
4119
+ this.name = "BlockedTargetError";
4120
+ }
4121
+ };
4122
+ function guardedLookup(allowPrivate) {
4123
+ return (hostname, options, callback) => {
4124
+ dns.lookup(hostname, { ...options, all: true }, (error, addresses) => {
4125
+ if (error) return callback(error, "", 0);
4126
+ const list = addresses;
4127
+ if (list.length === 0) return callback(Object.assign(new Error(`No address for ${hostname}`), { code: "ENOTFOUND" }), "", 0);
4128
+ if (!allowPrivate && list.some((a) => isPrivateAddress(a.address))) return callback(new BlockedTargetError(hostname), "", 0);
4129
+ if (options.all) return callback(null, list);
4130
+ callback(null, list[0].address, list[0].family);
4131
+ });
4132
+ };
4133
+ }
4134
+ function createNodeTransport(options = {}) {
4135
+ const allowPrivate = options.allowInsecureTargets === true;
4136
+ return ({ url, headers, body, timeoutMs }) => new Promise((resolve, reject) => {
4137
+ const client = url.protocol === "https:" ? https : http;
4138
+ let settled = false;
4139
+ const finish = (action) => {
4140
+ if (settled) return;
4141
+ settled = true;
4142
+ clearTimeout(timer);
4143
+ action();
4144
+ };
4145
+ const request = client.request(
4146
+ url,
4147
+ {
4148
+ method: "POST",
4149
+ headers: { ...headers, "content-length": String(Buffer.byteLength(body)) },
4150
+ lookup: guardedLookup(allowPrivate),
4151
+ agent: false
4152
+ },
4153
+ (response) => {
4154
+ const status = response.statusCode ?? 0;
4155
+ response.destroy();
4156
+ finish(() => resolve({ status }));
4157
+ }
4158
+ );
4159
+ const timer = setTimeout(() => {
4160
+ request.destroy(new Error(`Timed out after ${timeoutMs} ms`));
4161
+ }, timeoutMs);
4162
+ request.on("error", (error) => finish(() => reject(error)));
4163
+ request.end(body);
4164
+ });
4165
+ }
4166
+
4167
+ // src/webhooks/endpoints.ts
4168
+ var MAX_ENDPOINTS_PER_ORGANIZATION = 20;
4169
+ var VIEW_FIELDS = { id: true, url: true, description: true, eventTypes: true, isActive: true, createdAt: true };
4170
+ async function createWebhookEndpoint(db, input, options = {}) {
4171
+ const checked = checkWebhookUrl(input.url, options);
4172
+ if (!checked.ok) throw new SchedulingValidationError(checked.reason, "SCHED_1000", { url: input.url });
4173
+ const eventTypes = normalizeEventTypes(input.eventTypes);
4174
+ if (!eventTypes) throw new SchedulingValidationError("Choose at least one valid event, or *", "SCHED_1001");
4175
+ const existing = await db.webhookEndpoint.count({ where: { organizationId: input.organizationId } });
4176
+ if (existing >= MAX_ENDPOINTS_PER_ORGANIZATION) {
4177
+ throw new SchedulingValidationError(
4178
+ `An organization can have at most ${MAX_ENDPOINTS_PER_ORGANIZATION} webhook endpoints`,
4179
+ "SCHED_1002",
4180
+ { organizationId: input.organizationId }
4181
+ );
4182
+ }
4183
+ const secret = generateWebhookSecret();
4184
+ const endpoint = await db.webhookEndpoint.create({
4185
+ data: {
4186
+ organizationId: input.organizationId,
4187
+ url: checked.url.toString(),
4188
+ description: input.description?.trim() || null,
4189
+ eventTypes,
4190
+ secret
4191
+ },
4192
+ select: VIEW_FIELDS
4193
+ });
4194
+ return { endpoint, secret };
4195
+ }
4196
+ async function listWebhookEndpoints(db, organizationId) {
4197
+ return db.webhookEndpoint.findMany({ where: { organizationId }, orderBy: { createdAt: "desc" }, select: VIEW_FIELDS });
4198
+ }
4199
+ async function deleteWebhookEndpoint(db, organizationId, endpointId) {
4200
+ const removed = await db.webhookEndpoint.deleteMany({ where: { id: endpointId, organizationId } });
4201
+ if (removed.count === 0) throw new SchedulingNotFoundError("Webhook endpoint not found", "SCHED_1003", { endpointId });
4202
+ }
4203
+
4204
+ // src/webhooks/deliver.ts
4205
+ import { randomUUID as randomUUID3 } from "crypto";
4206
+ import { Prisma as Prisma8 } from "@prisma/client";
4207
+
4208
+ // src/webhooks/attempt.ts
4209
+ var DEFAULT_BACKOFF_SECONDS = [60, 300, 1800, 7200, 21600];
4210
+ var MAX_ERROR_LENGTH = 300;
4211
+ function describe(error) {
4212
+ const code = error.code;
4213
+ const message = error instanceof Error ? error.message : String(error);
4214
+ return (code && !message.includes(code) ? `${code}: ${message}` : message).slice(0, MAX_ERROR_LENGTH);
4215
+ }
4216
+ async function attemptDelivery(db, delivery, workerId, options = {}) {
4217
+ const now = options.now ?? (() => /* @__PURE__ */ new Date());
4218
+ const backoff = options.backoffSeconds ?? DEFAULT_BACKOFF_SECONDS;
4219
+ const maxAttempts = options.maxAttempts ?? backoff.length + 1;
4220
+ const transport = options.transport ?? createNodeTransport({ allowInsecureTargets: options.allowInsecureTargets });
4221
+ const attemptNumber = delivery.attempts + 1;
4222
+ const startedAt = now();
4223
+ let statusCode = null;
4224
+ let error = null;
4225
+ let retryable = true;
4226
+ const target = checkWebhookUrl(delivery.endpoint.url, { allowInsecureTargets: options.allowInsecureTargets });
4227
+ if (!delivery.endpoint.isActive) {
4228
+ error = "The endpoint is switched off";
4229
+ retryable = false;
4230
+ } else if (!target.ok) {
4231
+ error = `${schedError("SCHED_1005", { endpointId: delivery.endpoint.id }).ref}: ${target.reason}`;
4232
+ retryable = false;
4233
+ } else {
4234
+ try {
4235
+ const response = await transport({
4236
+ url: target.url,
4237
+ timeoutMs: options.timeoutMs ?? 1e4,
4238
+ body: delivery.body,
4239
+ headers: {
4240
+ "content-type": "application/json",
4241
+ "user-agent": "scheduling-webhooks/1",
4242
+ "x-scheduling-event": delivery.eventType,
4243
+ "x-scheduling-delivery": delivery.id,
4244
+ [SIGNATURE_HEADER]: signWebhook({ secret: delivery.endpoint.secret, body: delivery.body, now: startedAt })
4245
+ }
4246
+ });
4247
+ statusCode = response.status;
4248
+ if (response.status < 200 || response.status >= 300) error = `The receiver answered HTTP ${response.status}`;
4249
+ } catch (caught) {
4250
+ error = describe(caught);
4251
+ retryable = caught.name !== "BlockedTargetError";
4252
+ }
4253
+ }
4254
+ const finishedAt = now();
4255
+ const succeeded = error === null;
4256
+ const exhausted = !retryable || attemptNumber >= maxAttempts;
4257
+ const outcome = succeeded ? "SUCCEEDED" : exhausted ? "DEAD_LETTER" : "RETRY";
4258
+ const updated = await db.webhookDelivery.updateMany({
4259
+ where: { id: delivery.id, organizationId: delivery.organizationId, status: "PROCESSING", processingId: workerId },
4260
+ data: {
4261
+ status: outcome === "SUCCEEDED" ? "SUCCEEDED" : outcome === "DEAD_LETTER" ? "DEAD_LETTER" : "PENDING",
4262
+ attempts: attemptNumber,
4263
+ lastStatusCode: statusCode,
4264
+ lastError: error,
4265
+ deliveredAt: succeeded ? finishedAt : null,
4266
+ nextAttemptAt: outcome === "RETRY" ? new Date(finishedAt.getTime() + backoff[Math.min(attemptNumber - 1, backoff.length - 1)] * 1e3) : void 0,
4267
+ processingId: null,
4268
+ claimedAt: null
4269
+ }
4270
+ });
4271
+ if (updated.count === 0) return { outcome: "LOST_CLAIM", statusCode, error };
4272
+ await db.webhookAttempt.create({
4273
+ data: { deliveryId: delivery.id, attemptNumber, statusCode, error, durationMs: Math.max(0, finishedAt.getTime() - startedAt.getTime()) }
4274
+ });
4275
+ return { outcome, statusCode, error };
4276
+ }
4277
+
4278
+ // src/webhooks/deliver.ts
4279
+ async function deliverDueWebhooks(db, options = {}) {
4280
+ const now = (options.now ?? (() => /* @__PURE__ */ new Date()))();
4281
+ const batchSize = Math.max(1, Math.min(200, Math.floor(options.batchSize ?? 20)));
4282
+ const concurrency = Math.max(1, Math.floor(options.concurrency ?? 5));
4283
+ const workerId = options.workerId ?? randomUUID3();
4284
+ const staleBefore = new Date(now.getTime() - (options.staleClaimMs ?? 5 * 6e4));
4285
+ const claimed = await db.$queryRaw`
4286
+ WITH candidates AS (
4287
+ SELECT id FROM "WebhookDelivery"
4288
+ WHERE (status = 'PENDING' AND "nextAttemptAt" <= ${now})
4289
+ OR (status = 'PROCESSING' AND "claimedAt" < ${staleBefore})
4290
+ ORDER BY "nextAttemptAt" ASC
4291
+ LIMIT ${Prisma8.raw(String(batchSize))}
4292
+ FOR UPDATE SKIP LOCKED
4293
+ )
4294
+ UPDATE "WebhookDelivery" d
4295
+ SET status = 'PROCESSING', "processingId" = ${workerId}, "claimedAt" = ${now}
4296
+ FROM candidates
4297
+ WHERE d.id = candidates.id
4298
+ RETURNING d.id
4299
+ `;
4300
+ const summary = { succeeded: 0, retried: 0, deadLettered: 0, lostClaim: 0 };
4301
+ if (claimed.length === 0) return summary;
4302
+ const rows = await db.webhookDelivery.findMany({
4303
+ where: { id: { in: claimed.map((c) => c.id) }, processingId: workerId },
4304
+ select: {
4305
+ id: true,
4306
+ organizationId: true,
4307
+ eventId: true,
4308
+ eventType: true,
4309
+ body: true,
4310
+ attempts: true,
4311
+ endpoint: { select: { id: true, url: true, secret: true, isActive: true } }
4312
+ }
4313
+ });
4314
+ for (let i = 0; i < rows.length; i += concurrency) {
4315
+ const results = await Promise.all(rows.slice(i, i + concurrency).map((row) => attemptDelivery(db, row, workerId, options)));
4316
+ for (const { outcome } of results) {
4317
+ if (outcome === "SUCCEEDED") summary.succeeded++;
4318
+ else if (outcome === "RETRY") summary.retried++;
4319
+ else if (outcome === "DEAD_LETTER") summary.deadLettered++;
4320
+ else summary.lostClaim++;
4321
+ }
4322
+ }
4323
+ return summary;
4324
+ }
4325
+
4326
+ // src/webhooks/test-send.ts
4327
+ import { randomUUID as randomUUID4 } from "crypto";
4328
+ async function sendTestWebhook(db, input, options = {}) {
4329
+ const endpoint = await db.webhookEndpoint.findFirst({
4330
+ where: { id: input.endpointId, organizationId: input.organizationId },
4331
+ select: { id: true, url: true, secret: true, isActive: true }
4332
+ });
4333
+ if (!endpoint) throw new SchedulingNotFoundError("Webhook endpoint not found", "SCHED_1003", { endpointId: input.endpointId });
4334
+ const now = (options.now ?? (() => /* @__PURE__ */ new Date()))();
4335
+ const workerId = randomUUID4();
4336
+ const envelope = buildEnvelope({
4337
+ organizationId: input.organizationId,
4338
+ type: WEBHOOK_TEST_EVENT,
4339
+ data: { message: "This is a test event from your scheduling system." },
4340
+ now
4341
+ });
4342
+ const created = await db.webhookDelivery.create({
4343
+ data: {
4344
+ organizationId: input.organizationId,
4345
+ endpointId: endpoint.id,
4346
+ eventId: envelope.id,
4347
+ eventType: WEBHOOK_TEST_EVENT,
4348
+ body: JSON.stringify(envelope),
4349
+ status: "PROCESSING",
4350
+ processingId: workerId,
4351
+ claimedAt: now,
4352
+ nextAttemptAt: now
4353
+ },
4354
+ select: { id: true, organizationId: true, eventId: true, eventType: true, body: true, attempts: true }
4355
+ });
4356
+ const result = await attemptDelivery(db, { ...created, endpoint }, workerId, { ...options, maxAttempts: 1 });
4357
+ return { deliveryId: created.id, ok: result.outcome === "SUCCEEDED", statusCode: result.statusCode, error: result.error };
4358
+ }
4359
+
4360
+ // src/webhooks/deliveries.ts
4361
+ async function listWebhookDeliveries(db, input) {
4362
+ const where = {
4363
+ organizationId: input.organizationId,
4364
+ ...input.endpointId ? { endpointId: input.endpointId } : {},
4365
+ ...input.status ? { status: input.status } : {}
4366
+ };
4367
+ const [deliveries, total] = await Promise.all([
4368
+ db.webhookDelivery.findMany({
4369
+ where,
4370
+ orderBy: { createdAt: "desc" },
4371
+ take: Math.min(input.limit ?? 50, 200),
4372
+ skip: input.offset ?? 0,
4373
+ select: {
4374
+ id: true,
4375
+ endpointId: true,
4376
+ eventId: true,
4377
+ eventType: true,
4378
+ status: true,
4379
+ attempts: true,
4380
+ nextAttemptAt: true,
4381
+ lastStatusCode: true,
4382
+ lastError: true,
4383
+ deliveredAt: true,
4384
+ createdAt: true,
4385
+ attemptLog: { orderBy: { attemptNumber: "desc" }, take: 10, select: { attemptNumber: true, statusCode: true, error: true, durationMs: true, createdAt: true } }
4386
+ }
4387
+ }),
4388
+ db.webhookDelivery.count({ where })
4389
+ ]);
4390
+ return { deliveries, total };
4391
+ }
4392
+ async function retryWebhookDelivery(db, organizationId, deliveryId, now = /* @__PURE__ */ new Date()) {
4393
+ const updated = await db.webhookDelivery.updateMany({
4394
+ where: { id: deliveryId, organizationId, status: "DEAD_LETTER" },
4395
+ data: { status: "PENDING", attempts: 0, nextAttemptAt: now, processingId: null, claimedAt: null }
4396
+ });
4397
+ if (updated.count === 0) throw new SchedulingNotFoundError("Delivery not found or not in the dead-letter list", "SCHED_1004", { deliveryId });
4398
+ }
3779
4399
  export {
4400
+ BlockedTargetError,
4401
+ DEFAULT_BACKOFF_SECONDS,
4402
+ MAX_ENDPOINTS_PER_ORGANIZATION,
3780
4403
  RECURRING_MAX_OCCURRENCES,
3781
4404
  SCHEDULING_ERRORS,
4405
+ SIGNATURE_HEADER,
3782
4406
  SchedulingNotFoundError,
3783
4407
  SchedulingValidationError,
3784
4408
  USER_DAY_LIMIT,
4409
+ WEBHOOK_EVENT_TYPES,
4410
+ WEBHOOK_TEST_EVENT,
3785
4411
  adaptersToCallbacks,
3786
4412
  addDateOverride,
3787
4413
  addTimeBlock,
4414
+ appointmentWebhookData,
3788
4415
  archiveCalendar,
3789
4416
  bookAppointment,
3790
4417
  buildJitsiUrl,
@@ -3799,13 +4426,22 @@ export {
3799
4426
  checkClockContract,
3800
4427
  checkNotificationContract,
3801
4428
  checkPaymentContract,
4429
+ checkWebhookUrl,
3802
4430
  createAppointmentType,
3803
4431
  createCalendar,
3804
4432
  createInMemoryAdapters,
4433
+ createNodeTransport,
3805
4434
  createNotificationTemplate,
4435
+ createWebhookEndpoint,
3806
4436
  deleteCalendar,
3807
4437
  deleteNotificationTemplate,
4438
+ deleteWebhookEndpoint,
4439
+ deliverDueWebhooks,
4440
+ enqueueAppointmentWebhook,
4441
+ enqueueReminderSent,
4442
+ enqueueWebhookEvent,
3808
4443
  generateOccurrenceDates,
4444
+ generateWebhookSecret,
3809
4445
  getAppointment,
3810
4446
  getAppointmentDashboard,
3811
4447
  getAppointmentType,
@@ -3819,6 +4455,7 @@ export {
3819
4455
  getNotificationTemplate,
3820
4456
  getTeamAvailableSlots,
3821
4457
  getUserDayAppointments,
4458
+ isPrivateAddress,
3822
4459
  isSlotAvailable,
3823
4460
  isVirtualMeeting,
3824
4461
  listAppointmentTypes,
@@ -3826,6 +4463,8 @@ export {
3826
4463
  listAvailabilityRules,
3827
4464
  listCalendars,
3828
4465
  listNotificationTemplates,
4466
+ listWebhookDeliveries,
4467
+ listWebhookEndpoints,
3829
4468
  localToUTC,
3830
4469
  markNoShow,
3831
4470
  parseTimeLocal,
@@ -3836,12 +4475,16 @@ export {
3836
4475
  renderTemplate,
3837
4476
  rescheduleAppointment,
3838
4477
  resolveLocation,
4478
+ retryWebhookDelivery,
3839
4479
  schedError,
3840
4480
  scheduleNotifications,
3841
4481
  selectCalendarForBooking,
4482
+ sendTestWebhook,
3842
4483
  setWeeklyAvailability,
4484
+ signWebhook,
3843
4485
  updateAppointmentType,
3844
4486
  updateCalendar,
3845
4487
  updateNotificationTemplate,
4488
+ verifyWebhookSignature,
3846
4489
  withCalendarVisibility
3847
4490
  };