Zap Studio

repository·main·Indexed 41 days ago

https://github.com/zap-studio/monorepo

A suite of type-safe, framework-agnostic, and tree-shakeable TypeScript libraries for web development. The monorepo includes @zap-studio/cache for in-memory key-value caching with multiple eviction policies, @zap-studio/fetch for schema-validated API requests, @zap-studio/logger for runtime-agnostic logging with OpenTelemetry support, and @zap-studio/monads for functional error and null handling using Result, Option, and ResultAsync.

Tokens
161K
Snippets
576
Records
754
Agent score
48%

What's inside Zap Studio

  1. Overview of Zap Studio packages

    main

    Zap Studio provides small, standalone, framework-agnostic TypeScript packages. Each package can be used independently or composed together.

    PackageDescription
    @zap-studio/cacheIn-memory cache with pluggable eviction and optional TTL
    @zap-studio/envTyped, validated env vars with server/client/shared split
    @zap-studio/fetchTyped responses from any API without manual casts
    @zap-studio/loggerStructured logs for console or various backends
    @zap-studio/monadsErrors as values that must be handled
    @zap-studio/oxfmtStandardized import and package.json ordering
    @zap-studio/oxlintZero-config linting presets for specific stacks
    @zap-studio/permitCentralized, auditable permission checks
    @zap-studio/react-hooksFocused, tree-shakeable React hooks
    @zap-studio/retryRetry logic with backoff, jitter, and cancellation
    @zap-studio/storeState management with derived values and built-in persistence
    @zap-studio/validationUnified validation error shape for any schema library
    @zap-studio/webhooksVerified and routed webhooks
    @zap-studio/webmcpSSR-safe tool registration for WebMCP browser API
  2. Overview of @zap-studio/react-hooks

    main

    The @zap-studio/react-hooks package provides a collection of over 100 small, focused, and tree-shakeable React hooks.

    Key features include:

    • SSR and Hydration Safety: Hooks are designed to be safe for Server-Side Rendering (SSR). They avoid direct access to window, document, or navigator outside of effects or guarded checks, preventing server-side crashes and hydration mismatches.
    • Tree-shaking: Each hook is a standalone, side-effect-free module. You can import hooks via their specific subpaths to ensure you only bundle the code you actually use.
    • High Reliability: Hooks are built to wrap complex browser APIs (like IntersectionObserver, ResizeObserver, and various Web APIs) with correct cleanup logic to prevent memory leaks and listener leaks.
  3. Debug and observability hooks in @zap-studio/react-hooks

    main

    The @zap-studio/react-hooks package provides several diagnostic hooks for monitoring component renders and performance.

    Important Behaviors:

    • Production Safety: All debug hooks automatically turn themselves off in production builds to avoid performance overhead and security risks.
    • Unstable Hooks: Hooks prefixed with useUnstable (specifically useUnstableFiber and useUnstableRenderReason) access React's private, undocumented Fiber tree. These are not guaranteed to work across React versions and carry an Unstable marker to warn users of this risk.
    • Stable Hooks: Hooks like useRenderCount, useWhyDidYouUpdate, and useIsFirstRender use only public React APIs and are safe to use without the Unstable warning.
  4. Core Features of @zap-studio/env

    main

    The @zap-studio/env package provides several key capabilities for managing environment variables:

    • Full type safety: The parsed environment object is automatically inferred from your schemas.
    • Standard Schema support: Compatible with Zod, Valibot, ArkType, and other Standard Schema-compliant libraries.
    • server/client/shared split: Enforces access boundaries. Use clientPrefix to define which keys are safe for the client.
    • Schema composition via extends: Allows merging schemas with reference-equality conflict detection (throws if keys conflict with different schemas).
    • Platform presets: Built-in support for common hosting providers including Cloudflare Workers and Deno Deploy.
    • .env.example generation: Automatically build a .env.example file from your schema using generateEnvironmentExample().
    • Structured errors: Provides specific error types: EnvironmentError, EnvironmentValidationError, and EnvironmentAccessError.
    • OpenTelemetry support: Includes a zero-cost env.validate span for observability.
    • Tree-shakeable: Designed as plain functions and objects for minimal bundle size.
  5. Core Features of @zap-studio/webhooks

    main

    The @zap-studio/webhooks package provides several key capabilities for webhook management:

    • Web API Native: Uses standard Request and Response objects, making it compatible with Bun, Deno, Cloudflare Workers, Next.js, and Hono.
    • Type-safe Routing: Handler payload types are automatically inferred from the route schema.
    • Standard Schema Validation: Supports any library compatible with the Standard Schema specification, such as Zod, Valibot, or ArkType.
    • Signature Verification: Includes a built-in HMAC verifier using the Web Crypto API (globalThis.crypto.subtle) with constant-time comparison to prevent timing attacks. You can also provide a custom verify function.
    • Lifecycle Hooks: Provides before, after, and onError hooks for cross-cutting concerns.
    • Observability: Supports optional logging via @zap-studio/logger and native OpenTelemetry integration (providing SERVER and handler dispatch spans).
    • Tree-shakeable: Designed to allow bundlers to drop unused validation and hook-running internals.
  6. Core Features of @zap-studio/fetch

    main

    The @zap-studio/fetch package provides several modes and utilities for handling HTTP requests:

    • Validated fetch mode: Use $fetch(input, schema, options) to parse and validate the JSON response against a schema.
    • Raw fetch mode: Use $fetch(input, options) to behave like the native fetch API, returning a Response object.
    • HTTP method helpers: Use api.get, api.post, api.put, api.patch, and api.delete for common verbs.
    • Configured clients: Use createFetch(...) to create a client with shared baseURL, headers, query params, and error defaults.
    • JSON convenience: Use the json option to automatically serialize the request body and set the Content-Type header.
    • Structured errors:
      • FetchError: Thrown on bad HTTP status codes.
      • ValidationError: Thrown when the response body fails schema validation.
    • Validator-agnostic: Works with any library implementing the Standard Schema (e.g., Zod, Valibot).
    • Observability: Supports optional logging via createFetch({ logger }) and native OpenTelemetry for distributed tracing.
  7. Available Hooks in @zap-studio/react-hooks

    main

    The @zap-studio/react-hooks package provides a comprehensive collection of React hooks categorized by their functional domain. Every hook is also importable from its own category subpath (e.g., import { useMediaQuery } from '@zap-studio/react-hooks/sensors').

    Categories and Hook Groups

    Sensors (sensors/)

    Used for detecting environmental and device states (e.g., useMediaQuery, useIsMobile, useColorScheme, useOnlineStatus, useWindowSize, useGeolocation, useDeviceOrientation). Many experimental sensors are available for Chromium-only environments.

    DOM / Element Interaction (dom/)

    Used for interacting with the DOM and elements (e.g., useClickOutside, useHover, useIntersectionObserver, useResizeObserver, useEventListener, useLockBodyScroll, useFullscreen).

    Input (input/)

    Used for handling user input events (e.g., useKeyPress, useHotkeys, useIdle, useGamepad, usePointerLock).

    Media (media/)

    Used for audio, video, and speech APIs (e.g., useUserMedia, useCamera, useScreenCapture, useMediaRecorder, useSpeechSynthesis, usePictureInPicture).

    History & Navigation (navigation/)

    Used for managing browser history and navigation (e.g., usePopState, useNavigationType, useNavigation, useNavigationBlocker).

    Network (network/)

    Used for real-time communication protocols (e.g., useWebSocket, useEventSource, useWebTransport).

    PWA (pwa/)

    Used for Progressive Web App features (e.g., useInstallPrompt, useServiceWorker, useAppBadge, useStandaloneMode).

    Commerce (commerce/)

    Used for payment integrations (e.g., usePaymentRequest).

    Lifecycle (lifecycle/)

    Used for managing component and asynchronous lifecycles (e.g., useMount, useUnmount, useUpdateEffect, useAsync, useTimeout, useInterval, useWorker).

    State (state/)

    Used for managing application state and synchronization (e.g., useToggle, useDebounce, useLocalStorage, useIndexedDB, useSearchParams, useHistoryState, useBroadcastChannel).

    Debug / Observability (debug/)

    Used for profiling and debugging React components (e.g., useRenderCount, useWhyDidYouUpdate, useIsFirstRender, useRenderDuration).

  8. What is ResultAsync?

    main
    In @zap-studio/monads, ResultAsync<T, E> is a thenable wrapper around Promise<Result<T, E>>. It is designed for chaining asynchronous operations that can fail. Unlike Result and Option which are plain discriminated unions with standalone functions, ResultAsync uses instance methods for its combinators, allowing you to build an entire asynchronous chain before finally awaiting the result.
  9. How @zap-studio/react-hooks works

    main

    The library provides React interfaces for browser APIs (e.g., IntersectionObserver, ResizeObserver, Battery, Geolocation, matchMedia) while solving two common problems:

    1. Memory Leaks: Every hook handles its own cleanup (e.g., removing listeners) automatically when the component unmounts.
    2. SSR & Hydration Safety: Hooks are designed to be safe for Server-Side Rendering. They avoid direct access to window, document, or navigator outside of effects or guarded checks. This ensures that server-rendered output matches the first client-side render, preventing hydration mismatch errors.

    Tree-shaking: Each hook is a standalone, side-effect-free module. You can import hooks from the top-level package or via specific subpath exports to ensure only the code you need is included in your bundle.

  10. Core principles of Zap Studio packages

    main

    Every Zap Studio package is designed around four core guarantees to ensure predictability and reliability across different environments:

    1. Type safety: Types are derived from your schema via Standard Schema rather than manual annotations. This eliminates the need for as type casts when handling responses.
    2. Framework-agnostic: Packages are built using standard runtime APIs such as fetch, Request/Response, AbortSignal, and crypto.subtle. They do not require framework adapters, plugin systems, or global setup.
    3. Composable: Packages are designed to work together by accepting others as plain values. For example, you can wrap a fetch call in a retry policy, validate the payload with a validation package, and pass a logger through the chain.
    4. Tree-shakeable: Packages consist of standalone functions with no shared state and use one subpath per feature. Only the code you explicitly import will be included in your bundle.

    Because of these principles, Zap Studio packages do not include a custom runtime (no effect system, scheduler, or DI container), do not maintain hidden global state, do not require logging/tracing (they are optional parameters), and do not support CommonJS (ESM only).

  11. How @zap-studio/store works: Core Concepts

    main

    The @zap-studio/store package is a framework-agnostic state container designed to solve common issues found in other state management libraries:

    • Reactivity: It uses an auto-tracked signal graph (similar to TanStack Store). Derived values only recompute when their actual dependencies change.
    • Predictable Updates: Unlike Zustand, which allows set({ ... }) shortcuts, @zap-studio/store requires an updater function: set((prev) => partialOrFullState). This ensures all updates are shallow-merged and prevents confusion between merging and replacing state.
    • Stable References: The get() method returns a stable reference, making it safe for use with tools like React's useSyncExternalStore.
    • Minimal API: The library intentionally limits its surface to createStore, derive, and set to avoid the complexity of middleware chains or provider patterns.