@thebookingkit/server 0.1.2 → 0.1.3

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.
Files changed (95) hide show
  1. package/README.md +2 -2
  2. package/dist/adapters/calendar-adapter.d.ts +47 -0
  3. package/dist/adapters/calendar-adapter.d.ts.map +1 -0
  4. package/dist/adapters/calendar-adapter.js +2 -0
  5. package/dist/adapters/calendar-adapter.js.map +1 -0
  6. package/dist/adapters/email-adapter.d.ts +65 -0
  7. package/dist/adapters/email-adapter.d.ts.map +1 -0
  8. package/dist/adapters/email-adapter.js +40 -0
  9. package/dist/adapters/email-adapter.js.map +1 -0
  10. package/dist/adapters/index.d.ts +9 -0
  11. package/dist/adapters/index.d.ts.map +1 -0
  12. package/dist/adapters/index.js +3 -0
  13. package/dist/adapters/index.js.map +1 -0
  14. package/dist/adapters/job-adapter.d.ts +26 -0
  15. package/dist/adapters/job-adapter.d.ts.map +1 -0
  16. package/dist/adapters/job-adapter.js +13 -0
  17. package/dist/adapters/job-adapter.js.map +1 -0
  18. package/dist/adapters/payment-adapter.d.ts +106 -0
  19. package/dist/adapters/payment-adapter.d.ts.map +1 -0
  20. package/dist/adapters/payment-adapter.js +8 -0
  21. package/dist/adapters/payment-adapter.js.map +1 -0
  22. package/dist/adapters/sms-adapter.d.ts +33 -0
  23. package/dist/adapters/sms-adapter.d.ts.map +1 -0
  24. package/dist/adapters/sms-adapter.js +8 -0
  25. package/dist/adapters/sms-adapter.js.map +1 -0
  26. package/{src/adapters/storage-adapter.ts → dist/adapters/storage-adapter.d.ts} +5 -4
  27. package/dist/adapters/storage-adapter.d.ts.map +1 -0
  28. package/dist/adapters/storage-adapter.js +2 -0
  29. package/dist/adapters/storage-adapter.js.map +1 -0
  30. package/dist/api.d.ts +223 -0
  31. package/dist/api.d.ts.map +1 -0
  32. package/dist/api.js +271 -0
  33. package/dist/api.js.map +1 -0
  34. package/dist/auth.d.ts +71 -0
  35. package/dist/auth.d.ts.map +1 -0
  36. package/dist/auth.js +81 -0
  37. package/dist/auth.js.map +1 -0
  38. package/dist/booking-tokens.d.ts +23 -0
  39. package/dist/booking-tokens.d.ts.map +1 -0
  40. package/dist/booking-tokens.js +52 -0
  41. package/dist/booking-tokens.js.map +1 -0
  42. package/dist/email-templates.d.ts +36 -0
  43. package/dist/email-templates.d.ts.map +1 -0
  44. package/{src/email-templates.ts → dist/email-templates.js} +6 -34
  45. package/dist/email-templates.js.map +1 -0
  46. package/dist/index.d.ts +13 -0
  47. package/dist/index.d.ts.map +1 -0
  48. package/dist/index.js +22 -0
  49. package/dist/index.js.map +1 -0
  50. package/dist/multi-tenancy.d.ts +132 -0
  51. package/dist/multi-tenancy.d.ts.map +1 -0
  52. package/dist/multi-tenancy.js +188 -0
  53. package/dist/multi-tenancy.js.map +1 -0
  54. package/dist/notification-jobs.d.ts +143 -0
  55. package/dist/notification-jobs.d.ts.map +1 -0
  56. package/dist/notification-jobs.js +278 -0
  57. package/dist/notification-jobs.js.map +1 -0
  58. package/dist/serialization-retry.d.ts +28 -0
  59. package/dist/serialization-retry.d.ts.map +1 -0
  60. package/dist/serialization-retry.js +71 -0
  61. package/dist/serialization-retry.js.map +1 -0
  62. package/dist/webhooks.d.ts +164 -0
  63. package/dist/webhooks.d.ts.map +1 -0
  64. package/dist/webhooks.js +228 -0
  65. package/dist/webhooks.js.map +1 -0
  66. package/dist/workflows.d.ts +169 -0
  67. package/dist/workflows.d.ts.map +1 -0
  68. package/dist/workflows.js +251 -0
  69. package/dist/workflows.js.map +1 -0
  70. package/package.json +21 -2
  71. package/CHANGELOG.md +0 -9
  72. package/src/__tests__/api.test.ts +0 -354
  73. package/src/__tests__/auth.test.ts +0 -111
  74. package/src/__tests__/concurrent-booking.test.ts +0 -170
  75. package/src/__tests__/multi-tenancy.test.ts +0 -267
  76. package/src/__tests__/serialization-retry.test.ts +0 -76
  77. package/src/__tests__/webhooks.test.ts +0 -412
  78. package/src/__tests__/workflows.test.ts +0 -422
  79. package/src/adapters/calendar-adapter.ts +0 -49
  80. package/src/adapters/email-adapter.ts +0 -108
  81. package/src/adapters/index.ts +0 -36
  82. package/src/adapters/job-adapter.ts +0 -26
  83. package/src/adapters/payment-adapter.ts +0 -118
  84. package/src/adapters/sms-adapter.ts +0 -35
  85. package/src/api.ts +0 -446
  86. package/src/auth.ts +0 -146
  87. package/src/booking-tokens.ts +0 -61
  88. package/src/index.ts +0 -192
  89. package/src/multi-tenancy.ts +0 -301
  90. package/src/notification-jobs.ts +0 -428
  91. package/src/serialization-retry.ts +0 -94
  92. package/src/webhooks.ts +0 -378
  93. package/src/workflows.ts +0 -441
  94. package/tsconfig.json +0 -9
  95. package/vitest.config.ts +0 -7
