/** * Framework Bootstrap * * Single source of truth for which framework packages are wired into * boot. Each entry below either: * * 1. Imports a framework package whose `index.ts` self-registers via * `route.register(...)` on import — analogous to the service * provider pattern other frameworks (competitors) use to give * packages a chance to wire themselves up at boot. This is the * preferred shape for packages that own their own routes, * migrations, etc. * * 2. Registers a framework routes file directly via `route.register()` * — used when a routes file isn't yet wrapped in its own package. * * Adding a new framework package? Add a line here. There is no * filesystem scanning, no auto-discovery: this file is the entire * grep-able answer to "what does the framework load on boot?". * * @see storage/framework/core/router/src/route-loader.ts:loadFrameworkRoutes */ import { config, feature } from '@stacksjs/config' import process from 'node:process' import { frameworkPath } from '@stacksjs/path' import { log } from '@stacksjs/logging/runtime' import { bundleMounts, DEFAULT_ROUTE_BUNDLE_FEATURES, route, withRouteAdmission } from '@stacksjs/router' import MaintenanceMiddleware from './app/Middleware/Maintenance' // Global maintenance / coming-soon gate. Registered first so the // `buddy down` / `buddy coming-soon` (and their env-var equivalents) // state files intercept every request before any other middleware or // route runs. // // The middleware is a thin wrapper around `maintenanceGate()` in // @stacksjs/server, which is also called from the dev server's // `onRequest` hook — so dev and prod use one implementation. The gate // itself reads `activeSiteModePayload()` so it covers both maintenance // and coming-soon modes (plus `APP_MAINTENANCE` / `APP_COMING_SOON` // env overrides) without the bootstrap needing to know the details. // // `toRouterHandler()` adapts the Middleware contract (return void to // continue, throw a Response to short-circuit) to bun-router's // `(req, next) => Response` shape. Without the adapter, `handle` would // return `undefined`, bun-router's chain treats that as a short-circuit // to an empty 200, and every route returns `200 OK Content-Length: 0`. route.use(MaintenanceMiddleware.toRouterHandler() as any) // Locale cookie + STX-style path redirect (`/locale/en` → `/en/…`). // Overridable by registering the same path in app routes first. await route.register(frameworkPath('defaults/routes/core.ts')) // Which default route bundles this app mounts. The route loader resolves the // selection (STACKS_DEFAULT_ROUTES, or the legacy STACKS_SKIP_DEFAULT_ROUTES) // and leaves it here; see `resolveDefaultRouteBundles` in // `core/router/src/route-loader.ts`. Absent when bootstrap is imported by // something other than the loader, in which case every bundle is eligible and // the feature gates below decide, exactly as before. const selection = (globalThis as Record).__stacksDefaultRouteBundles as { bundles: Set, explicit: boolean } | undefined /** * Whether a bundle mounts: named by the app, or, when the app named none, its * feature flag is on. * * The rule and the flag each bundle rides on live in the router * (`bundleMounts`, `DEFAULT_ROUTE_BUNDLE_FEATURES`), because the views server * asks the same question from another process - it serves `/login` only when * this file mounts `POST /login` - and two copies of one rule drift. */ function mounts(bundle: keyof typeof DEFAULT_ROUTE_BUNDLE_FEATURES): boolean { return bundleMounts(selection, bundle, feature(DEFAULT_ROUTE_BUNDLE_FEATURES[bundle])) } /** * Every default bundle this app mounts, registered in one place so the * admission check below covers all of them. */ async function registerDefaultBundles(): Promise { // Auth: login, registration, logout, refresh/revoke, passkeys, TOTP 2FA and // password reset. Split out of dashboard.ts so it can be mounted on its own // (stacksjs/stacks#2229) — previously the only way to get `/login` was to // activate `dashboard` and take the storefront, reviews, AI and voice surface // with it. // // Registered BEFORE dashboard.ts, which is where these lived, so the // first-registration-wins order among framework routes is unchanged. // // Deliberately NOT gated on `feature('auth')`, despite the issue asking for // it: `config/auth.ts` ships in every app with `enabled: true`, so that gate // is true everywhere and would mount the auth surface — including // `/generate-two-factor-secret`, `/logout-all` and `/auth/tokens` — in apps // currently running with `dashboard` off. Widening an app's public surface on // upgrade is not something a refactor gets to do silently. if (mounts('auth')) await route.register(frameworkPath('defaults/routes/auth.ts')) // The rest of dashboard.ts: email subscribe, sitemap, AI, voice, and the // admin dashboard's REST surface (its CMS and commerce groups follow their // features). The storefront moved to its own bundle below. Still // one file and still one gate — splitting auth out was the case with a // reporter behind it; marketing.ts / commerce.ts / monitoring.ts remain the // obvious next cuts. // // Apps that need only a slice can also define the routes they want directly // in `routes/api.ts` — first-registration-wins means the user version takes // priority. if (mounts('dashboard')) { await route.register(frameworkPath('defaults/routes/dashboard.ts')) // JSON endpoints for the dev dashboard UI. Kept separate from the view // routes above so the data layer is one obvious file to grep. // The standalone dashboard registers this after the app loader finishes, // outside table admission. Its home endpoint intentionally reports optional // stores as unavailable instead of disappearing when Request is not used. if (process.env.STACKS_DASHBOARD_WORKER !== '1') await route.register(frameworkPath('defaults/routes/dashboard-api.ts')) // The dev dashboard boots through this file rather than the application // router's importRoutes() path, so load model-declared useApi routes here too. // // Package first, vendored second, matching importRoutes() and start.ts. This // line used to import the vendored copy only, and nothing re-vendors that // file: `@stacksjs/orm` publishes `dist/routes.js` and no `routes.ts`, so an // app kept whatever generator its copy froze at however often it upgraded. // An old enough copy compares route paths literally, so a generated // `PATCH /api/sites/{id}` does not recognise a hand-written // `/api/sites/{siteId}` as the same endpoint and registers alongside it, // and the hand-written handler's authorization check stops running // (stacksjs/stacks#2364). // // Held in a variable so the specifier resolves at runtime rather than while // transpiling, where an unresolvable literal would fail this module instead // of throwing where it can be caught. const ormRoutesPackage = '@stacksjs/orm/routes' try { await import(ormRoutesPackage) } catch { await import(frameworkPath('orm/routes.ts')) } } // Email webhook + unsubscribe routes (stacksjs/stacks#1881, #1880). // Always mounted when the `email` feature is on — the underlying // handlers self-disable when their provider credentials aren't // configured (they 401 rather than processing). Apps that need a // non-default mount path register their own routes in `routes/api.ts` // and the framework's mount silently no-ops since user routes // register first. if (mounts('email')) { await route.register(frameworkPath('defaults/routes/email.ts')) } // Form-builder public endpoints (`@stacksjs/forms`). Gated on the `forms` // feature, which defaults OFF - an app opts in with config/forms.ts // (`buddy forms:install`) and only then do the public submit routes exist. if (mounts('forms')) { await route.register(frameworkPath('defaults/routes/forms.ts')) } // Courier delivery endpoints: position ingest and the stop/route lifecycle a // courier's device drives. Gated with the rest of the commerce surface, since // they are meaningless without the delivery models behind them. if (mounts('delivery')) { await route.register(frameworkPath('defaults/routes/delivery.ts')) } // The storefront: cart, checkout and buyer reviews, behind the default // `cart`, `checkout` and `orders` pages. Gated with the commerce surface, so // an app without commerce neither mounts these routes nor serves the pages. if (mounts('storefront')) { await route.register(frameworkPath('defaults/routes/storefront.ts')) } // The payment provider's webhook, which applies payments and refunds to // orders. Gated with the commerce surface; it answers 401 until the driver's // webhook secret is configured. if (mounts('payments')) { await route.register(frameworkPath('defaults/routes/payments.ts')) } // The page a Paddle payment link opens: Paddle has no hosted checkout, so // its default payment link has to point at a page of the app's that loads // Paddle.js. Mounted while the app pays through Paddle, as part of the // `payments` bundle when the app names its bundles. const paymentDriverName = (config as { payment?: { driver?: string } }).payment?.driver if (paymentDriverName === 'paddle' && (selection?.explicit ? selection.bundles.has('payments') : true)) { await route.register(frameworkPath('defaults/routes/paddle.ts')) } // Software licensing: activate, check, release, resend, transfer and team // seats (`@stacksjs/commerce` `licensing`). An opt-in bundle like `social`: // an app that named its bundles decides outright, and an app that said // nothing gets it exactly when it has a license signing key, since without // one no token can be issued and the routes are surface for nothing. const mountLicensing = selection?.explicit ? selection.bundles.has('licensing') : Boolean(process.env.LICENSE_SIGNING_KEY) if (mountLicensing) { await route.register(frameworkPath('defaults/routes/licensing.ts')) } // Social sign-in: `/auth/{provider}` + `/auth/{provider}/callback` // (stacksjs/stacks#2276). An opt-in bundle, NOT part of the implicit default // set or `all` — OAuth callback URLs in an app that configured no provider // are surface for nothing. So `mounts()` does not apply here: an app that // NAMED its bundles decides outright (`social` listed → on, absent → off), // and an app that said nothing gets it exactly when a provider is actually // configured in config/services.ts — configuring GitHub and finding // /auth/github dead would be the puzzle, not the mount. const { configuredSocialProviders } = await import('@stacksjs/socials') const mountSocial = selection?.explicit ? selection.bundles.has('social') : configuredSocialProviders().length > 0 if (mountSocial) { await route.register(frameworkPath('defaults/routes/socials.ts')) } // The desktop update feed (`/api/updates/{platform}/{arch}`): what an // installed desktop app asks for a newer version. Like `social`, it exists // exactly when the app configured it - `webview.updates` or `macos.updates` // in config/desktop.ts - so no existing app gains a route. The config file // is read directly: the desktop build package is not loaded at server boot. if (await publishesDesktopUpdates()) { await route.register(frameworkPath('defaults/routes/desktop-updates.ts')) } } async function publishesDesktopUpdates(): Promise { const { existsSync } = await import('node:fs') const { projectPath } = await import('@stacksjs/path') const file = projectPath('config/desktop.ts') if (!existsSync(file)) return false try { const desktop = (await import(file) as { default?: { webview?: { updates?: unknown }, macos?: { updates?: unknown } } }).default return Boolean(desktop?.webview?.updates || desktop?.macos?.updates) } catch { return false } } // Register the bundles, withholding any route whose framework action depends // on a model this app excluded from its schema and whose table its database // does not have. Those routes could only answer 500 (stacksjs/stacks#2943); now // they are absent, and boot says which and why. When the table list cannot be // read, nothing is withheld. const { frameworkRouteAdmission } = await import('@stacksjs/database') const withheld = await withRouteAdmission(await frameworkRouteAdmission(), registerDefaultBundles) if (withheld.length > 0) { const shown = withheld.slice(0, 5).map(r => `${r.method} ${r.path} -> ${r.handler} needs ${r.reason}`) const more = withheld.length > shown.length ? `\n ... and ${withheld.length - shown.length} more` : '' log.warn(`[Routes] Not registering ${withheld.length} framework route(s) whose models are not in this app's schema (database.models.includeFrameworkDefaults is false) and whose tables do not exist:\n ${shown.join('\n ')}${more}\nPublish a model with \`buddy publish model \` or set includeFrameworkDefaults to serve them.`) }