Open-Source Wikis

/

Cal.com

/

Packages

/

lib

calcom/cal.com

lib

Purpose

packages/lib is the shared utility layer that almost every other package imports from. It is the closest thing the codebase has to a "core" module: small, mostly-pure helpers for dates, calendars, encryption, error handling, fetch wrappers, OG-image generation, IP/SSRF protection, and a hundred other small things.

Directory layout (selected highlights)

lib/
├── CalendarService.ts (37 KB)        # Base Calendar adapter that other providers extend
├── CalendarService.test.ts
├── CalEventParser.ts (19 KB)         # Parses Cal.com events to/from vendor formats
├── constants.ts (14 KB)              # Project-wide constants (timeouts, URLs, ...)
├── crypto.ts                         # AES + HMAC helpers (uses CALENDSO_ENCRYPTION_KEY)
├── dayjs/                            # Pre-configured Day.js bundle
├── default-cookies.ts                # NextAuth cookie config
├── delegationCredential.ts           # Domain-wide credential helpers
├── errorCodes.ts                     # Canonical ErrorWithCode + error-code list
├── errors.ts                         # ErrorWithCode base class
├── fetch-wrapper.ts                  # Logging fetch wrapper used by app-store adapters
├── getIP.ts / getIP.test.ts          # Client IP extraction (X-Forwarded-For aware)
├── getSafeRedirectUrl.ts             # Validate redirect URLs against an allowlist
├── http-error.ts                     # HTTP error envelope for Pages Router
├── isOutOfBounds.tsx (14 KB)         # Time-zone-aware bounds check for event types
├── logger.ts / logger.server.ts      # tslog wrappers
├── markdownToSafeHTML.ts             # Sanitized markdown rendering
├── piiFreeData.ts                    # PII redaction
├── rateLimit.ts                      # Per-IP rate limiter (Redis)
├── redactError.ts / redactSensitiveData.ts
├── sentryWrapper.ts                  # Sentry helpers (capture w/ tags, span helpers)
├── ssrfProtection.ts (7 KB)          # Block private-IP / loopback / internal hostnames
├── slugify.ts                        # URL-safe slugs
├── timeFormat.ts / timeZones.ts / timezone.ts / timezoneConstants.ts
├── totp.ts                           # TOTP for 2FA
├── unstable_cache/                   # Wrapper around Next.js cache primitives
├── webstorage.ts                     # localStorage helpers w/ quota handling
├── parse-dates.ts / parse-zone.ts
├── apps/                             # App-store-related helpers
├── auth/                             # Auth helpers shared across modules
├── bookings/                         # Booking helpers reused outside features/bookings
├── builders/                         # Builder pattern helpers (event payload, ...)
├── crmManager/                       # CRM dispatch helpers
├── domainManager/
├── dto/                              # Data transfer object helpers
├── hooks/                            # React hooks
├── intervalLimits/                   # Booking limits (per day/week/month)
├── server/                           # Server-only utilities
├── service/
├── sync/                             # External sync helpers
├── tasker/                           # Tasker types
├── tracing/, tracking/               # Observability helpers
└── zod/                              # Zod helpers

The 30+ subdirectories all live in the same workspace; they exist purely to group helpers.

Key abstractions

Symbol File Purpose
BaseCalendarService packages/lib/CalendarService.ts Concrete base class for calendar app-store adapters. Implements OAuth refresh, error handling, and the shared Calendar interface from packages/types/Calendar.d.ts.
CalEventParser packages/lib/CalEventParser.ts Marshals between Cal.com's internal event shape and vendor formats. Used by every calendar adapter.
ErrorWithCode packages/lib/errors.ts + errorCodes.ts The error class everything outside tRPC throws. Adds a machine-readable code.
getIP packages/lib/getIP.ts Returns the real client IP, X-Forwarded-For aware. Used by rate limiter and audit logs.
ssrfProtection packages/lib/ssrfProtection.ts Blocks SSRF on outbound fetches by rejecting private/loopback addresses.
getSafeRedirectUrl packages/lib/getSafeRedirectUrl.ts Validates a redirect URL against the configured allowlist. Used after auth.
redactSensitiveData packages/lib/redactSensitiveData.ts Strips passwords, tokens, and credential keys from log output.
crypto packages/lib/crypto.ts AES-256-CBC encrypt/decrypt using CALENDSO_ENCRYPTION_KEY. Wraps Credential.key.
markdownToSafeHTML packages/lib/markdownToSafeHTML.ts Parses markdown with markdown-it, sanitizes with DOMPurify, and renders.
rateLimit packages/lib/rateLimit.ts Redis-backed token-bucket limiter shared by tRPC + Pages-Router APIs.
Constants packages/lib/constants.ts Centralized constants imported by hundreds of files.
unstable_cache packages/lib/unstable_cache/ Project-internal wrapper around the Next.js cache so it can be swapped for tests.

How it works

lib is purely "leaf" code — it must not import from features/, trpc/, or apps/ (the dependency layer would otherwise cycle). It does import from prisma, types, and external dependencies. The pattern is:

graph LR
    Lib[packages/lib] --> Prisma[packages/prisma]
    Lib --> Types[packages/types]
    Lib --> External[Day.js, Zod, Sentry, ...]
    Features[packages/features/*] --> Lib
    AppStore[packages/app-store/*] --> Lib
    UI[packages/ui] --> Lib
    Apps[apps/*] --> Lib

Integration points

  • App-store adapters extend BaseCalendarService and call CalEventParser.
  • NextAuth uses default-cookies.ts and helpers from lib/auth/.
  • Booking pipeline depends on isOutOfBounds, intervalLimits/, parse-dates, and the Day.js plugin set in lib/dayjs.
  • Sentry integration calls into sentryWrapper.ts from both web and api/v2.
  • apps/api/v2 consumes lib helpers indirectly via packages/platform/libraries.

Entry points for modification

  • Adding a utility: drop a single-purpose file with a colocated *.test.ts. Avoid mega-files; the team's culture leans toward many small modules.
  • Cross-cutting concern (logging, redaction, etc.): extend the existing helper rather than introducing a parallel one. logger.ts, redactSensitiveData.ts, and sentryWrapper.ts are intentionally the only modules of their kind.
  • features — depends heavily on lib
  • primitives
  • securityssrfProtection, getSafeRedirectUrl, redactSensitiveData originate here

Built by Factory AutoWiki from public repository content. It is a generated preview for codebase exploration, not source-maintained documentation.

lib – Cal.com wiki | Factory