Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

7.9 KB
Raw Blame
import type { ComponentType } from 'react'
import { useSyncExternalStore } from 'react'
import type { SubjectName } from './permissions'

/**
 * Where a registry route mounts:
 *
 * - `store` (default) — inside a store, under `/$storeId`, with the store's
 *   sidebar and top bar.
 * - `authenticated` — at the root, for signed-in users, outside any store
 *   (account or onboarding pages). Signed-out visitors go to the login page.
 * - `public` — at the root, with no sign-in required (a sign-up or terms page).
 */
export type RouteScope = 'store' | 'authenticated' | 'public'

/**
 * Dashboard route contributed by a plugin. Store routes mount under the
 * dashboard's `/_authenticated/$storeId/$` catch-all, which reads this
 * registry at render time and dispatches based on the splat path.
 *
 * Path patterns use TanStack-Router-style param tokens (`$brandId`) inside the
 * plugin's namespace. The dashboard strips the `/$storeId/` prefix before
 * matching, so a plugin pattern of `/brands/$brandId` matches the URL
 * `/store_xyz/brands/br_abc123` with `params: { brandId: 'br_abc123' }`.
 */
export interface StoreRouteEntry {
  /**
   * Stable identifier — used for register/remove/update and as the React key.
   * Mirrors the slug a plugin would use in its `nav.add({ key })` call so the
   * sidebar entry and route stay paired.
   */
  key: string
  scope?: 'store'
  /**
   * Path pattern relative to `/$storeId`. Examples: `/brands`,
   * `/brands/$brandId`, `/wishlists/$wishlistId/items`.
   * Must start with `/`. Do NOT include the `/$storeId` prefix; the dashboard
   * adds it at render time.
   */
  path: string
  /**
   * The component to render. Receives:
   * - `params`: extracted path params (e.g. matching `/brands/$brandId`
   *   against `/brands/br_abc` yields `{ brandId: 'br_abc' }`)
   * - `storeId`: the current store — every store route is implicitly scoped
   *   under `/$storeId/...`
   * - `searchParams`: the URL search-state object from TanStack Router. Use
   *   this with `<ResourceTable searchParams={searchParams} ... />` so
   *   filter/sort/pagination round-trip through the URL.
   */
  component: ComponentType<{
    params: Record<string, string>
    storeId: string
    searchParams: Record<string, unknown>
  }>
  /**
   * Optional CanCanCan subject required to view the route. The catch-all
   * renderer checks `permissions.can('read', subject)` and renders a 403
   * fallback when denied. Omit for routes that don't need permission gating.
   */
  subject?: SubjectName
}

/**
 * Route mounted at the dashboard's root, outside any store. Unlike store
 * routes these become real router routes when `createDashboardRouter` runs,
 * so they must be registered before it — `plugins.ts` and installed plugins
 * always are.
 */
export interface RootRouteEntry {
  key: string
  scope: 'authenticated' | 'public'
  /** Full URL path, e.g. `/sign-up` or `/account/$section`. Must start with `/`. */
  path: string
  component: ComponentType<{
    params: Record<string, string>
    searchParams: Record<string, unknown>
  }>
}

export type RouteEntry = StoreRouteEntry | RootRouteEntry

const ROUTE_SCOPES: readonly RouteScope[] = ['store', 'authenticated', 'public']

const entries: RouteEntry[] = []
const listeners = new Set<() => void>()

function notify() {
  for (const l of listeners) l()
}

function subscribe(listener: () => void): () => void {
  listeners.add(listener)
  return () => {
    listeners.delete(listener)
  }
}

interface RouteMutator {
  /** Register a route. Throws if `key` is already registered. */
  add(entry: RouteEntry): void
  /** Remove a route by key. No-op when missing. */
  remove(key: string): void
}