@@ -1,111 +0,0 @@
1
- import { describe, it, expect, vi } from "vitest";
2
- import {
3
- withAuth,
4
- assertProviderOwnership,
5
- assertCustomerAccess,
6
- UnauthorizedError,
7
- ForbiddenError,
8
- type AuthAdapter,
9
- type AuthUser,
10
- } from "../index.js";
11
-
12
- function mockAdapter(user: AuthUser | null): AuthAdapter {
13
- return {
14
- getCurrentUser: vi.fn().mockResolvedValue(user),
15
- getSession: vi.fn().mockResolvedValue(user ? { user, expires: new Date() } : null),
16
- verifyToken: vi.fn().mockResolvedValue(user),
17
- };
18
- }
19
-
20
- function mockRequest(headers: Record<string, string> = {}): Request {
21
- return new Request("http://localhost/api/test", {
22
- headers: new Headers(headers),
23
- });
24
- }
25
-
26
- describe("withAuth", () => {
27
- it("injects user and calls handler on valid session", async () => {
28
- const user: AuthUser = { id: "user1", email: "test@test.com" };
29
- const adapter = mockAdapter(user);
30
- const handler = vi.fn().mockResolvedValue(Response.json({ ok: true }));
31
-
32
- const wrapped = withAuth(adapter, handler);
33
- const response = await wrapped(mockRequest());
34
-
35
- expect(response.status).toBe(200);
36
- expect(handler).toHaveBeenCalledTimes(1);
37
- const calledReq = handler.mock.calls[0][0];
38
- expect(calledReq.user).toEqual(user);
39
- });
40
-
41
- it("returns 401 when no user is authenticated", async () => {
42
- const adapter = mockAdapter(null);
43
- // verifyToken also returns null
44
- adapter.verifyToken = vi.fn().mockResolvedValue(null);
45
- const handler = vi.fn();
46
-
47
- const wrapped = withAuth(adapter, handler);
48
- const response = await wrapped(mockRequest());
49
-
50
- expect(response.status).toBe(401);
51
- expect(handler).not.toHaveBeenCalled();
52
- });
53
-
54
- it("falls back to Bearer token when session returns null", async () => {
55
- const user: AuthUser = { id: "user2", email: "api@test.com" };
56
- const adapter = mockAdapter(null);
57
- adapter.getCurrentUser = vi.fn().mockResolvedValue(null);
58
- adapter.verifyToken = vi.fn().mockResolvedValue(user);
59
-
60
- const handler = vi.fn().mockResolvedValue(Response.json({ ok: true }));
61
- const wrapped = withAuth(adapter, handler);
62
- const response = await wrapped(
63
- mockRequest({ Authorization: "Bearer test-token-123" }),
64
- );
65
-
66
- expect(response.status).toBe(200);
67
- expect(adapter.verifyToken).toHaveBeenCalledWith("test-token-123");
68
- });
69
-
70
- it("returns 403 when role does not match", async () => {
71
- const user: AuthUser = {
72
- id: "user3",
73
- email: "member@test.com",
74
- role: "customer",
75
- };
76
- const adapter = mockAdapter(user);
77
- const handler = vi.fn();
78
-
79
- const wrapped = withAuth(adapter, handler, { requiredRole: "admin" });
80
- const response = await wrapped(mockRequest());
81
-
82
- expect(response.status).toBe(403);
83
- expect(handler).not.toHaveBeenCalled();
84
- });
85
- });
86
-
87
- describe("assertProviderOwnership", () => {
88
- it("does not throw when user IDs match", () => {
89
- expect(() => assertProviderOwnership("user1", "user1")).not.toThrow();
90
- });
91
-
92
- it("throws ForbiddenError when user IDs do not match", () => {
93
- expect(() => assertProviderOwnership("user1", "user2")).toThrow(
94
- ForbiddenError,
95
- );
96
- });
97
- });
98
-
99
- describe("assertCustomerAccess", () => {
100
- it("does not throw when emails match", () => {
101
- expect(() =>
102
- assertCustomerAccess("a@test.com", "a@test.com"),
103
- ).not.toThrow();
104
- });
105
-
106
- it("throws ForbiddenError when emails do not match", () => {
107
- expect(() =>
108
- assertCustomerAccess("a@test.com", "b@test.com"),
109
- ).toThrow(ForbiddenError);
110
- });
111
- });
@@ -1,170 +0,0 @@
1
- import { describe, it, expect } from "vitest";
2
- import {
3
- withSerializableRetry,
4
- BookingConflictError,
5
- SerializationRetryExhaustedError,
6
- } from "../index.js";
7
-
8
- /**
9
- * Concurrent booking simulation tests.
10
- *
11
- * These tests simulate the load test from E01-S04:
12
- * "50 concurrent booking attempts for the same slot yields exactly 1 confirmed
13
- * booking, 0 unhandled serialization errors, and all other callers receive
14
- * a clear conflict response within 2 seconds."
15
- *
16
- * Since we can't connect to a real Postgres in unit tests, we simulate the
17
- * database behavior with an in-memory "slot lock" that mimics the EXCLUDE
18
- * constraint (SQLSTATE 23P01) and serialization failures (SQLSTATE 40001).
19
- */
20
-
21
- /** Simulates a Postgres error with a SQLSTATE code */
22
- class PgError extends Error {
23
- code: string;
24
- constructor(message: string, code: string) {
25
- super(message);
26
- this.name = "PgError";
27
- this.code = code;
28
- }
29
- }
30
-
31
- describe("Concurrent Booking Simulation (E01-S04 Load Test)", () => {
32
- it("50 concurrent attempts for the same slot: exactly 1 success, rest get conflict", async () => {
33
- // Simulate a database slot that can only be booked once.
34
- // The first successful INSERT wins; subsequent attempts get exclusion_violation.
35
- let slotBooked = false;
36
- let serializationFailureCount = 0;
37
- const maxSimulatedSerializationFailures = 5; // simulate some contention
38
-
39
- const attemptBooking = async (attemptId: number): Promise<string> => {
40
- return withSerializableRetry(
41
- async () => {
42
- // Simulate random serialization failures under contention
43
- if (
44
- !slotBooked &&
45
- serializationFailureCount < maxSimulatedSerializationFailures &&
46
- Math.random() < 0.3
47
- ) {
48
- serializationFailureCount++;
49
- throw new PgError("serialization failure", "40001");
50
- }
51
-
52
- // Simulate the EXCLUDE constraint check
53
- if (slotBooked) {
54
- throw new PgError(
55
- "conflicting key value violates exclusion constraint",
56
- "23P01",
57
- );
58
- }
59
-
60
- // Race: first writer wins
61
- slotBooked = true;
62
- return `booking-${attemptId}`;
63
- },
64
- { maxRetries: 3, baseDelayMs: 10 },
65
- );
66
- };
67
-
68
- const CONCURRENCY = 50;
69
- const results = await Promise.allSettled(
70
- Array.from({ length: CONCURRENCY }, (_, i) => attemptBooking(i)),
71
- );
72
-
73
- const successes = results.filter((r) => r.status === "fulfilled");
74
- const failures = results.filter((r) => r.status === "rejected");
75
-
76
- // Exactly 1 booking should succeed
77
- expect(successes.length).toBe(1);
78
-
79
- // All failures should be BookingConflictError (not unhandled errors)
80
- for (const failure of failures) {
81
- if (failure.status === "rejected") {
82
- expect(failure.reason).toBeInstanceOf(BookingConflictError);
83
- }
84
- }
85
-
86
- // Zero unhandled serialization errors
87
- const serializationErrors = failures.filter(
88
- (f) =>
89
- f.status === "rejected" &&
90
- f.reason instanceof SerializationRetryExhaustedError,
91
- );
92
- expect(serializationErrors.length).toBe(0);
93
- });
94
-
95
- it("completes all 50 attempts within 2 seconds", async () => {
96
- let slotBooked = false;
97
-
98
- const attemptBooking = async (attemptId: number): Promise<string> => {
99
- return withSerializableRetry(
100
- async () => {
101
- if (slotBooked) {
102
- throw new PgError(
103
- "conflicting key value violates exclusion constraint",
104
- "23P01",
105
- );
106
- }
107
- slotBooked = true;
108
- return `booking-${attemptId}`;
109
- },
110
- { maxRetries: 3, baseDelayMs: 10 },
111
- );
112
- };
113
-
114
- const start = Date.now();
115
-
116
- await Promise.allSettled(
117
- Array.from({ length: 50 }, (_, i) => attemptBooking(i)),
118
- );
119
-
120
- const elapsed = Date.now() - start;
121
- expect(elapsed).toBeLessThan(2000);
122
- });
123
-
124
- it("serialization failures are retried and can succeed on a different slot", async () => {
125
- let attempt = 0;
126
-
127
- const result = await withSerializableRetry(
128
- async () => {
129
- attempt++;
130
- if (attempt <= 2) {
131
- throw new PgError("serialization failure", "40001");
132
- }
133
- return "booking-success";
134
- },
135
- { maxRetries: 3, baseDelayMs: 10 },
136
- );
137
-
138
- expect(result).toBe("booking-success");
139
- expect(attempt).toBe(3);
140
- });
141
-
142
- it("retries are exhausted after maxRetries serialization failures", async () => {
143
- const fn = () =>
144
- withSerializableRetry(
145
- async () => {
146
- throw new PgError("serialization failure", "40001");
147
- },
148
- { maxRetries: 3, baseDelayMs: 10 },
149
- );
150
-
151
- await expect(fn()).rejects.toThrow(SerializationRetryExhaustedError);
152
- });
153
-
154
- it("exclusion violation (slot taken) is never retried", async () => {
155
- let callCount = 0;
156
-
157
- const fn = () =>
158
- withSerializableRetry(
159
- async () => {
160
- callCount++;
161
- throw new PgError("exclusion constraint", "23P01");
162
- },
163
- { maxRetries: 3, baseDelayMs: 10 },
164
- );
165
-
166
- await expect(fn()).rejects.toThrow(BookingConflictError);
167
- // Should NOT have retried — only 1 call
168
- expect(callCount).toBe(1);
169
- });
170
- });
@@ -1,267 +0,0 @@
1
- import { describe, it, expect } from "vitest";
2
- import {
3
- resolveEffectiveSettings,
4
- getRolePermissions,
5
- roleHasPermission,
6
- assertOrgPermission,
7
- assertTenantScope,
8
- buildOrgBookingUrl,
9
- parseOrgBookingPath,
10
- TenantAuthorizationError,
11
- GLOBAL_DEFAULTS,
12
- type OrgMember,
13
- type OrgSettings,
14
- type ProviderSettings,
15
- type EventTypeSettings,
16
- } from "../multi-tenancy.js";
17
-
18
- // ---------------------------------------------------------------------------
19
- // resolveEffectiveSettings
20
- // ---------------------------------------------------------------------------
21
-
22
- describe("resolveEffectiveSettings", () => {
23
- it("uses global defaults when no settings provided", () => {
24
- const resolved = resolveEffectiveSettings();
25
- expect(resolved.timezone).toBe(GLOBAL_DEFAULTS.timezone);
26
- expect(resolved.currency).toBe(GLOBAL_DEFAULTS.currency);
27
- expect(resolved.bufferMinutes).toBe(GLOBAL_DEFAULTS.bufferMinutes);
28
- expect(resolved.branding).toEqual({});
29
- expect(resolved.bookingLimits).toEqual({});
30
- });
31
-
32
- it("applies org settings over global defaults", () => {
33
- const org: OrgSettings = {
34
- defaultTimezone: "America/New_York",
35
- defaultCurrency: "EUR",
36
- branding: { primaryColor: "#6366f1" },
37
- };
38
-
39
- const resolved = resolveEffectiveSettings(org);
40
- expect(resolved.timezone).toBe("America/New_York");
41
- expect(resolved.currency).toBe("EUR");
42
- expect(resolved.branding.primaryColor).toBe("#6366f1");
43
- });
44
-
45
- it("provider settings override org settings", () => {
46
- const org: OrgSettings = {
47
- defaultTimezone: "America/New_York",
48
- defaultCurrency: "USD",
49
- };
50
- const provider: ProviderSettings = {
51
- timezone: "Europe/London",
52
- currency: "GBP",
53
- };
54
-
55
- const resolved = resolveEffectiveSettings(org, provider);
56
- expect(resolved.timezone).toBe("Europe/London");
57
- expect(resolved.currency).toBe("GBP");
58
- });
59
-
60
- it("event type settings override provider settings", () => {
61
- const org: OrgSettings = { defaultTimezone: "UTC" };
62
- const provider: ProviderSettings = { timezone: "America/New_York" };
63
- const eventType: EventTypeSettings = { timezone: "Asia/Tokyo" };
64
-
65
- const resolved = resolveEffectiveSettings(org, provider, eventType);
66
- expect(resolved.timezone).toBe("Asia/Tokyo");
67
- });
68
-
69
- it("merges branding settings additively", () => {
70
- const org: OrgSettings = {
71
- branding: { primaryColor: "#000", logoUrl: "https://example.com/logo.png" },
72
- };
73
- const provider: ProviderSettings = {
74
- branding: { primaryColor: "#fff" },
75
- };
76
-
77
- const resolved = resolveEffectiveSettings(org, provider);
78
- expect(resolved.branding.primaryColor).toBe("#fff"); // provider overrides
79
- expect(resolved.branding.logoUrl).toBe("https://example.com/logo.png"); // org preserved
80
- });
81
-
82
- it("merges booking limits additively", () => {
83
- const org: OrgSettings = {
84
- defaultBookingLimits: { maxPerDay: 5 },
85
- };
86
- const provider: ProviderSettings = {
87
- bookingLimits: { maxPerWeek: 20 },
88
- };
89
-
90
- const resolved = resolveEffectiveSettings(org, provider);
91
- expect(resolved.bookingLimits).toMatchObject({ maxPerDay: 5, maxPerWeek: 20 });
92
- });
93
-
94
- it("handles null settings gracefully", () => {
95
- expect(() => resolveEffectiveSettings(null, null, null)).not.toThrow();
96
- });
97
- });
98
-
99
- // ---------------------------------------------------------------------------
100
- // getRolePermissions
101
- // ---------------------------------------------------------------------------
102
-
103
- describe("getRolePermissions", () => {
104
- it("owner has all permissions", () => {
105
- const perms = getRolePermissions("owner");
106
- expect(perms).toContain("manage:members");
107
- expect(perms).toContain("manage:teams");
108
- expect(perms).toContain("view:all-bookings");
109
- expect(perms).toContain("manage:organization");
110
- expect(perms).toContain("view:analytics");
111
- });
112
-
113
- it("admin has management permissions but not member management", () => {
114
- const perms = getRolePermissions("admin");
115
- expect(perms).toContain("manage:teams");
116
- expect(perms).toContain("view:all-bookings");
117
- expect(perms).not.toContain("manage:members");
118
- expect(perms).not.toContain("manage:organization");
119
- });
120
-
121
- it("member has only own-resource permissions", () => {
122
- const perms = getRolePermissions("member");
123
- expect(perms).toContain("view:own-bookings");
124
- expect(perms).toContain("manage:own-availability");
125
- expect(perms).not.toContain("view:all-bookings");
126
- expect(perms).not.toContain("manage:teams");
127
- });
128
- });
129
-
130
- // ---------------------------------------------------------------------------
131
- // roleHasPermission
132
- // ---------------------------------------------------------------------------
133
-
134
- describe("roleHasPermission", () => {
135
- it("returns true for permitted action", () => {
136
- expect(roleHasPermission("owner", "manage:members")).toBe(true);
137
- });
138
-
139
- it("returns false for unpermitted action", () => {
140
- expect(roleHasPermission("member", "manage:members")).toBe(false);
141
- });
142
-
143
- it("admin can view all bookings", () => {
144
- expect(roleHasPermission("admin", "view:all-bookings")).toBe(true);
145
- });
146
- });
147
-
148
- // ---------------------------------------------------------------------------
149
- // assertOrgPermission
150
- // ---------------------------------------------------------------------------
151
-
152
- describe("assertOrgPermission", () => {
153
- const ownerMember: OrgMember = {
154
- userId: "user-1",
155
- organizationId: "org-1",
156
- role: "owner",
157
- };
158
-
159
- const regularMember: OrgMember = {
160
- userId: "user-2",
161
- organizationId: "org-1",
162
- role: "member",
163
- };
164
-
165
- it("does not throw for permitted action", () => {
166
- expect(() =>
167
- assertOrgPermission(ownerMember, "manage:members"),
168
- ).not.toThrow();
169
- });
170
-
171
- it("throws for unpermitted action", () => {
172
- expect(() =>
173
- assertOrgPermission(regularMember, "manage:members"),
174
- ).toThrow(TenantAuthorizationError);
175
- });
176
-
177
- it("throws with descriptive message", () => {
178
- expect(() =>
179
- assertOrgPermission(regularMember, "view:all-bookings"),
180
- ).toThrow('"member"');
181
- });
182
- });
183
-
184
- // ---------------------------------------------------------------------------
185
- // assertTenantScope
186
- // ---------------------------------------------------------------------------
187
-
188
- describe("assertTenantScope", () => {
189
- it("does not throw when org IDs match", () => {
190
- expect(() => assertTenantScope("org-1", "org-1")).not.toThrow();
191
- });
192
-
193
- it("does not throw when resource has no org ID", () => {
194
- expect(() => assertTenantScope(null, "org-1")).not.toThrow();
195
- expect(() => assertTenantScope(undefined, "org-1")).not.toThrow();
196
- });
197
-
198
- it("throws when org IDs don't match", () => {
199
- expect(() => assertTenantScope("org-2", "org-1")).toThrow(
200
- TenantAuthorizationError,
201
- );
202
- expect(() => assertTenantScope("org-2", "org-1")).toThrow(
203
- "does not belong to the current organization",
204
- );
205
- });
206
- });
207
-
208
- // ---------------------------------------------------------------------------
209
- // buildOrgBookingUrl
210
- // ---------------------------------------------------------------------------
211
-
212
- describe("buildOrgBookingUrl", () => {
213
- it("builds the correct URL", () => {
214
- const url = buildOrgBookingUrl(
215
- "acme-corp",
216
- "dr-smith",
217
- "consultation",
218
- "https://booking.example.com",
219
- );
220
- expect(url).toBe(
221
- "https://booking.example.com/acme-corp/dr-smith/consultation",
222
- );
223
- });
224
- });
225
-
226
- // ---------------------------------------------------------------------------
227
- // parseOrgBookingPath
228
- // ---------------------------------------------------------------------------
229
-
230
- describe("parseOrgBookingPath", () => {
231
- it("parses valid path", () => {
232
- const result = parseOrgBookingPath("/acme-corp/dr-smith/consultation");
233
- expect(result).toEqual({
234
- orgSlug: "acme-corp",
235
- providerSlug: "dr-smith",
236
- eventTypeSlug: "consultation",
237
- });
238
- });
239
-
240
- it("returns null for invalid path", () => {
241
- expect(parseOrgBookingPath("/only-two/segments")).toBeNull();
242
- expect(parseOrgBookingPath("/too/many/path/segments")).toBeNull();
243
- expect(parseOrgBookingPath("no-leading-slash")).toBeNull();
244
- });
245
-
246
- it("returns null for empty path", () => {
247
- expect(parseOrgBookingPath("")).toBeNull();
248
- });
249
- });
250
-
251
- // ---------------------------------------------------------------------------
252
- // GLOBAL_DEFAULTS
253
- // ---------------------------------------------------------------------------
254
-
255
- describe("GLOBAL_DEFAULTS", () => {
256
- it("uses UTC timezone", () => {
257
- expect(GLOBAL_DEFAULTS.timezone).toBe("UTC");
258
- });
259
-
260
- it("uses USD currency", () => {
261
- expect(GLOBAL_DEFAULTS.currency).toBe("USD");
262
- });
263
-
264
- it("uses 0 buffer minutes", () => {
265
- expect(GLOBAL_DEFAULTS.bufferMinutes).toBe(0);
266
- });
267
- });
@@ -1,76 +0,0 @@
1
- import { describe, it, expect, vi } from "vitest";
2
- import {
3
- withSerializableRetry,
4
- BookingConflictError,
5
- SerializationRetryExhaustedError,
6
- } from "../index.js";
7
-
8
- function makePostgresError(code: string, message = "pg error") {
9
- const err = new Error(message) as Error & { code: string };
10
- err.code = code;
11
- return err;
12
- }
13
-
14
- describe("withSerializableRetry", () => {
15
- it("returns the result on success", async () => {
16
- const result = await withSerializableRetry(async () => ({ id: "123" }));
17
- expect(result).toEqual({ id: "123" });
18
- });
19
-
20
- it("throws BookingConflictError on exclusion violation (23P01)", async () => {
21
- const fn = vi.fn().mockRejectedValue(makePostgresError("23P01"));
22
-
23
- await expect(withSerializableRetry(fn)).rejects.toThrow(
24
- BookingConflictError,
25
- );
26
- // Should NOT retry on exclusion violation
27
- expect(fn).toHaveBeenCalledTimes(1);
28
- });
29
-
30
- it("retries on serialization failure (40001) and succeeds", async () => {
31
- const fn = vi
32
- .fn()
33
- .mockRejectedValueOnce(makePostgresError("40001"))
34
- .mockRejectedValueOnce(makePostgresError("40001"))
35
- .mockResolvedValueOnce({ id: "456" });
36
-
37
- const result = await withSerializableRetry(fn, {
38
- maxRetries: 3,
39
- baseDelayMs: 1, // fast for tests
40
- });
41
-
42
- expect(result).toEqual({ id: "456" });
43
- expect(fn).toHaveBeenCalledTimes(3);
44
- });
45
-
46
- it("throws SerializationRetryExhaustedError when all retries fail", async () => {
47
- const fn = vi.fn().mockRejectedValue(makePostgresError("40001"));
48
-
49
- await expect(
50
- withSerializableRetry(fn, { maxRetries: 2, baseDelayMs: 1 }),
51
- ).rejects.toThrow(SerializationRetryExhaustedError);
52
-
53
- // Initial attempt + 2 retries = 3 calls
54
- expect(fn).toHaveBeenCalledTimes(3);
55
- });
56
-
57
- it("rethrows unknown errors without retrying", async () => {
58
- const fn = vi.fn().mockRejectedValue(new Error("connection refused"));
59
-
60
- await expect(withSerializableRetry(fn)).rejects.toThrow(
61
- "connection refused",
62
- );
63
- expect(fn).toHaveBeenCalledTimes(1);
64
- });
65
-
66
- it("uses default options (3 retries, 50ms base delay)", async () => {
67
- const fn = vi
68
- .fn()
69
- .mockRejectedValueOnce(makePostgresError("40001"))
70
- .mockResolvedValueOnce("ok");
71
-
72
- const result = await withSerializableRetry(fn);
73
- expect(result).toBe("ok");
74
- expect(fn).toHaveBeenCalledTimes(2);
75
- });
76
- });