export const pluginRoutes: RouteMutator = {
  add(entry) {
    if (entries.some((e) => e.key === entry.key)) {
      throw new Error(`Plugin route "${entry.key}" already registered.`)
    }
    if (!entry.path.startsWith('/')) {
      throw new Error(`Plugin route "${entry.key}" path must start with "/", got "${entry.path}".`)
    }
    if (entry.scope !== undefined && !ROUTE_SCOPES.includes(entry.scope)) {
      throw new Error(
        `Plugin route "${entry.key}" scope must be one of ${ROUTE_SCOPES.join(', ')}, got "${entry.scope}".`,
      )
    }
    entries.push(entry)
    notify()
  },
  remove(key) {
    const i = entries.findIndex((e) => e.key === key)
    if (i === -1) return
    entries.splice(i, 1)
    notify()
  },
}

/** Every registered route, read outside React. */
export function getPluginRoutes(): readonly RouteEntry[] {
  return entries
}

/**
 * Subscribe to plugin route updates. Returns the full list of registered
 * routes; the catch-all renderer matches against this on every navigation.
 */
export function usePluginRoutes(): readonly RouteEntry[] {
  return useSyncExternalStore(subscribe, getPluginRoutes, getPluginRoutes)
}

/**
 * Match a URL splat (the bit after `/$storeId/`) against the registered
 * store routes. Returns the matched entry plus the extracted path params, or
 * `null` if nothing matched.
 *
 * Path patterns support TanStack-style `$param` tokens. A pattern segment
 * of `$brandId` matches any non-empty URL segment and binds it to
 * `params.brandId`.
 *
 * More-specific patterns win regardless of registration order: `/brands/new`
 * beats `/brands/$brandId` for the URL `/brands/new` because it has fewer
 * dynamic segments.
 */
export function matchPluginRoute(
  splat: string,
  routes: readonly RouteEntry[],
): { entry: StoreRouteEntry; params: Record<string, string> } | null {
  // Normalize: strip leading slash, drop empty trailing segments.
  const urlSegments = splat.replace(/^\/+/, '').split('/').filter(Boolean)
  const bySpecificity = routes
    .filter(isStoreRoute)
    .sort((a, b) => countDynamicSegments(a.path) - countDynamicSegments(b.path))
  for (const entry of bySpecificity) {
    const patternSegments = entry.path.replace(/^\/+/, '').split('/').filter(Boolean)
    if (patternSegments.length !== urlSegments.length) continue

    const params: Record<string, string> = {}
    let matched = true
    for (let i = 0; i < patternSegments.length; i++) {
      const p = patternSegments[i]
      const u = urlSegments[i]
      if (p.startsWith('$')) {
        params[p.slice(1)] = u
      } else if (p !== u) {
        matched = false
        break
      }
    }
    if (matched) return { entry, params }
  }
  return null
}

/**
 * Whether a registry route outranks the file route the router matched for the
 * same URL, so it renders in that route's place. The router sends
 * `/sellers/shopify` to `/sellers/$sellerId`, never to the catch-all, which
 * would leave a plugin page under a first-party section unreachable.
 *
 * Uses the router's own ranking: segment by segment, a fixed segment beats a
 * `$param`. A registry route therefore takes over only an address where it is
 * more specific, never a first-party page at its own path or through a
 * pattern like `/sellers/$id`.
 *
 * @param pluginPath the registry route's path, relative to `/$storeId`
 * @param routerPath the matched file route's path, relative to `/$storeId`
 */
export function outranksRouterMatch(pluginPath: string, routerPath: string): boolean {
  const pluginSegments = pathSegments(pluginPath)
  const routerSegments = pathSegments(routerPath)
  for (const [index, pluginSegment] of pluginSegments.entries()) {
    const pluginFixed = !pluginSegment.startsWith('$')
    const routerFixed = !(routerSegments[index] ?? '$').startsWith('$')
    if (pluginFixed !== routerFixed) return pluginFixed
  }
  return false
}

function pathSegments(path: string): string[] {
  return path.split('/').filter(Boolean)
}

function isStoreRoute(entry: RouteEntry): entry is StoreRouteEntry {
  return entry.scope === undefined || entry.scope === 'store'
}

function countDynamicSegments(path: string): number {
  return path
    .replace(/^\/+/, '')
    .split('/')
    .filter((segment) => segment.startsWith('$')).length
}

/** Test-only: clear the registry. */
export function __resetPluginRoutes(): void {
  entries.length = 0
  notify()
}