diff --git a/ai/context/operations.md b/ai/context/operations.md index f4fe7e8..58f443e 100644 --- a/ai/context/operations.md +++ b/ai/context/operations.md @@ -253,7 +253,6 @@ anyone's real domain). Nothing that uses the domain was removed; it waits: | `apps/api-edge/wrangler.template.jsonc` | `CONSOLE_CUSTOM_DOMAIN`, the console origin CORS allows besides the workers.dev one | | `apps/identity-worker/wrangler.template.jsonc` | `OAUTH_ALLOWED_CONSOLE_ORIGINS`, which lists the workers.dev console and CMS too, so sign-in works without a domain | | `apps/notifications-worker/wrangler.template.jsonc` | `EMAIL_FROM_ADDRESS`, `no-reply@mail.multi-tenant-saas-2.example.com` | -| `apps/billing-worker/wrangler.template.jsonc` | `POLAR_SUCCESS_URL`, the fallback return after checkout | | `tests/api-edge` | the CORS fixtures, which follow the edge's config | To set it, in one PR: diff --git a/apps/billing-worker/wrangler.template.jsonc b/apps/billing-worker/wrangler.template.jsonc index 2e441e0..9047c0b 100644 --- a/apps/billing-worker/wrangler.template.jsonc +++ b/apps/billing-worker/wrangler.template.jsonc @@ -17,9 +17,10 @@ // wrangler secret put POLAR_ACCESS_TOKEN --env // wrangler secret put POLAR_WEBHOOK_SECRET --env // - POLAR_PRODUCT_MAP (plan code → Polar product id) is set per env. - // - POLAR_SUCCESS_URL is the FALLBACK post-checkout return (console root) for - // callers that don't supply embedOrigin+returnPath; the console always does, - // so the buyer normally returns to its own billing page. + // - POLAR_SUCCESS_URL is the FALLBACK post-checkout return for callers that + // don't supply embedOrigin+returnPath: the CMS's Billing & plan page (the + // CMS is the console, lumen-payload-console PX4). The CMS always supplies + // both, so the buyer normally returns there anyway. "vars": { "ENVIRONMENT": "local", "BILLING_PROVIDER": "polar", @@ -41,7 +42,7 @@ "BILLING_PROVIDER": "polar", "POLAR_SERVER": "sandbox", "POLAR_PRODUCT_MAP": "{\"pro\":\"c3e33c12-1ec6-4843-aed1-10b21c6fcb4f\",\"business\":\"aefd7468-6f9f-4ebc-b373-31c852b9842a\"}", - "POLAR_SUCCESS_URL": "https://stage.multi-tenant-saas-2.example.com/" + "POLAR_SUCCESS_URL": "https://multi-tenant-saas-2-cms-stage.nexo-7be.workers.dev/admin/organization/billing?checkout=complete" }, "hyperdrive": [ { @@ -67,7 +68,7 @@ "BILLING_PROVIDER": "polar", "POLAR_SERVER": "production", "POLAR_PRODUCT_MAP": "{\"pro\":\"c711fc4c-74e2-47f5-991e-b940df833899\",\"business\":\"e2ba3e96-b97a-4348-82ef-87bcebad1d17\"}", - "POLAR_SUCCESS_URL": "https://prod.multi-tenant-saas-2.example.com/" + "POLAR_SUCCESS_URL": "https://multi-tenant-saas-2-cms-prod.nexo-7be.workers.dev/admin/organization/billing?checkout=complete" }, "hyperdrive": [ { diff --git a/apps/cms/docs/architecture.md b/apps/cms/docs/architecture.md index 3315919..2f8fcb0 100644 --- a/apps/cms/docs/architecture.md +++ b/apps/cms/docs/architecture.md @@ -7,8 +7,8 @@ into `.open-next/worker.js` plus `.open-next/assets`, deployed by the itself, so the composition's `wrangler deploy` ships the whole build. ``` -browser ──► multi-tenant-saas-2-cms- (Worker) - /admin Payload admin (React, server components) +browser ──► multi-tenant-saas-2-cms- (Worker) ◄──308── multi-tenant-saas-2-web-console-next- (the old console URL) + /admin Payload admin (React, server components): the staff console /api/ REST ┐ /api/graphql GraphQL ├─ payload ─► HYPERDRIVE_CMS ─► Supabase Postgres, schema cms /health liveness + db ┘ (cache disabled) diff --git a/apps/cms/docs/overview.md b/apps/cms/docs/overview.md index 6d24a11..0a853ca 100644 --- a/apps/cms/docs/overview.md +++ b/apps/cms/docs/overview.md @@ -1,6 +1,7 @@ # cms -Payload CMS on Cloudflare Workers: the admin panel at `/admin`, the REST API +Payload CMS on Cloudflare Workers, and the product: the academy at `/`, the +staff console (the admin panel) at `/admin`, which the old console URL opens, the REST API at `/api/` and GraphQL at `/api/graphql`, over Postgres schema `cms`, deployed beside the fleet as `multi-tenant-saas-2-cms-`. diff --git a/apps/cms/src/app/(payload)/admin/importMap.js b/apps/cms/src/app/(payload)/admin/importMap.js index c927328..cf74a8a 100644 --- a/apps/cms/src/app/(payload)/admin/importMap.js +++ b/apps/cms/src/app/(payload)/admin/importMap.js @@ -21,6 +21,8 @@ import { StrikethroughFeatureClient as StrikethroughFeatureClient_e70f5e05f09f93 import { UnderlineFeatureClient as UnderlineFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client' import { BoldFeatureClient as BoldFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client' import { ItalicFeatureClient as ItalicFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client' +import { Icon as Icon_81fda60f3e3709e861f40982a767707d } from '../../../components/admin/Brand' +import { Logo as Logo_81fda60f3e3709e861f40982a767707d } from '../../../components/admin/Brand' import { AccountNav as AccountNav_d70fd73be0c9b3a7c754123a7e679b3d } from '../../../components/admin/account/AccountNav' import { LumenLogin as LumenLogin_7ffca7fd7bddfb9b50fd712bb1cc26c1 } from '../../../components/admin/LumenLogin' import { PendingAccess as PendingAccess_44e69ba3ff986b78d5b2450d962466d0 } from '../../../components/admin/PendingAccess' @@ -57,6 +59,8 @@ export const importMap = { "@payloadcms/richtext-lexical/client#UnderlineFeatureClient": UnderlineFeatureClient_e70f5e05f09f93e00b997edb1ef0c864, "@payloadcms/richtext-lexical/client#BoldFeatureClient": BoldFeatureClient_e70f5e05f09f93e00b997edb1ef0c864, "@payloadcms/richtext-lexical/client#ItalicFeatureClient": ItalicFeatureClient_e70f5e05f09f93e00b997edb1ef0c864, + "/components/admin/Brand#Icon": Icon_81fda60f3e3709e861f40982a767707d, + "/components/admin/Brand#Logo": Logo_81fda60f3e3709e861f40982a767707d, "/components/admin/account/AccountNav#AccountNav": AccountNav_d70fd73be0c9b3a7c754123a7e679b3d, "/components/admin/LumenLogin#LumenLogin": LumenLogin_7ffca7fd7bddfb9b50fd712bb1cc26c1, "/components/admin/PendingAccess#PendingAccess": PendingAccess_44e69ba3ff986b78d5b2450d962466d0, diff --git a/apps/cms/src/components/admin/Brand.tsx b/apps/cms/src/components/admin/Brand.tsx new file mode 100644 index 0000000..de656be --- /dev/null +++ b/apps/cms/src/components/admin/Brand.tsx @@ -0,0 +1,31 @@ +// The product's mark in the admin (multi-tenant-saas-2-console design §5): the +// name from .rebrand/values.json ("Multi Tenant Saas 2") beside a simple glyph, drawn in +// the admin's own text colour so it follows the light and dark themes. + +function Glyph({ size }: { size: number }) { + return ( + + ) +} + +/** The sign-in and loading screens' logo. */ +export function Logo() { + return ( + + + Multi Tenant Saas 2 + + ) +} + +/** The nav's icon. */ +export function Icon() { + return ( + + + + ) +} diff --git a/apps/cms/src/components/admin/LumenLogin.tsx b/apps/cms/src/components/admin/LumenLogin.tsx index 7652c71..f6c5d87 100644 --- a/apps/cms/src/components/admin/LumenLogin.tsx +++ b/apps/cms/src/components/admin/LumenLogin.tsx @@ -3,6 +3,7 @@ import { redirect } from 'next/navigation' import { safeAdminRedirect } from '../../lib/lumen/cookies' import { lumenPublicApiUrl } from '../../lib/lumen/transport' +import { Logo } from './Brand' import { LumenSignIn } from './LumenSignIn' const first = (value: string | string[] | undefined): string | null => (typeof value === 'string' ? value : null) @@ -13,12 +14,17 @@ export async function LumenLogin({ initPageResult, searchParams }: AdminViewServ const target = safeAdminRedirect(first(searchParams?.redirect)) if (initPageResult.req.user) redirect(target) return ( - + <> +
+ +
+ + ) } diff --git a/apps/cms/src/payload.config.ts b/apps/cms/src/payload.config.ts index 62ee9ac..efb53cc 100644 --- a/apps/cms/src/payload.config.ts +++ b/apps/cms/src/payload.config.ts @@ -44,7 +44,7 @@ export default buildConfig({ admin: { user: Users.slug, importMap: { baseDir: path.resolve(dirname) }, - meta: { titleSuffix: ' — CMS' }, + meta: { titleSuffix: ' — Multi Tenant Saas 2' }, // Lumen sign-in replaces Payload's password views for staff // (multi-tenant-saas-2-console design §1–§2): Payload's local strategy is // off on `users`. Learners keep their own sign-in in the academy. @@ -53,6 +53,7 @@ export default buildConfig({ // account view becomes the Lumen profile, and the rest are custom views // under an Account group in the nav. afterNavLinks: ['/components/admin/account/AccountNav#AccountNav'], + graphics: { Logo: '/components/admin/Brand#Logo', Icon: '/components/admin/Brand#Icon' }, views: { login: { Component: '/components/admin/LumenLogin#LumenLogin' }, unauthorized: { Component: '/components/admin/PendingAccess#PendingAccess' }, diff --git a/apps/web-console-next/.gitignore b/apps/web-console-next/.gitignore index ae9d535..16b1737 100644 --- a/apps/web-console-next/.gitignore +++ b/apps/web-console-next/.gitignore @@ -1,15 +1,5 @@ -# Next.js build output -.next/ -out/ - -# OpenNext / @opennextjs/cloudflare build output -.open-next/ - -# Local env files -.env*.local +# Build output +dist/ # Wrangler local state .wrangler/ - -# TS build info -*.tsbuildinfo diff --git a/apps/web-console-next/README.md b/apps/web-console-next/README.md index 419a7f7..9cb3366 100644 --- a/apps/web-console-next/README.md +++ b/apps/web-console-next/README.md @@ -1,98 +1,16 @@ -# @saas/web-console-next - -Next.js 15 + [opennextjs/cloudflare](https://github.com/opennextjs/opennextjs-cloudflare) delivery of the Multi Tenant Saas 2 web console. - -Wired against the same `@saas/contracts` typed envelope as `apps/web-console`, -deployed via the same `cloudflare-pages-turbo` orun composition (with -`outputDir: .open-next/assets` instead of `dist/`). - -## Scripts - -```bash -pnpm -F @saas/web-console-next dev # next dev on :3001 -pnpm -F @saas/web-console-next typecheck # tsc --noEmit -pnpm -F @saas/web-console-next lint # eslint -pnpm -F @saas/web-console-next build # next build (standalone) + opennextjs-cloudflare build -``` - -The `build` script runs Next's standalone build (configured via -`output: "standalone"` + `outputFileTracingRoot` in `next.config.mjs`) and -then invokes `opennextjs-cloudflare build --skipBuild ---skipWranglerConfigCheck`, which reads `.next/standalone/**` and emits the -Cloudflare Pages-compatible bundle into `.open-next/`: - -- `.open-next/assets/**` — static assets the `cloudflare-pages-turbo` - orun component publishes (matches `outputDir` in `component.yaml`). -- `.open-next/worker.js` — Pages Function entrypoint, referenced from - `wrangler.jsonc#main`. - -`open-next.config.ts` keeps the in-memory `dummy` overrides for the -incremental cache / tag cache / queue — this app has no R2/KV/D1 bindings -and runs fully session-authenticated, so no persistent caching layer is -needed. - -## Parity vs. apps/web-console - -| Surface | web-console (Vite) | web-console-next (Next 15) | -|-----------------------------|--------------------|----------------------------| -| Login (email-code) | ✅ inline form | ✅ Zod form + tabs | -| Login (bearer token paste) | ✅ | ✅ | -| Org listing | ✅ | ✅ card grid | -| Create organization | ✅ | ✅ Zod dialog form | -| Projects list | ✅ | ✅ card grid + status | -| Create project | ✅ | ✅ Zod dialog form | -| Members list | ✅ | ✅ table + role badges | -| Remove member | ✅ | ✅ | -| Invitations list | ✅ | ✅ table + status badges | -| Create invitation | ✅ | ✅ Zod dialog form (role enum) | -| Revoke invitation | ✅ | ✅ | -| API keys list | ✅ | ✅ table | -| Create API key + one-time secret reveal | ✅ | ✅ reveal modal + copy | -| Revoke API key | ✅ | ✅ | -| Environments list | ✅ | ✅ card grid | -| Create environment | ✅ | ✅ Zod dialog form | -| Environment detail | (basic) | ✅ identity card | -| Audit log | ✅ | ✅ category filter | -| Billing (plan/ents/invoices)| ✅ | ✅ + precondition_failed UX| -| Config / org identifiers | partial | ✅ | -| Target switching | ✅ | ✅ (sidebar + palette) | -| Dark mode | ❌ | ✅ next-themes (default) | -| Empty states + skeletons | minimal | ✅ across every list | -| Cmd-K command palette | ❌ | ✅ | -| URL-driven scope | sessionStorage | ✅ `useParams` | -| Designed precondition_failed UX | ❌ | ✅ four reason-coded shapes| - -## Notable design choices - -- **Tailwind 3.4 + Next 15.0 stable** rather than Tailwind v4-beta + Next 15 alpha (risk reduction). -- **Design system co-located** in `src/components/ui/`; promoting to `packages/ui` is a future task. -- **URL is the source of truth for scope**: `/orgs/[orgSlug]/projects/[projectSlug]/environments/[envSlug]`. We never cache scope in storage so cross-tab tenant isolation is enforced. -- **Per-target `ApiClient` instance** constructed by `SessionProvider`, not a module singleton. -- **Error envelope preserves `meta.requestId`** on the failure branch so `PreconditionInsight` can always surface request IDs. -- **`NEXT_PUBLIC_DEPLOY_ENV`** mirrors the old `VITE_DEPLOY_ENV` build-time lock — when set, the target switcher is hidden. -- **`/demo`** is a token-free showcase route used for verifier screenshots. -- **`ZodForm`** is the canonical contracts→form proof: a single Zod schema feeds validation, types, and the rendered fields. - -## Designed `precondition_failed` UX - -Reason codes (per `ai/context/current.md`): - -- `limit_reached` — entitlement quota exhausted; offer upgrade. -- `disabled` — feature exists on a higher plan; offer upgrade. -- `not_configured` — no entitlement record; offer "talk to sales". -- `malformed_limit` — defensive; surfaces request ID for support escalation. - -All four shapes are rendered on `/demo` for screenshot evidence. - -## Deployment - -Identical orun composition pattern to `apps/web-console`: - -- `spec.type: cloudflare-pages-turbo` -- `outputDir: .open-next/assets` (opennextjs/cloudflare output) -- `environmentBuildVar: NEXT_PUBLIC_DEPLOY_ENV` (was `VITE_DEPLOY_ENV`) -- Per-env Cloudflare Pages projects: `multi-tenant-saas-2-web-console-next-{dev,stage,prod}` -- Smoke probe identical to the existing console. - -Verification is via the same `verify`/`deploy` profile split, so this app -fits cleanly into the existing platform pipeline. +# web-console-next — retired to a redirect + +This was the Multi Tenant Saas 2 web console (Next.js on Workers). The console is +now the **Payload admin** (`apps/cms`, specs/epics/multi-tenant-saas-2-console), and +this component keeps only the old URL alive: +`multi-tenant-saas-2-web-console-next-.nexo-7be.workers.dev` answers every +request with a `308` to the same page's place in the CMS of the same +environment, so bookmarks, old links and old OAuth returns land in Payload. + +The console's UI, its models and its tests were removed in PX4. The models +the admin still uses were copied into `apps/cms/src/lib/lumen/models/` with +their tests; the rest is in git history. + +- [Overview](docs/overview.md) +- [Architecture](docs/architecture.md) +- [Runbook](docs/runbook.md) diff --git a/apps/web-console-next/component.yaml b/apps/web-console-next/component.yaml index 0bec45c..15a0461 100644 --- a/apps/web-console-next/component.yaml +++ b/apps/web-console-next/component.yaml @@ -2,7 +2,7 @@ apiVersion: sourceplane.io/v1 kind: Component metadata: name: web-console-next - description: Next.js 15 + opennextjs/cloudflare delivery of the Multi Tenant Saas 2 web console (per-environment, Workers + Static Assets) + description: The Lumen console's URL, kept as a Worker that 308-redirects every path to its place in the Payload admin (apps/cms) of the same environment spec: docs: overview: docs/overview.md @@ -14,21 +14,13 @@ spec: owner: platform domain: starter-ui path: apps/web-console-next - # Its own lane per environment (execution.lanes in intent.yaml): the Next.js - # build is the longest job in the plan, and a shared lane would wait on it. + # Its own lane per environment (execution.lanes in intent.yaml), as when it + # was the Next.js console. lane: isolated - # The deploy smoke health-checks the api-edge worker - # (multi-tenant-saas-2-api-edge-/health), so api-edge must be live before this - # component's stage/prod deploy+smoke runs. Without this ordering the smoke - # races api-edge's concurrent deploy and fails with curl exit 22 (404). + # The smoke follows the redirect into the CMS's sign-in page, so the CMS + # must be live first. dependsOn: - - component: api-edge - # Shared workspace packages this component BUNDLES. Declared so a change - # to one marks this component changed and redeploys it — without the - # edge, `orun plan --changed` keys on `path:` alone and a worker can run - # a months-old copy of a package that has since changed underneath it. - - component: contracts - - component: sdk + - component: cms subscribe: environments: - name: dev @@ -55,10 +47,10 @@ spec: turboFilter: "@saas/web-console-next" wranglerConfig: wrangler.jsonc - # @opennextjs/cloudflare emits a Worker entrypoint plus a static-assets - # directory bound via ASSETS — both are deployed in one `wrangler deploy`. - workerEntrypoint: .open-next/worker.js - assetsDir: .open-next/assets + # A plain Worker compiled by tsc (no static assets: dist/ only has to exist + # for the composition's output check). + workerEntrypoint: dist/worker.js + assetsDir: dist # Worker is named per-env (multi-tenant-saas-2-web-console-next-{dev,stage,prod}), # matching the prior Pages-project naming convention so the cutover in @@ -70,36 +62,18 @@ spec: # ${WORKERS_DEV_SUBDOMAIN} and used to build ${DEPLOYED_URL}. workersDevSubdomain: nexo-7be - # NO environmentBuildVar (saas-console-artifact CA2): the console learns its - # environment at runtime — CONSOLE_DEPLOY_ENV if the deploy sets one, else - # the `-` its workers.dev host carries — so the build is the same for - # every environment and a build made anywhere can be deployed to any of - # them. It used to pass NEXT_PUBLIC_DEPLOY_ENV, which baked the environment - # into the bundle and is exactly what stopped one build from serving both. - installCommand: pnpm install --frozen-lockfile - # saas-console-artifact CA4: with a console-artifact.pin.json (written by - # the bootstrap's 06-console phase) and sources that still hash to it, this - # fetches the baseline's prebuilt console and verifies its sha256 instead - # of building. No pin, changed sources or an unreachable artifact all fall - # back to the normal turbo build, so a product that never saw a published - # artifact behaves exactly as before. - buildCommand: node scripts/console-artifact.mjs build + # Compile, then run tests/web-console-next (the redirect map) in this lane: + # that component's own lane is quick-check, which runs no tests. + buildCommand: pnpm run build && pnpm --filter @saas/web-console-next-tests test - # Smoke: follow redirects (root `redirect("/orgs")` is a 307) and confirm - # the SSR'd page contains the console marker. The api-edge worker is the - # same hostname pattern as before. - # Buffer curl into a variable before grepping so `grep -q` matching early - # cannot SIGPIPE curl and produce a flaky exit-23 race (observed on prod - # in main CI run 26628207777 even though the site was live). - # `${WORKERS_DEV_SUBDOMAIN}` is exported by the composition's deploy/smoke - # step from the `workersDevSubdomain` parameter above (BF3: no duplicated - # subdomain literal here). - smokeCommand: "html=$(curl -sfL \"${DEPLOYED_URL}/\") && echo \"${html}\" | grep -q 'Multi Tenant Saas 2 Console' && health=$(curl -sf \"https://multi-tenant-saas-2-api-edge-${ORUN_ENVIRONMENT}.${WORKERS_DEV_SUBDOMAIN}.workers.dev/health\") && echo \"${health}\" | grep -q ok" + # Smoke: an old console page answers 308 to its place in the CMS of the + # same environment, query kept, and the old /login, followed, is the + # admin's Lumen sign-in view (the page payload names LumenSignIn; the form + # itself renders in the browser). + smokeCommand: "out=$(curl -s -o /dev/null -w '%{http_code} %{redirect_url}' \"${DEPLOYED_URL}/orgs/x/settings/billing?checkout=complete\") && [ \"${out}\" = \"308 https://multi-tenant-saas-2-cms-${ORUN_ENVIRONMENT}.${WORKERS_DEV_SUBDOMAIN}.workers.dev/admin/organization/billing?checkout=complete\" ] && html=$(curl -sfL \"${DEPLOYED_URL}/login\") && echo \"${html}\" | grep -q 'LumenSignIn'" labels: team: platform layer: delivery surface: web-console-next runtime: cloudflare -# ci: re-trigger web-console after api-edge is live (20260622T142123Z) -# orun: redeploy 06-console as_c778553f7ed74a0fa6ec diff --git a/apps/web-console-next/console-artifact.pin.json b/apps/web-console-next/console-artifact.pin.json deleted file mode 100644 index c444d5e..0000000 --- a/apps/web-console-next/console-artifact.pin.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "url": "https://github.com/sourceplane/lumen/releases/download/console-artifacts/web-console-next-04d3d8f60a082a5ab94cbaa6b13a1c72.tar.gz", - "sha256": "b2ea278a9cf24c1a23f691a435f727d897c096fb4683a975f7d3a33bdb2da370", - "sourceHash": "572662f19381021f38915f65bc1896c5" -} diff --git a/apps/web-console-next/docs/architecture.md b/apps/web-console-next/docs/architecture.md index 339c719..848eb24 100644 --- a/apps/web-console-next/docs/architecture.md +++ b/apps/web-console-next/docs/architecture.md @@ -1,11 +1,23 @@ # web-console-next — architecture -A `cloudflare-workers-assets-turbo` component: the Next.js app in `apps/web-console-next` builds to -static assets plus a thin Worker runtime, deployed per environment. - -- All data access goes through the API edge — the console holds no - credentials and no direct data-plane access. -- Environment selection (stage/prod edge URL) is wired at build/deploy - time by the lane; the console is static after that. -- Being assets-first, the console can be "up" while the API behind it is - degraded — always verify the edge separately. +One plain Worker, `src/worker.ts`, compiled by `tsc` to `dist/worker.js` and +deployed by the `cloudflare-workers-assets-turbo` composition as +`multi-tenant-saas-2-web-console-next-`. No bindings, no static assets, no +state. + +``` +browser ──► multi-tenant-saas-2-web-console-next- ──308──► multi-tenant-saas-2-cms-/? +``` + +## Decisions + +- **The environment comes from the host.** The Worker serves only + `multi-tenant-saas-2-web-console-next-(dev|stage|prod)..workers.dev` and + sends each to the CMS of the same environment on the same subdomain. Any + other host answers 404, so the Worker cannot be made to redirect anywhere + else. +- **308, cached an hour.** 308 keeps the method (an old form post still + arrives as a post), and an hour's cache lets the mapping change without + browsers holding a permanent redirect forever. +- **Same lane as before.** The component keeps its isolated lane and its + Worker name, so nothing else in the plan moves. diff --git a/apps/web-console-next/docs/overview.md b/apps/web-console-next/docs/overview.md index 3455bbc..8c3af08 100644 --- a/apps/web-console-next/docs/overview.md +++ b/apps/web-console-next/docs/overview.md @@ -1,11 +1,34 @@ # web-console-next -Next.js 15 + opennextjs/cloudflare delivery of the Multi Tenant Saas 2 web console (per-environment, Workers + Static Assets) +The Lumen console's old URL, kept as a redirect to the Payload admin, which is +the product's console now (multi-tenant-saas-2-console LX3, after lumen-payload-console PX4). -The multi-tenant-saas-2 console UI — Next.js compiled to a Cloudflare Worker with -Static Assets, configured against the API edge. Public at -`https://multi-tenant-saas-2-web-console-next-{stage,prod}.nexo-7be.workers.dev`. +| | stage | prod | +|---|---|---| +| URL | https://multi-tenant-saas-2-web-console-next-stage.nexo-7be.workers.dev | https://multi-tenant-saas-2-web-console-next-prod.nexo-7be.workers.dev | +| Goes to | https://multi-tenant-saas-2-cms-stage.nexo-7be.workers.dev/admin | https://multi-tenant-saas-2-cms-prod.nexo-7be.workers.dev/admin | + +## Where each old page goes + +| Old console path | In the CMS | +|---|---| +| `/`, and anything not below | `/admin` | +| `/login` | `/admin/login` | +| `/auth/callback` (the OAuth return) | `/auth/lumen/callback` (the browser keeps the `#token` fragment) | +| `/account`, `/account/security` | `/admin/account`, `/admin/account/security` | +| `/orgs`, `/orgs/`, `/orgs//settings` | `/admin/organization` | +| `/orgs//settings/notifications` | `/admin/organization/notifications` | +| `/orgs//settings/billing` (and `…/change-plan`, `/orgs//billing`) | `/admin/organization/billing` | + +The query string is kept (a billing return's `?checkout=complete` still +reconciles the plan). ## Depends on -- **api-edge** — Cloudflare Worker for the API edge Runtime +- **cms**: the redirect's target; the deploy's smoke check follows the + redirect to the CMS sign-in page. + +## Verified by + +- **web-console-next-tests** (the redirect map, run in this component's own + build) and the deploy's smoke check. diff --git a/apps/web-console-next/docs/runbook.md b/apps/web-console-next/docs/runbook.md index e1ebbd1..e96d161 100644 --- a/apps/web-console-next/docs/runbook.md +++ b/apps/web-console-next/docs/runbook.md @@ -2,31 +2,31 @@ ## How it deploys -Merges to `main` converge automatically: CI plans changed components -(`orun plan --changed`) and runs this component's lane via -`orun run --remote-state` with credential-free OIDC auth. The convergence -run is the deployment; the DAG orders this component after everything it -depends on. Failed lanes resume with `gh run rerun --failed`. - -## Rollback - -Revert the offending commit on `main`; the next convergence applies the -previous desired state. There is no out-of-band mutation to undo — the -repo is the source of truth. +A merge to `main` that changes `apps/web-console-next` deploys stage, then +prod, after the CMS. The build compiles the Worker and runs +`tests/web-console-next`; the smoke check asserts that +`/orgs/x/settings/billing?checkout=complete` answers `308` to the CMS billing +page of the same environment, and that following `/login` lands on the CMS's +Lumen sign-in view. ## Verify ```bash -curl -s -o /dev/null -w '%{http_code}\n' https://multi-tenant-saas-2-web-console-next-stage.nexo-7be.workers.dev -curl -s -o /dev/null -w '%{http_code}\n' https://multi-tenant-saas-2-web-console-next-prod.nexo-7be.workers.dev +C=https://multi-tenant-saas-2-web-console-next-stage.nexo-7be.workers.dev +curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' $C/ # 308 …-cms-stage…/admin +curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' "$C/auth/callback?x=1" # 308 …/auth/lumen/callback?x=1 ``` -Then probe the edge `/health` too — a green console does not imply a -healthy API. +## Change where an old page goes + +Edit `ROUTES` in `src/worker.ts` and the table in `tests/web-console-next` +together. ## Common failures -- **Build lane slow/failing**: console builds are the heaviest in the - repo; check the lane's build output before suspecting infrastructure. -- **Console up, API calls failing**: verify `api-edge` — the console is - static assets and survives an edge outage visually. +- **Smoke: "308 …" did not match.** The CMS Worker name or the account's + workers.dev subdomain changed: `CMS_WORKER_PREFIX` in `src/worker.ts` and + `workersDevSubdomain` in `component.yaml` must match the CMS. +- **Smoke: the final page does not name `LumenSignIn`.** The CMS is down, + answering an error, or its sign-in view was renamed; see + `apps/cms/docs/runbook.md`. diff --git a/apps/web-console-next/next-env.d.ts b/apps/web-console-next/next-env.d.ts deleted file mode 100644 index 40c3d68..0000000 --- a/apps/web-console-next/next-env.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -/// -/// - -// NOTE: This file should not be edited -// see https://nextjs.org/docs/app/building-your-application/configuring/typescript for more information. diff --git a/apps/web-console-next/next.config.mjs b/apps/web-console-next/next.config.mjs deleted file mode 100644 index 65f2bbc..0000000 --- a/apps/web-console-next/next.config.mjs +++ /dev/null @@ -1,48 +0,0 @@ -import path from "node:path"; -import { fileURLToPath } from "node:url"; - -const __dirname = path.dirname(fileURLToPath(import.meta.url)); - -/** @type {import('next').NextConfig} */ -const nextConfig = { - reactStrictMode: true, - // `@saas/sdk` is a workspace-source package: its `package.json` exports - // point at `./src/index.ts` and the file uses TS NodeNext-style `./*.js` - // import specifiers that resolve to the sibling `.ts` source. Next's - // webpack pipeline does not perform that pairing for source-mode workspace - // deps, so register an extension alias and run the package through SWC. - transpilePackages: ["@saas/sdk"], - webpack(config) { - config.resolve = config.resolve || {}; - config.resolve.extensionAlias = { - ...(config.resolve.extensionAlias || {}), - ".js": [".ts", ".tsx", ".js"], - }; - return config; - }, - // `output: "standalone"` is required by the @opennextjs/cloudflare adapter, - // which reads `.next/standalone/**` to bundle the server function before - // emitting Pages-compatible assets into `.open-next/assets/**`. - output: "standalone", - // Trace from the monorepo root so the standalone build pulls in workspace - // dependencies (e.g. @saas/contracts) instead of trying to resolve them - // from the per-app node_modules. - outputFileTracingRoot: path.join(__dirname, "../.."), - typescript: { - ignoreBuildErrors: false, - }, - eslint: { - // Lint runs separately via `pnpm lint`. Skip during `next build` to keep - // the build deterministic across Node/ESLint flat-config quirks. - ignoreDuringBuilds: true, - }, - env: { - NEXT_PUBLIC_DEPLOY_ENV: process.env.NEXT_PUBLIC_DEPLOY_ENV ?? "", - // M0 / Solo profile (MultiTenantSaas2 ships single-user). Build with - // NEXT_PUBLIC_SOLO_MODE=false to restore the full multi-tenant baseline. - // See specs/profiles/solo-m0.md. - NEXT_PUBLIC_SOLO_MODE: process.env.NEXT_PUBLIC_SOLO_MODE ?? "true", - }, -}; - -export default nextConfig; diff --git a/apps/web-console-next/open-next.config.ts b/apps/web-console-next/open-next.config.ts deleted file mode 100644 index 812ed70..0000000 --- a/apps/web-console-next/open-next.config.ts +++ /dev/null @@ -1,12 +0,0 @@ -// OpenNext Cloudflare adapter config for @saas/web-console-next. -// -// The orun `cloudflare-pages-turbo` component only consumes the assets -// directory the adapter emits (`.open-next/assets/**`) — it does NOT bind -// R2, KV, or D1 to this app. So we use the in-memory "dummy" overrides for -// the incremental cache, tag cache, and queue. This keeps the build hermetic -// and the per-env Pages projects (multi-tenant-saas-2-web-console-next-{dev,stage,prod}) -// publishable without any extra Cloudflare resources beyond the Pages project -// the component already provisions. -import { defineCloudflareConfig } from "@opennextjs/cloudflare/config"; - -export default defineCloudflareConfig({}); diff --git a/apps/web-console-next/package.json b/apps/web-console-next/package.json index 4378001..c9edb75 100644 --- a/apps/web-console-next/package.json +++ b/apps/web-console-next/package.json @@ -4,51 +4,14 @@ "private": true, "type": "module", "scripts": { - "dev": "next dev -p 3001", - "build": "next build && opennextjs-cloudflare build --skipBuild --skipWranglerConfigCheck && node scripts/check-worker-size.mjs", - "start": "next start -p 3001", - "typecheck": "tsc --noEmit", + "build": "tsc -p tsconfig.json", + "typecheck": "tsc --noEmit -p tsconfig.json", "lint": "eslint src" }, - "dependencies": { - "@hookform/resolvers": "^3.9.1", - "@opennextjs/aws": "3.6.2", - "@opennextjs/cloudflare": "1.0.4", - "@polar-sh/checkout": "^0.3.0", - "@radix-ui/react-dialog": "^1.1.2", - "@radix-ui/react-dropdown-menu": "^2.1.2", - "@radix-ui/react-label": "^2.1.0", - "@radix-ui/react-select": "^2.1.2", - "@radix-ui/react-slot": "^1.1.0", - "@radix-ui/react-tabs": "^1.1.1", - "@radix-ui/react-toast": "^1.2.2", - "@radix-ui/react-tooltip": "^1.1.3", - "@saas/contracts": "workspace:*", - "@saas/sdk": "workspace:*", - "@tanstack/react-query": "^5.62.7", - "class-variance-authority": "^0.7.1", - "clsx": "^2.1.1", - "cmdk": "^1.0.4", - "lucide-react": "^0.460.0", - "next": "15.0.3", - "next-themes": "^0.4.3", - "react": "19.0.0-rc-66855b96-20241106", - "react-dom": "19.0.0-rc-66855b96-20241106", - "react-hook-form": "^7.53.2", - "tailwind-merge": "^2.5.4", - "zod": "^3.23.8" - }, "devDependencies": { "@saas/eslint-config": "workspace:*", "@saas/tsconfig": "workspace:*", - "@types/node": "^22.9.0", - "@types/react": "npm:types-react@19.0.0-rc.1", - "@types/react-dom": "npm:types-react-dom@19.0.0-rc.1", - "autoprefixer": "^10.4.20", "eslint": "^9.27.0", - "eslint-config-next": "15.0.3", - "postcss": "^8.4.49", - "tailwindcss": "^3.4.14", "typescript": "^5.8.3", "wrangler": "^4.14.0" } diff --git a/apps/web-console-next/postcss.config.mjs b/apps/web-console-next/postcss.config.mjs deleted file mode 100644 index 2aa7205..0000000 --- a/apps/web-console-next/postcss.config.mjs +++ /dev/null @@ -1,6 +0,0 @@ -export default { - plugins: { - tailwindcss: {}, - autoprefixer: {}, - }, -}; diff --git a/apps/web-console-next/public/_headers b/apps/web-console-next/public/_headers deleted file mode 100644 index a27bdd5..0000000 --- a/apps/web-console-next/public/_headers +++ /dev/null @@ -1,14 +0,0 @@ -# PERF10 — immutable caching for content-hashed build assets. -# -# Next.js fingerprints every file under /_next/static/ (the hash is in the -# filename), so a content change always produces a new URL and stale cached -# copies become unreachable. They are therefore safe to cache for a year with -# no revalidation. The Cloudflare default for these assets is -# `public, max-age=0, must-revalidate`, which forces the browser to send a -# conditional request (304) for every chunk on every repeat visit — slow. -# -# Files in this `public/` directory are copied to the asset root -# (`.open-next/assets/`) by the @opennextjs/cloudflare adapter, where Pages -# honours `_headers`. HTML stays dynamic (SSR, `no-store`) and is unaffected. -/_next/static/* - Cache-Control: public, max-age=31536000, immutable diff --git a/apps/web-console-next/public/manifest.webmanifest b/apps/web-console-next/public/manifest.webmanifest deleted file mode 100644 index b91f28e..0000000 --- a/apps/web-console-next/public/manifest.webmanifest +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "Multi Tenant Saas 2 Console", - "short_name": "Multi Tenant Saas 2", - "description": "Control plane for your projects, environments, and entitlements.", - "start_url": "/orgs", - "scope": "/", - "display": "standalone", - "background_color": "#09090b", - "theme_color": "#09090b", - "orientation": "portrait-primary" -} diff --git a/apps/web-console-next/scripts/check-worker-size.mjs b/apps/web-console-next/scripts/check-worker-size.mjs deleted file mode 100644 index 9fb5cfb..0000000 --- a/apps/web-console-next/scripts/check-worker-size.mjs +++ /dev/null @@ -1,97 +0,0 @@ -#!/usr/bin/env node -// Console worker size guard (FT5 — specs/profiles/free-tier.md). -// -// The Workers Free plan caps a worker script at 3 MB gzipped, against 10 MB on -// Paid. Every other worker in this fleet gzips to 27–40 KiB and will never come -// near it. The OpenNext console is the exception: it is the only bundle whose -// size is a live constraint, and the only one where a few added dependencies -// can quietly make the free-tier deploy impossible. -// -// This runs in the console's own build lane, where the artifact already exists. -// The platform-limits suite cannot do it: measuring means building Next, which -// is minutes of work in a lane whose value is being cheap enough to always run. -// -// Two things it deliberately does NOT measure: -// -// - Static assets. They are served from the assets binding, are free and -// unlimited, and do not count toward the script size limit. -// - `.open-next/worker.js` on its own. That file is a ~2 KiB entry shim; the -// 48 MB of server-function code it pulls in is what actually ships. Gzipping -// the shim reports 1 KiB and passes any budget, which is worse than having -// no guard at all. -// -// So the measurement comes from `wrangler deploy --dry-run`, which performs the -// same bundling the real deploy does and reports the gzipped upload size that -// the platform will actually weigh. - -import { execFileSync } from "node:child_process"; -import { existsSync } from "node:fs"; -import { join, dirname } from "node:path"; -import { fileURLToPath } from "node:url"; - -const APP_DIR = join(dirname(fileURLToPath(import.meta.url)), ".."); - -/** Workers Free, per script, gzipped. Paid raises this to 10 MB. */ -const FREE_PLAN_LIMIT_KIB = 3 * 1024; - -/** - * The budget this bundle holds itself to, below the hard cap on purpose. - * - * Failing at the cap means failing at deploy time, on the free plan, with no - * warning — the failure mode this whole profile exists to avoid. The gap - * between budget and cap is the room to notice and react. - * - * Measured at 1880 KiB with `minify: true` (2296 KiB without). - */ -const BUDGET_KIB = 2400; - -if (!existsSync(join(APP_DIR, ".open-next", "worker.js"))) { - console.error("check-worker-size: no OpenNext output — run the build first."); - process.exit(2); -} - -let output; -try { - output = execFileSync( - "pnpm", - ["exec", "wrangler", "deploy", "--dry-run"], - { cwd: APP_DIR, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 10 * 60_000 }, - ); -} catch (error) { - const detail = /** @type {{ stdout?: string; stderr?: string }} */ (error); - console.error("check-worker-size: wrangler dry-run failed\n", detail.stderr ?? detail.stdout ?? error); - process.exit(2); -} - -// "Total Upload: 8944.37 KiB / gzip: 1879.69 KiB" -const match = /gzip:\s*([\d.]+)\s*KiB/.exec(output); -if (!match) { - console.error("check-worker-size: could not read the gzip size from wrangler output\n", output); - process.exit(2); -} - -const gzippedKiB = Number(match[1]); -const pctOfCap = (gzippedKiB / FREE_PLAN_LIMIT_KIB) * 100; - -// Always reported, not only on failure: the trend is the useful part, and a -// number that appears only when it is already too late is not a guard. -console.log( - `check-worker-size: ${gzippedKiB.toFixed(0)} KiB gzipped — ` + - `${pctOfCap.toFixed(0)}% of the free plan's ${FREE_PLAN_LIMIT_KIB} KiB cap ` + - `(budget ${BUDGET_KIB} KiB)`, -); - -if (gzippedKiB > BUDGET_KIB) { - console.error( - `\ncheck-worker-size: OVER BUDGET by ${(gzippedKiB - BUDGET_KIB).toFixed(0)} KiB.\n` + - `\nThe free plan refuses a script over ${FREE_PLAN_LIMIT_KIB} KiB gzipped, so this\n` + - `budget exists to be hit while there is still room to act. Options, cheapest first:\n` + - ` - Check what grew: a dependency reaching a server component lands in this\n` + - ` bundle, whereas one used only in a client component does not.\n` + - ` - Move work to a route that can be statically rendered — static assets are\n` + - ` served from the assets binding and cost nothing against this limit.\n` + - ` - Raise BUDGET_KIB deliberately, and record the new figure in\n` + - ` specs/profiles/free-tier.md so the headroom stays written down.\n`, - ); - process.exit(1); -} diff --git a/apps/web-console-next/scripts/console-artifact.mjs b/apps/web-console-next/scripts/console-artifact.mjs deleted file mode 100644 index 59b099b..0000000 --- a/apps/web-console-next/scripts/console-artifact.mjs +++ /dev/null @@ -1,227 +0,0 @@ -#!/usr/bin/env node -// THE CONSOLE, BUILT ONCE PER BASELINE (saas-console-artifact CA3/CA4). -// -// Since CA1/CA2 the console carries no product identity and no environment in -// its build — both come from the Worker's `vars` and host at runtime — so the -// OpenNext output of a baseline commit can be deployed as any product's -// console. A bootstrap's first console deploy downloads it instead of spending -// 4-5 minutes on a cold Next.js build. -// -// Artifacts are CONTENT-ADDRESSED: named by a hash of the sources that produce -// the build (this app, packages/, the lockfile and root build config), on one -// rolling `console-artifacts` release. An artifact can only ever be used for -// exactly the code it was built from, and nothing needs to know a tag. -// -// hash [--root ] print the source hash -// pack [--root ] [--out ] bundle the built worker -// (wrangler --dry-run) and tar it with the static assets as -// web-console-next-.tar.gz (+ .sha256); build first -// pin --baseline --repo (a bootstrap hook, run in -// [--root ] the product) if the -// baseline's sources have a published artifact, record it and the -// product's own source hash in console-artifact.pin.json -// build [--root ] (the component's build -// command) if a pin exists and this tree still hashes to it, fetch -// and verify the artifact; otherwise run the normal turbo build -// -// Node + the system `tar` and `gzip`. No dependencies. - -import { execFileSync } from "node:child_process"; -import { createHash } from "node:crypto"; -import fs from "node:fs"; -import os from "node:os"; -import path from "node:path"; -import { fileURLToPath } from "node:url"; - -const APP = "apps/web-console-next"; -const RELEASE = "console-artifacts"; -const PIN = "console-artifact.pin.json"; -// What decides the console's build output, relative to the repo root. -const SOURCES = [APP, "packages", "tooling/tsconfig", "package.json", "pnpm-lock.yaml", "pnpm-workspace.yaml", "turbo.json"]; -const SKIP_DIRS = new Set(["node_modules", ".next", ".open-next", "dist", ".turbo", ".wrangler", "coverage"]); -const SKIP_FILES = new Set([`${APP}/${PIN}`]); -// Byproducts a build or typecheck writes into the source tree: hashing them -// would make the publish job (which hashes after building) disagree with a -// bootstrap (which hashes a clean clone). -const SKIP_FILE_RE = /(\.tsbuildinfo|(^|\/)next-env\.d\.ts)$/; - -function arg(name, fallback) { - const i = process.argv.indexOf(`--${name}`); - return i >= 0 && process.argv[i + 1] !== undefined ? process.argv[i + 1] : fallback; -} - -function fail(message) { - console.error(`✕ console-artifact: ${message}`); - process.exit(1); -} - -function repoRoot() { - const given = arg("root"); - if (given) return path.resolve(given); - let dir = path.dirname(fileURLToPath(import.meta.url)); - while (!fs.existsSync(path.join(dir, "pnpm-workspace.yaml"))) { - const up = path.dirname(dir); - if (up === dir) fail("no pnpm-workspace.yaml above this script; pass --root"); - dir = up; - } - return dir; -} - -const sha256 = (data) => createHash("sha256").update(data).digest("hex"); - -/** sha256 over every source file's path and content, in a fixed order. */ -export function sourceHash(root) { - const files = []; - const walk = (rel) => { - const abs = path.join(root, rel); - if (!fs.existsSync(abs)) return; - const stat = fs.lstatSync(abs); - if (stat.isSymbolicLink()) return; - if (stat.isDirectory()) { - if (SKIP_DIRS.has(path.basename(rel))) return; - for (const name of fs.readdirSync(abs)) walk(rel ? `${rel}/${name}` : name); - } else if (stat.isFile() && !SKIP_FILES.has(rel) && !SKIP_FILE_RE.test(rel)) { - files.push(rel); - } - }; - for (const source of SOURCES) walk(source); - files.sort(); - const h = createHash("sha256"); - for (const rel of files) h.update(`${rel}\0${sha256(fs.readFileSync(path.join(root, rel)))}\n`); - return h.digest("hex").slice(0, 32); -} - -const assetName = (hash) => `web-console-next-${hash}.tar.gz`; -const releaseUrl = (repo) => `https://github.com/${repo}/releases/download/${RELEASE}`; - -function pack() { - const root = repoRoot(); - const hash = sourceHash(root); - const app = path.join(root, APP); - for (const required of ["worker.js", "assets"]) { - if (!fs.existsSync(path.join(app, ".open-next", required))) fail(`${APP}/.open-next/${required} is missing: build first`); - } - const out = path.resolve(arg("out", "dist/console-artifact")); - fs.mkdirSync(out, { recursive: true }); - const work = fs.mkdtempSync(path.join(os.tmpdir(), "console-artifact-pack-")); - try { - // BUNDLE HERE, WHERE THE BUILD IS. OpenNext's output require()s files by - // ABSOLUTE build-machine paths (/home/runner/work//…/.open-next/…), - // which `wrangler deploy` resolves when it bundles — so the raw - // .open-next only deploys on the machine, at the path, that built it. - // Bundling on this machine resolves them; the artifact is the - // self-contained worker plus the static assets — exactly what a deploy - // uploads — and re-bundling it in a product's deploy is a no-op. - const wrangler = path.join(app, "node_modules", ".bin", "wrangler"); - if (!fs.existsSync(wrangler)) fail(`${wrangler} is missing: install the workspace first`); - execFileSync(wrangler, ["deploy", "--dry-run", "--config", "wrangler.jsonc", "--outdir", path.join(work, "bundle")], { - cwd: app, - stdio: ["ignore", "ignore", "inherit"], - }); - const bundled = path.join(work, "bundle", "worker.js"); - if (!fs.existsSync(bundled)) fail("wrangler produced no bundled worker.js"); - if (/require\(\s*["']\//.test(fs.readFileSync(bundled, "utf8"))) { - fail("the bundled worker still require()s an absolute path; it would only run on this machine"); - } - const stage = path.join(work, "stage", ".open-next"); - fs.mkdirSync(stage, { recursive: true }); - fs.copyFileSync(bundled, path.join(stage, "worker.js")); - fs.cpSync(path.join(app, ".open-next", "assets"), path.join(stage, "assets"), { recursive: true }); - - const name = assetName(hash); - const raw = path.join(out, name.replace(/\.gz$/, "")); - // Deterministic: the same build packs to the same bytes. - execFileSync("tar", ["--sort=name", "--mtime=@0", "--owner=0", "--group=0", "--numeric-owner", "-cf", raw, "-C", path.join(work, "stage"), ".open-next"]); - execFileSync("gzip", ["-n", "-9", "-f", raw]); - const tarball = path.join(out, name); - const digest = sha256(fs.readFileSync(tarball)); - fs.writeFileSync(`${tarball}.sha256`, `${digest} ${name}\n`); - console.log(`✓ ${name} ${(fs.statSync(tarball).size / 1e6).toFixed(1)} MB sha256:${digest}`); - console.log(`asset=${name}`); - } finally { - fs.rmSync(work, { recursive: true, force: true }); - } -} - -async function get(url) { - if (url.startsWith("file://")) return fs.readFileSync(fileURLToPath(url)); - const res = await fetch(url, { redirect: "follow" }); - if (!res.ok) { - const err = new Error(`GET ${url}: HTTP ${res.status}`); - err.status = res.status; - throw err; - } - return Buffer.from(await res.arrayBuffer()); -} - -async function pin() { - const baseline = arg("baseline"); - const repo = arg("repo"); - if (!baseline || !repo) fail("pin needs --baseline and --repo "); - const root = repoRoot(); - const name = assetName(sourceHash(path.resolve(baseline))); - const base = arg("from", releaseUrl(repo)); - let digest; - try { - digest = (await get(`${base}/${name}.sha256`)).toString("utf8").trim().split(/\s+/)[0]; - } catch (err) { - // No artifact for this baseline's sources: the product builds the console - // itself, exactly as before. Not an error. - console.log(`· no prebuilt console for this baseline (${err.message}); the product will build it`); - fs.rmSync(path.join(root, APP, PIN), { force: true }); - return; - } - if (!/^[0-9a-f]{64}$/.test(digest ?? "")) fail(`${name}.sha256 is not a sha256`); - const record = { url: `${base}/${name}`, sha256: digest, sourceHash: sourceHash(root) }; - fs.writeFileSync(path.join(root, APP, PIN), JSON.stringify(record, null, 2) + "\n"); - console.log(`✓ pinned ${name} for this product's console (sources ${record.sourceHash})`); -} - -function turboBuild(root) { - execFileSync("pnpm", ["exec", "turbo", "run", "build", "--filter=@saas/web-console-next"], { cwd: root, stdio: "inherit" }); -} - -async function build() { - const root = repoRoot(); - const pinFile = path.join(root, APP, PIN); - if (!fs.existsSync(pinFile)) return turboBuild(root); - const record = JSON.parse(fs.readFileSync(pinFile, "utf8")); - const current = sourceHash(root); - if (current !== record.sourceHash) { - console.log(`· the console's sources changed since the pin (${record.sourceHash} → ${current}); building from source`); - return turboBuild(root); - } - let tarball; - try { - tarball = await get(record.url); - } catch (err) { - console.log(`· ${err.message}; building from source`); - return turboBuild(root); - } - const actual = sha256(tarball); - // A digest mismatch is never papered over with a build: something served - // bytes other than the ones that were published. - if (actual !== record.sha256) fail(`${record.url}: sha256 ${actual}, pinned ${record.sha256}`); - const work = fs.mkdtempSync(path.join(os.tmpdir(), "console-artifact-")); - try { - fs.writeFileSync(path.join(work, "a.tar.gz"), tarball); - execFileSync("tar", ["-xzf", path.join(work, "a.tar.gz"), "-C", work, "--no-same-owner"]); - if (!fs.existsSync(path.join(work, ".open-next", "worker.js"))) fail(`${record.url} holds no .open-next/worker.js`); - const app = path.join(root, APP); - fs.rmSync(path.join(app, ".open-next"), { recursive: true, force: true }); - fs.renameSync(path.join(work, ".open-next"), path.join(app, ".open-next")); - } finally { - fs.rmSync(work, { recursive: true, force: true }); - } - console.log(`✓ prebuilt console ${path.basename(record.url)} (sha256:${actual}); no build`); -} - -const command = process.argv[2]; -if (command === "hash") console.log(sourceHash(repoRoot())); -else if (command === "pack") pack(); -else if (command === "pin") await pin(); -else if (command === "build") await build(); -else { - console.error("usage: console-artifact.mjs hash|pack|pin|build [--root ] … (see the header)"); - process.exit(2); -} diff --git a/apps/web-console-next/src/app/(app)/account/page.tsx b/apps/web-console-next/src/app/(app)/account/page.tsx deleted file mode 100644 index 8c18c1b..0000000 --- a/apps/web-console-next/src/app/(app)/account/page.tsx +++ /dev/null @@ -1,186 +0,0 @@ -"use client"; - -import * as React from "react"; -import { useRouter } from "next/navigation"; -import { LogOut, User2 } from "lucide-react"; -import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; -import { Skeleton } from "@/components/ui/skeleton"; -import { Button } from "@/components/ui/button"; -import { Input } from "@/components/ui/input"; -import { Label } from "@/components/ui/label"; -import { AccountTabs } from "@/components/account/account-tabs"; -import { useQueryClient } from "@tanstack/react-query"; -import { wrap } from "@/lib/api"; -import { useApiQuery, qk } from "@/lib/query"; -import { useSession } from "@/lib/session"; -import { useUnsavedChangesGuard } from "@/lib/use-unsaved-guard"; -import { useToast } from "@/components/ui/toast"; -import { - buildProfilePatch, - validateDisplayName, - initials, - DISPLAY_NAME_MAX, -} from "@/components/account/profile"; -import type { AuthUser } from "@saas/contracts/auth"; - -export default function AccountPage() { - const { client, setToken } = useSession(); - const router = useRouter(); - const { toast } = useToast(); - const qc = useQueryClient(); - - // PERF11: profile is read through react-query so revisits paint instantly from - // cache (stale-while-revalidate) instead of a manual uncached refetch. - const profile = useApiQuery(qk.profile(), () => - wrap(async () => (await client.auth.getProfile()).user), - ); - const user: AuthUser | null = profile.data; - const loading = profile.loading; - const error = profile.error?.message ?? null; - const [name, setName] = React.useState(""); - const [saving, setSaving] = React.useState(false); - - // Seed the editable field from the (cached) profile. Keyed on the saved - // displayName so a user's in-progress edit is never clobbered by a background - // revalidation; a successful save updates the cache and re-seeds to the new value. - React.useEffect(() => { - if (user) setName(user.displayName ?? ""); - }, [user?.id, user?.displayName]); - - const nameValid = validateDisplayName(name); - const dirty = user ? buildProfilePatch(user.displayName, name) !== null : false; - useUnsavedChangesGuard(dirty && !saving); - - const save = async () => { - if (!user || !nameValid.ok) return; - const patch = buildProfilePatch(user.displayName, name); - if (!patch) return; - setSaving(true); - const r = await wrap(() => client.auth.updateProfile(patch)); - setSaving(false); - if (!r.ok) { - toast({ kind: "error", title: "Save failed", description: r.error.message }); - return; - } - // Write the saved user back to the shared cache (instant, no refetch); the - // seed effect re-syncs `name` to the persisted displayName. - qc.setQueryData(qk.profile(), r.data.user); - toast({ kind: "success", title: "Profile updated" }); - }; - - const signOut = async () => { - // Best-effort server logout, then clear the local token regardless. - await wrap(() => client.auth.logout()); - setToken(null); - toast({ kind: "success", title: "Signed out" }); - router.push("/login"); - }; - - return ( -
-
-

Account

-

Manage your profile and session.

-
- - - - {loading ? ( - - - - - - - - ) : error ? ( - - - Failed to load profile - {error} - - - ) : user ? ( - <> - - - Profile - Your identity across every organization. - - -
-
- {initials(user.displayName, user.email)} -
-
-
{user.displayName ?? "—"}
-
{user.email}
-
-
- -
-
- - -

- Email changes aren't available from the console yet. -

-
-
- - setName(e.target.value)} - /> - {!nameValid.ok ? ( -

{nameValid.message}

- ) : null} -
-
- -
- - {dirty ? ( - - ) : null} -
- -
- - {user.id} -
-
-
- - - - Session - Sign out of the console on this device. - - - - - - - ) : null} -
- ); -} diff --git a/apps/web-console-next/src/app/(app)/account/security/page.tsx b/apps/web-console-next/src/app/(app)/account/security/page.tsx deleted file mode 100644 index 103d244..0000000 --- a/apps/web-console-next/src/app/(app)/account/security/page.tsx +++ /dev/null @@ -1,148 +0,0 @@ -"use client"; - -import * as React from "react"; -import { ShieldCheck } from "lucide-react"; -import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; -import { Skeleton } from "@/components/ui/skeleton"; -import { Badge } from "@/components/ui/badge"; -import { Button } from "@/components/ui/button"; -import { EmptyState } from "@/components/ui/empty-state"; -import { wrap } from "@/lib/api"; -import { useSession } from "@/lib/session"; -import { AccountTabs } from "@/components/account/account-tabs"; -import { - appendSecurityPage, - EMPTY_SECURITY_EVENTS, - hasMoreSecurityEvents, - toSecurityRow, - type SecurityEventsState, -} from "@/components/security/security-events"; - -/** - * Account security activity. - * - * Actor/account-scoped (NOT org-scoped): there is no `OrgScope`, no `orgId`, - * and no org filters. The SDK call hits `/v1/auth/security-events` for the - * authenticated actor. Cursor pagination mirrors the audit log — the opaque - * `nextCursor` from `listPage` is passed back verbatim for "Load more". - */ -export default function AccountSecurityPage() { - const { client } = useSession(); - - const [state, setState] = React.useState(EMPTY_SECURITY_EVENTS); - const [loading, setLoading] = React.useState(true); - const [loadingMore, setLoadingMore] = React.useState(false); - const [error, setError] = React.useState<{ code: string; message: string } | null>(null); - - const loadFirstPage = React.useCallback(async () => { - setLoading(true); - setError(null); - const res = await wrap(() => client.securityEvents.listPage()); - if (res.ok) { - setState(appendSecurityPage(EMPTY_SECURITY_EVENTS, res.data, /* reset */ true)); - } else { - setError({ code: res.error.code, message: res.error.message }); - setState(EMPTY_SECURITY_EVENTS); - } - setLoading(false); - }, [client]); - - React.useEffect(() => { - void loadFirstPage(); - }, [loadFirstPage]); - - const loadMore = React.useCallback(async () => { - if (state.cursor === null) return; - const cursor = state.cursor; - setLoadingMore(true); - const res = await wrap(() => client.securityEvents.listPage({ cursor })); - if (res.ok) { - setState((prev) => appendSecurityPage(prev, res.data)); - } else { - setError({ code: res.error.code, message: res.error.message }); - } - setLoadingMore(false); - }, [client, state.cursor]); - - const rows = state.events.map(toSecurityRow); - - return ( -
-
-

Account

-

Manage your profile and session.

-
- - - -
-

Security activity

-

- Recent authentication and session events on your account, newest - first. Sensitive material (codes, tokens, hashes) is never shown. -

-
- - {loading ? ( - - - {Array.from({ length: 5 }).map((_, i) => ( - - ))} - - - ) : error ? ( - - - {error.code} - {error.message} - - - ) : rows.length === 0 ? ( - - ) : ( -
- {rows.map((r) => ( - -
-
-
- - {r.eventType} - - - {r.badge.label} - -
-
- {r.ip} · {r.userAgent} -
-
-
- {r.occurredAtLabel} -
-
-
- ))} - - {hasMoreSecurityEvents(state) ? ( -
- -
- ) : null} -
- )} -
- ); -} diff --git a/apps/web-console-next/src/app/(app)/error.tsx b/apps/web-console-next/src/app/(app)/error.tsx deleted file mode 100644 index 2de8528..0000000 --- a/apps/web-console-next/src/app/(app)/error.tsx +++ /dev/null @@ -1,51 +0,0 @@ -"use client"; - -import * as React from "react"; -import { useRouter } from "next/navigation"; -import { AlertTriangle } from "lucide-react"; -import { Button } from "@/components/ui/button"; - -/** - * Segment error boundary for the authenticated app. Turns an unhandled - * client-side exception on any page into a recoverable card (instead of the - * bare "Application error" white-screen), and — crucially — gives an escape - * back to the org picker so a single bad org/page can't trap the user. - */ -export default function AppError({ - error, - reset, -}: { - error: Error & { digest?: string }; - reset: () => void; -}) { - const router = useRouter(); - React.useEffect(() => { - // Surface for diagnostics; the boundary already prevents the crash. - console.error("App segment error:", error); - }, [error]); - - return ( -
-
-
- -
-
-

Something went wrong

-

- This page hit an unexpected error. You can retry, or head back to your organizations. -

- {error.digest && ( -

ref: {error.digest}

- )} -
-
- - -
-
-
- ); -} diff --git a/apps/web-console-next/src/app/(app)/layout.tsx b/apps/web-console-next/src/app/(app)/layout.tsx deleted file mode 100644 index d760321..0000000 --- a/apps/web-console-next/src/app/(app)/layout.tsx +++ /dev/null @@ -1,90 +0,0 @@ -"use client"; - -import * as React from "react"; -import { useRouter } from "next/navigation"; -import { Sidebar } from "@/components/shell/sidebar"; -import { Topbar } from "@/components/shell/topbar"; -import { BottomTabs } from "@/components/shell/bottom-tabs"; -import { LastOrgRecorder } from "@/components/shell/last-org-recorder"; -import { Skeleton } from "@/components/ui/skeleton"; -import { useRequireAuth } from "@/lib/use-async"; -import { useSession } from "@/lib/session"; -import { useApiQuery, qk } from "@/lib/query"; -import { wrap } from "@/lib/api"; - -/** - * App shell. The frame (sidebar + topbar rails) paints immediately so there's - * no full-screen blank flash; the data-dependent shell content and page - * children mount only once the session token has hydrated (`ready`), which - * avoids firing requests with no token. `useRequireAuth` still redirects to - * /login when there is genuinely no token (Task 0130 / PERF1). - * - * On mobile the desktop sidebar collapses (it's `hidden md:flex`); navigation - * is provided by the topbar hamburger drawer and the bottom tab bar, so the - * main column reserves bottom space for the tab bar + home-indicator inset. - */ -export default function AppLayout({ children }: { children: React.ReactNode }) { - const ready = useRequireAuth(); - return ( -
- {ready ? ( - - ) : ( -
- ); -} - -/** - * Invisible guard: the console has no working view without an organization, so - * an authenticated user with zero orgs is sent to the mandatory `/onboarding` - * flow (create the parent org + pick a plan) from anywhere in the shell. Backed - * by the shared `orgs` query the shell already fetches, so this adds no extra - * request; on fetch errors it stays put rather than guessing. - */ -function OnboardingGate() { - const router = useRouter(); - const { client } = useSession(); - const orgs = useApiQuery(qk.orgs(), () => - wrap(async () => (await client.organizations.list()).organizations), - ); - React.useEffect(() => { - if (orgs.data && orgs.data.length === 0) router.replace("/onboarding"); - }, [orgs.data, router]); - return null; -} - -function ShellSkeleton() { - return ( -
-
- - -
-
- - -
-
- ); -} diff --git a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/api-keys/page.tsx b/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/api-keys/page.tsx deleted file mode 100644 index 688ef62..0000000 --- a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/api-keys/page.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { redirect } from "next/navigation"; - -/** - * Compatibility redirect. Organization administration moved under the dedicated - * Settings surface; this keeps old links to `/orgs/[slug]/api-keys` working. - */ -export default function LegacyRedirect({ params }: { params: { orgSlug: string } }) { - redirect(`/orgs/${params.orgSlug}/settings/api-keys`); -} diff --git a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/audit/page.tsx b/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/audit/page.tsx deleted file mode 100644 index e778b22..0000000 --- a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/audit/page.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { redirect } from "next/navigation"; - -/** - * Compatibility redirect. Organization administration moved under the dedicated - * Settings surface; this keeps old links to `/orgs/[slug]/audit` working. - */ -export default function LegacyRedirect({ params }: { params: { orgSlug: string } }) { - redirect(`/orgs/${params.orgSlug}/settings/audit`); -} diff --git a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/billing/page.tsx b/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/billing/page.tsx deleted file mode 100644 index 1f4010a..0000000 --- a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/billing/page.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { redirect } from "next/navigation"; - -/** - * Compatibility redirect. Organization administration moved under the dedicated - * Settings surface; this keeps old links to `/orgs/[slug]/billing` working. - */ -export default function LegacyRedirect({ params }: { params: { orgSlug: string } }) { - redirect(`/orgs/${params.orgSlug}/settings/billing`); -} diff --git a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/config/page.tsx b/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/config/page.tsx deleted file mode 100644 index 0de8ed0..0000000 --- a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/config/page.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { redirect } from "next/navigation"; - -/** - * Compatibility redirect. Organization administration moved under the dedicated - * Settings surface; this keeps old links to `/orgs/[slug]/config` working. - */ -export default function LegacyRedirect({ params }: { params: { orgSlug: string } }) { - redirect(`/orgs/${params.orgSlug}/settings/config`); -} diff --git a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/invitations/page.tsx b/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/invitations/page.tsx deleted file mode 100644 index b4759f0..0000000 --- a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/invitations/page.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { redirect } from "next/navigation"; - -/** - * Compatibility redirect. Organization administration moved under the dedicated - * Settings surface; this keeps old links to `/orgs/[slug]/invitations` working. - */ -export default function LegacyRedirect({ params }: { params: { orgSlug: string } }) { - redirect(`/orgs/${params.orgSlug}/settings/invitations`); -} diff --git a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/members/page.tsx b/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/members/page.tsx deleted file mode 100644 index db37ca9..0000000 --- a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/members/page.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { redirect } from "next/navigation"; - -/** - * Compatibility redirect. Organization administration moved under the dedicated - * Settings surface; this keeps old links to `/orgs/[slug]/members` working. - */ -export default function LegacyRedirect({ params }: { params: { orgSlug: string } }) { - redirect(`/orgs/${params.orgSlug}/settings/members`); -} diff --git a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/page.tsx b/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/page.tsx deleted file mode 100644 index 45d43c5..0000000 --- a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/page.tsx +++ /dev/null @@ -1,8 +0,0 @@ -import { redirect } from "next/navigation"; -import { SOLO_MODE } from "@/lib/solo-mode"; - -export default function OrgRoot({ params }: { params: { orgSlug: string } }) { - // The org root resolves to the profile's home surface. Baseline → Projects; - // Solo → the Account (settings) surface, since projects are suppressed. - redirect(`/orgs/${params.orgSlug}/${SOLO_MODE ? "settings" : "projects"}`); -} diff --git a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/projects/[projectSlug]/config/page.tsx b/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/projects/[projectSlug]/config/page.tsx deleted file mode 100644 index 6499d4d..0000000 --- a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/projects/[projectSlug]/config/page.tsx +++ /dev/null @@ -1,59 +0,0 @@ -"use client"; - -import * as React from "react"; -import { useParams } from "next/navigation"; -import { SlidersHorizontal } from "lucide-react"; -import { OrgScope } from "@/components/shell/org-scope"; -import { Card, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; -import { Skeleton } from "@/components/ui/skeleton"; -import { ConfigSurface } from "@/components/config/config-surface"; -import { wrap } from "@/lib/api"; -import { useSession } from "@/lib/session"; -import { useApiQuery, qk } from "@/lib/query"; - -export default function ProjectConfigPage() { - const params = useParams<{ orgSlug: string; projectSlug: string }>(); - const orgSlug = params?.orgSlug ?? ""; - const projectSlug = params?.projectSlug ?? ""; - return ( - - {(org) => } - - ); -} - -function Inner({ orgId, projectSlug }: { orgId: string; projectSlug: string }) { - const { client } = useSession(); - const projects = useApiQuery(qk.projects(orgId), () => - wrap(async () => (await client.projects.list(orgId)).projects), - ); - const project = projects.data?.find((p) => p.slug === projectSlug) ?? null; - - if (projects.loading) return ; - if (!project) { - return ( - - - Project not found - No project matches “{projectSlug}”. - - - ); - } - - return ( -
-
-
- -

Config · {project.name}

-
-

- Project-scoped settings, feature flags, and secrets. Environment scope lives on each - environment's page. -

-
- -
- ); -} diff --git a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/projects/[projectSlug]/environments/[envSlug]/page.tsx b/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/projects/[projectSlug]/environments/[envSlug]/page.tsx deleted file mode 100644 index 590a332..0000000 --- a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/projects/[projectSlug]/environments/[envSlug]/page.tsx +++ /dev/null @@ -1,109 +0,0 @@ -"use client"; - -import * as React from "react"; -import { useParams } from "next/navigation"; -import { Boxes } from "lucide-react"; -import { OrgScope } from "@/components/shell/org-scope"; -import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; -import { Badge } from "@/components/ui/badge"; -import { Skeleton } from "@/components/ui/skeleton"; -import { ConfigSurface } from "@/components/config/config-surface"; -import { wrap } from "@/lib/api"; -import { useSession } from "@/lib/session"; -import { useApiQuery, qk } from "@/lib/query"; - -export default function EnvironmentDetail() { - const params = useParams<{ orgSlug: string; projectSlug: string; envSlug: string }>(); - const orgSlug = params?.orgSlug ?? ""; - const projectSlug = params?.projectSlug ?? ""; - const envSlug = params?.envSlug ?? ""; - return ( - - {(org) => } - - ); -} - -function Inner({ - orgId, - projectSlug, - envSlug, -}: { - orgId: string; - projectSlug: string; - envSlug: string; -}) { - const { client } = useSession(); - const projects = useApiQuery(qk.projects(orgId), () => - wrap(async () => (await client.projects.list(orgId)).projects), - ); - const project = projects.data?.find((p) => p.slug === projectSlug) ?? null; - const envs = useApiQuery( - qk.environments(orgId, project?.id ?? "pending"), - () => wrap(async () => (await client.environments.list(orgId, project!.id)).environments), - { enabled: !!project }, - ); - const env = envs.data?.find((e) => e.slug === envSlug) ?? null; - - if (projects.loading || envs.loading) return ; - if (!project || !env) { - return ( - - - Environment not found - - No environment matches {projectSlug}/{envSlug}. - - - - ); - } - - return ( -
-
- -

{env.name}

- {env.status} -
- - - Identity - - -
- - - - - - - - -
-
-
- -
-
-

Configuration

-

- Settings, feature flags, and secrets scoped to this environment. -

-
- -
-
- ); -} - -function Pair({ k, v, mono = false }: { k: string; v: string; mono?: boolean }) { - return ( -
-
{k}
-
{v}
-
- ); -} diff --git a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/projects/[projectSlug]/environments/page.tsx b/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/projects/[projectSlug]/environments/page.tsx deleted file mode 100644 index 79114e0..0000000 --- a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/projects/[projectSlug]/environments/page.tsx +++ /dev/null @@ -1,226 +0,0 @@ -"use client"; - -import * as React from "react"; -import Link from "next/link"; -import { useParams } from "next/navigation"; -import { z } from "zod"; -import { Plus, Boxes } from "lucide-react"; -import { OrgScope } from "@/components/shell/org-scope"; -import { Button } from "@/components/ui/button"; -import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; -import { Skeleton } from "@/components/ui/skeleton"; -import { Badge } from "@/components/ui/badge"; -import { EmptyState } from "@/components/ui/empty-state"; -import { - Dialog, - DialogContent, - DialogDescription, - DialogHeader, - DialogTitle, - DialogTrigger, -} from "@/components/ui/dialog"; -import { ZodForm } from "@/components/ui/zod-form"; -import { PreconditionInsight } from "@/components/precondition/insight"; -import { ArchiveMenu } from "@/components/settings/archive-menu"; -import { removeById } from "@/components/settings/archive"; -import { useQueryClient } from "@tanstack/react-query"; -import { useSession } from "@/lib/session"; -import { useApiQuery, qk } from "@/lib/query"; -import { useToast } from "@/components/ui/toast"; -import { wrap, type ApiErrorBody } from "@/lib/api"; -import type { PublicEnvironment } from "@saas/contracts/projects"; - -const schema = z.object({ - name: z.string().min(2).max(48), - slug: z.string().regex(/^[a-z0-9-]*$/, "lowercase, digits, hyphens").max(32).optional(), -}); - -export default function EnvironmentsPage() { - const params = useParams<{ orgSlug: string; projectSlug: string }>(); - const orgSlug = params?.orgSlug ?? ""; - const projectSlug = params?.projectSlug ?? ""; - return ( - - {(org) => } - - ); -} - -function Inner({ orgId, orgSlug, projectSlug }: { orgId: string; orgSlug: string; projectSlug: string }) { - const { client } = useSession(); - const { toast } = useToast(); - const qc = useQueryClient(); - - // Shares the `projects` cache key with the projects list page, so navigating - // project-list → environments resolves the project synchronously from cache. - const projectsList = useApiQuery(qk.projects(orgId), () => - wrap(async () => (await client.projects.list(orgId)).projects), - ); - const project = React.useMemo( - () => projectsList.data?.find((p) => p.slug === projectSlug) ?? null, - [projectsList.data, projectSlug], - ); - - const envKey = qk.environments(orgId, project?.id ?? "pending"); - const envs = useApiQuery( - envKey, - () => wrap(async () => (await client.environments.list(orgId, project!.id)).environments), - { enabled: !!project }, - ); - - const [open, setOpen] = React.useState(false); - const [precondition, setPrecondition] = React.useState(null); - - // The query cache is the source of truth; archive mutates it optimistically. - const items = envs.data ?? []; - - const archive = async (env: PublicEnvironment) => { - if (!project) return; - const previous = qc.getQueryData(envKey); - qc.setQueryData(envKey, (cur) => removeById(cur ?? [], env.id)); // optimistic - const r = await wrap(() => client.environments.archive(orgId, project.id, env.id)); - if (!r.ok) { - qc.setQueryData(envKey, previous); // rollback - toast({ kind: "error", title: "Archive failed", description: r.error.message }); - return; - } - toast({ kind: "success", title: `Archived ${env.name}` }); - }; - - if (projectsList.loading) { - return ; - } - if (!project) { - return ( - - ); - } - - return ( -
-
-
-

- Environments · {project.name} -

-

- Deployment targets within this project. Each gets isolated config and bindings. -

-
- - - - - - - Create environment - - Environments are isolated deployment targets within this project. - - - setOpen(false) }} - onSubmit={async (v) => { - const payload: { name: string; slug?: string } = { name: v.name }; - if (v.slug) payload.slug = v.slug; - const r = await wrap(async () => - (await client.environments.create(orgId, project.id, payload)).environment, - ); - if (!r.ok) { - if (r.error.code === "precondition_failed") setPrecondition(r.error); - else toast({ kind: "error", title: "Create failed", description: r.error.message }); - return; - } - toast({ kind: "success", title: "Environment created" }); - setOpen(false); - envs.reload(); - }} - /> - - -
- - {precondition && ( - setPrecondition(null)} - /> - )} - - {envs.loading ? ( -
- {Array.from({ length: 3 }).map((_, i) => ( - - - - - - - ))} -
- ) : envs.error ? ( - - - {envs.error.code} - {envs.error.message} - - - ) : items.length === 0 ? ( - setOpen(true) }} - /> - ) : ( -
- {items.map((e) => ( -
-
- archive(e)} - /> -
- - - -
- {e.name} - {e.status} -
- {e.slug} -
- -
- Updated {new Date(e.updatedAt).toLocaleDateString()} -
-
-
- -
- ))} -
- )} -
- ); -} diff --git a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/projects/[projectSlug]/git/page.tsx b/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/projects/[projectSlug]/git/page.tsx deleted file mode 100644 index f0c46c2..0000000 --- a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/projects/[projectSlug]/git/page.tsx +++ /dev/null @@ -1,355 +0,0 @@ -"use client"; - -import * as React from "react"; - -import { useParams } from "next/navigation"; -import { GitBranch, Github, Plus, Search } from "lucide-react"; -import type { - PublicConnection, - PublicRepoLink, - PublicRepository, -} from "@saas/contracts/integrations"; -import type { PublicEnvironment } from "@saas/contracts/projects"; -import { OrgScope } from "@/components/shell/org-scope"; -import { Badge } from "@/components/ui/badge"; -import { Button } from "@/components/ui/button"; -import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; -import { ConfirmDialog } from "@/components/ui/confirm-dialog"; -import { - Dialog, - DialogContent, - DialogDescription, - DialogHeader, - DialogTitle, -} from "@/components/ui/dialog"; -import { EmptyState } from "@/components/ui/empty-state"; -import { Input } from "@/components/ui/input"; -import { Skeleton } from "@/components/ui/skeleton"; -import { PreconditionInsight } from "@/components/precondition/insight"; -import { useToast } from "@/components/ui/toast"; -import { wrap, type ApiErrorBody } from "@/lib/api"; -import { useSession } from "@/lib/session"; -import { useApiQuery, qk } from "@/lib/query"; -import { suggestBranchEnvMap } from "@/components/integrations/branch-map"; - -export default function ProjectGitPage() { - const params = useParams<{ orgSlug: string; projectSlug: string }>(); - const orgSlug = params?.orgSlug ?? ""; - const projectSlug = params?.projectSlug ?? ""; - return ( - - {(org) => } - - ); -} - -function Inner({ orgId, orgSlug, projectSlug }: { orgId: string; orgSlug: string; projectSlug: string }) { - const { client } = useSession(); - const { toast } = useToast(); - - const projectsList = useApiQuery(qk.projects(orgId), () => - wrap(async () => (await client.projects.list(orgId)).projects), - ); - const project = React.useMemo( - () => projectsList.data?.find((p) => p.slug === projectSlug) ?? null, - [projectsList.data, projectSlug], - ); - - const connections = useApiQuery(qk.integrations(orgId), () => - wrap(async () => (await client.integrations.list(orgId)).connections), - ); - const activeConnection: PublicConnection | null = - connections.data?.find((c) => c.status === "active") ?? null; - - const linksKey = qk.repoLinks(orgId, project?.id ?? "pending"); - const links = useApiQuery( - linksKey, - () => wrap(async () => (await client.integrations.listRepoLinks(orgId, project!.id)).repoLinks), - { enabled: !!project }, - ); - const environments = useApiQuery( - qk.environments(orgId, project?.id ?? "pending"), - () => wrap(async () => (await client.environments.list(orgId, project!.id)).environments), - { enabled: !!project }, - ); - - const [pickerOpen, setPickerOpen] = React.useState(false); - const [gateError, setGateError] = React.useState(null); - const [unlinkTarget, setUnlinkTarget] = React.useState(null); - - const linkRepo = async (repo: PublicRepository) => { - if (!project || !activeConnection) return; - setGateError(null); - const branchEnvMap = suggestBranchEnvMap( - repo.defaultBranch, - (environments.data ?? []) as PublicEnvironment[], - ); - const r = await wrap(() => - client.integrations.createRepoLink(orgId, project.id, { - connectionId: activeConnection.id, - repoExternalId: repo.externalId, - repoFullName: repo.fullName, - ...(repo.defaultBranch ? { defaultBranch: repo.defaultBranch } : {}), - branchEnvMap, - }), - ); - if (!r.ok) { - if (r.status === 412) { - setGateError(r.error); - setPickerOpen(false); - } else { - toast({ kind: "error", title: "Could not link repository", description: r.error.message }); - } - return; - } - setPickerOpen(false); - toast({ kind: "success", title: `Linked ${repo.fullName}` }); - links.reload(); - }; - - const unlink = async (link: PublicRepoLink) => { - if (!project) return; - const r = await wrap(() => client.integrations.unlinkRepoLink(orgId, project.id, link.id)); - if (!r.ok) { - toast({ kind: "error", title: "Unlink failed", description: r.error.message }); - return; - } - toast({ kind: "success", title: `Unlinked ${link.repoFullName}` }); - links.reload(); - }; - - const loading = projectsList.loading || connections.loading || (!!project && links.loading); - - return ( -
-
-
-
- -

Git

-
-

- Link repositories to this project and map branches to environments. Pushes and pull - requests on linked repos emit project-scoped events. -

-
- {activeConnection ? ( - - ) : null} -
- - {gateError ? ( - setGateError(null)} - /> - ) : null} - - {loading ? ( - - - {Array.from({ length: 3 }).map((_, i) => ( - - ))} - - - ) : !activeConnection ? ( - - ) : (links.data ?? []).length === 0 ? ( - setPickerOpen(true) }} - /> - ) : ( - - - Linked repositories - - Branch → environment mappings resolve which environment an event belongs to. - - - -
    - {(links.data ?? []).map((link) => ( -
  • -
    -
    - - {link.repoFullName} -
    -
    - {Object.entries(link.branchEnvMap).length === 0 ? ( - No branch mappings - ) : ( - Object.entries(link.branchEnvMap).map(([branch, envSlug]) => ( - - {branch} → {envSlug} - - )) - )} -
    -
    - -
  • - ))} -
-
-
- )} - - {activeConnection && project ? ( - l.repoExternalId))} - onPick={linkRepo} - /> - ) : null} - - { - if (!open) setUnlinkTarget(null); - }} - title="Unlink repository?" - description="Project-scoped events for this repository stop immediately. The repository itself is untouched on GitHub." - resourceName={unlinkTarget?.repoFullName} - confirmLabel="Unlink" - onConfirm={async () => { - if (unlinkTarget) await unlink(unlinkTarget); - }} - /> -
- ); -} - -function RepoPickerDialog({ - open, - onOpenChange, - orgId, - connection, - linkedExternalIds, - onPick, -}: { - open: boolean; - onOpenChange: (open: boolean) => void; - orgId: string; - connection: PublicConnection; - linkedExternalIds: Set; - onPick: (repo: PublicRepository) => Promise; -}) { - const { client } = useSession(); - const [query, setQuery] = React.useState(""); - const [repos, setRepos] = React.useState(null); - const [error, setError] = React.useState(null); - const [busy, setBusy] = React.useState(null); - - React.useEffect(() => { - if (!open) return; - let cancelled = false; - const t = setTimeout(() => { - void (async () => { - const r = await wrap(() => - client.integrations.listRepositories(orgId, connection.id, query || undefined), - ); - if (cancelled) return; - if (!r.ok) { - setError(r.error); - setRepos([]); - return; - } - setError(null); - setRepos(r.data.repositories); - })(); - }, 250); - return () => { - cancelled = true; - clearTimeout(t); - }; - }, [open, query, orgId, connection.id, client]); - - return ( - - - - Link a repository - - Repositories visible to the {connection.externalAccountLogin ?? "GitHub"} installation. - - -
- - setQuery(e.target.value)} - placeholder="Search repositories…" - className="pl-8" - autoFocus - /> -
- {error ? ( -
{error.message}
- ) : repos === null ? ( -
- {Array.from({ length: 4 }).map((_, i) => ( - - ))} -
- ) : repos.length === 0 ? ( -
- No repositories match. -
- ) : ( -
    - {repos.map((repo) => { - const linked = linkedExternalIds.has(repo.externalId); - return ( -
  • -
    -
    {repo.fullName}
    -
    - {repo.private ? "Private" : "Public"} - {repo.defaultBranch ? ` · default ${repo.defaultBranch}` : ""} -
    -
    - -
  • - ); - })} -
- )} -

- Don't see a repository? Adjust the installation's repository access on GitHub. -

-
-
- ); -} diff --git a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/projects/[projectSlug]/page.tsx b/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/projects/[projectSlug]/page.tsx deleted file mode 100644 index fce69c6..0000000 --- a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/projects/[projectSlug]/page.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { redirect } from "next/navigation"; - -export default function ProjectRoot({ - params, -}: { - params: { orgSlug: string; projectSlug: string }; -}) { - redirect(`/orgs/${params.orgSlug}/projects/${params.projectSlug}/environments`); -} diff --git a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/projects/page.tsx b/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/projects/page.tsx deleted file mode 100644 index 16c032d..0000000 --- a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/projects/page.tsx +++ /dev/null @@ -1,196 +0,0 @@ -"use client"; - -import * as React from "react"; -import Link from "next/link"; -import { useParams } from "next/navigation"; -import { z } from "zod"; -import { Plus, FolderKanban } from "lucide-react"; -import { OrgScope } from "@/components/shell/org-scope"; -import { Button } from "@/components/ui/button"; -import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; -import { Skeleton } from "@/components/ui/skeleton"; -import { Badge } from "@/components/ui/badge"; -import { EmptyState } from "@/components/ui/empty-state"; -import { - Dialog, - DialogContent, - DialogDescription, - DialogHeader, - DialogTitle, - DialogTrigger, -} from "@/components/ui/dialog"; -import { ZodForm } from "@/components/ui/zod-form"; -import { PreconditionInsight } from "@/components/precondition/insight"; -import { ArchiveMenu } from "@/components/settings/archive-menu"; -import { removeById } from "@/components/settings/archive"; -import { useQueryClient } from "@tanstack/react-query"; -import { useSession } from "@/lib/session"; -import { useApiQuery, qk, usePrefetch } from "@/lib/query"; -import { useToast } from "@/components/ui/toast"; -import { wrap, type ApiErrorBody } from "@/lib/api"; -import type { PublicProject } from "@saas/contracts/projects"; - -const schema = z.object({ - name: z.string().min(2).max(64), - slug: z.string().regex(/^[a-z0-9-]*$/, "lowercase, digits, hyphens").max(48).optional(), -}); - -export default function ProjectsPage() { - const params = useParams<{ orgSlug: string }>(); - const slug = params?.orgSlug ?? ""; - return {(org) => }; -} - -function Inner({ orgId, orgSlug }: { orgId: string; orgSlug: string }) { - const { client } = useSession(); - const { toast } = useToast(); - const qc = useQueryClient(); - const prefetch = usePrefetch(); - const key = qk.projects(orgId); - const projects = useApiQuery(key, () => - wrap(async () => (await client.projects.list(orgId)).projects), - ); - const [open, setOpen] = React.useState(false); - const [precondition, setPrecondition] = React.useState(null); - - // The query cache is the source of truth; archive mutates it optimistically. - const items = projects.data ?? []; - - const archive = async (project: PublicProject) => { - const previous = qc.getQueryData(key); - qc.setQueryData(key, (cur) => removeById(cur ?? [], project.id)); // optimistic - const r = await wrap(() => client.projects.archive(orgId, project.id)); - if (!r.ok) { - qc.setQueryData(key, previous); // rollback - toast({ kind: "error", title: "Archive failed", description: r.error.message }); - return; - } - toast({ kind: "success", title: `Archived ${project.name}` }); - }; - - return ( -
-
-
-

Projects

-

Project containers for environments and configuration.

-
- - - - - - - Create project - - A project groups your environments and configuration. - - - setOpen(false) }} - onSubmit={async (v) => { - const payload: { name: string; slug?: string } = { name: v.name }; - if (v.slug) payload.slug = v.slug; - const r = await wrap(async () => - (await client.projects.create(orgId, payload)).project, - ); - if (!r.ok) { - if (r.error.code === "precondition_failed") setPrecondition(r.error); - else toast({ kind: "error", title: "Create failed", description: r.error.message }); - return; - } - toast({ kind: "success", title: "Project created" }); - setOpen(false); - projects.reload(); - }} - /> - - -
- - {precondition && ( - setPrecondition(null)} - /> - )} - - {projects.loading ? ( -
- {Array.from({ length: 3 }).map((_, i) => ( - - - - - - - ))} -
- ) : projects.error ? ( - - - {projects.error.code} - {projects.error.message} - - - ) : items.length === 0 ? ( - setOpen(true) }} - /> - ) : ( -
- {items.map((p) => ( -
-
- archive(p)} - /> -
- - prefetch(qk.environments(orgId, p.id), () => - wrap(async () => (await client.environments.list(orgId, p.id)).environments), - ) - } - > - - -
- {p.name} - {p.status} -
- {p.slug} -
- -
- Updated {new Date(p.updatedAt).toLocaleDateString()} -
-
-
- -
- ))} -
- )} -
- ); -} diff --git a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/settings/api-keys/page.tsx b/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/settings/api-keys/page.tsx deleted file mode 100644 index eb78e9f..0000000 --- a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/settings/api-keys/page.tsx +++ /dev/null @@ -1,255 +0,0 @@ -"use client"; - -import * as React from "react"; -import { useParams } from "next/navigation"; -import { z } from "zod"; -import { Plus, KeyRound, Copy, Check } from "lucide-react"; -import { OrgScope } from "@/components/shell/org-scope"; -import { Button } from "@/components/ui/button"; -import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; -import { Skeleton } from "@/components/ui/skeleton"; -import { Badge } from "@/components/ui/badge"; -import { EmptyState } from "@/components/ui/empty-state"; -import { ConfirmDialog } from "@/components/ui/confirm-dialog"; -import { - Dialog, - DialogContent, - DialogDescription, - DialogFooter, - DialogHeader, - DialogTitle, - DialogTrigger, -} from "@/components/ui/dialog"; -import { ZodForm } from "@/components/ui/zod-form"; -import { Table, TableHeader, TableRow, TableHead, TableBody, TableCell } from "@/components/ui/table"; -import { PreconditionInsight } from "@/components/precondition/insight"; -import { useSession } from "@/lib/session"; -import { useApiQuery, qk } from "@/lib/query"; -import { useToast } from "@/components/ui/toast"; -import { wrap, type ApiErrorBody } from "@/lib/api"; -import { ORGANIZATION_ROLES } from "@saas/contracts/membership"; - -const schema = z.object({ - label: z.string().min(2).max(64), - role: z.enum(ORGANIZATION_ROLES), -}); - -export default function ApiKeysPage() { - const params = useParams<{ orgSlug: string }>(); - const slug = params?.orgSlug ?? ""; - return {(org) => }; -} - -function Inner({ orgId }: { orgId: string }) { - const { client } = useSession(); - const { toast } = useToast(); - const keys = useApiQuery(qk.apiKeys(orgId), () => - wrap(async () => (await client.apiKeys.list(orgId)).apiKeys), - ); - const [open, setOpen] = React.useState(false); - const [reveal, setReveal] = React.useState<{ label: string; secret: string } | null>(null); - const [precondition, setPrecondition] = React.useState(null); - const [copied, setCopied] = React.useState(false); - - const [pendingRevoke, setPendingRevoke] = React.useState<{ id: string; label: string } | null>( - null, - ); - - const revokeKey = async (id: string) => { - const r = await wrap(() => client.apiKeys.revoke(orgId, id)); - if (!r.ok) { - toast({ kind: "error", title: "Revoke failed", description: r.error.message }); - return; - } - toast({ kind: "success", title: "Key revoked" }); - keys.reload(); - }; - - return ( -
- !open && setPendingRevoke(null)} - title="Revoke API key" - description="Requests authenticated with this key start failing immediately. This cannot be undone." - resourceName={pendingRevoke?.label} - confirmLabel="Revoke key" - onConfirm={() => (pendingRevoke ? revokeKey(pendingRevoke.id) : undefined)} - /> -
-
-

API keys

-

- Long-lived credentials for service principals. Secrets are shown once at creation. -

-
- - - - - - - Create API key - The secret will only be shown once. Store it securely. - - setOpen(false) }} - onSubmit={async (v) => { - const r = await wrap(async () => - (await client.apiKeys.create(orgId, { label: v.label, role: v.role })).apiKey, - ); - if (!r.ok) { - if (r.error.code === "precondition_failed") setPrecondition(r.error); - else toast({ kind: "error", title: "Create failed", description: r.error.message }); - return; - } - setOpen(false); - setReveal({ label: r.data.label, secret: r.data.secret }); - keys.reload(); - }} - /> - - -
- - {precondition && ( - setPrecondition(null)} /> - )} - - !o && setReveal(null)}> - - - API key created - - This is the only time you’ll see the secret for{" "} - {reveal?.label}. Copy it now. - - -
- {reveal?.secret} -
- - - - -
-
- - {keys.loading ? ( - - - {Array.from({ length: 3 }).map((_, i) => ( - - ))} - - - ) : keys.error ? ( - - - {keys.error.code} - {keys.error.message} - - - ) : !keys.data || keys.data.length === 0 ? ( - setOpen(true) }} - /> - ) : ( - <> - {/* Mobile: stacked cards */} -
- {keys.data.map((k) => ( - -
-
-
{k.label}
-
{k.prefix}…
-
- {k.revokedAt ? ( - revoked - ) : ( - - )} -
-
- {k.servicePrincipal.role} - created {new Date(k.createdAt).toLocaleDateString()} - - last used {k.lastUsedAt ? new Date(k.lastUsedAt).toLocaleDateString() : "never"} - -
-
- ))} -
- - {/* Desktop: table */} - - - - - Label - Prefix - Role - Created - Last used - Actions - - - - {keys.data.map((k) => ( - - {k.label} - {k.prefix}… - - {k.servicePrincipal.role} - - - {new Date(k.createdAt).toLocaleDateString()} - - - {k.lastUsedAt ? new Date(k.lastUsedAt).toLocaleDateString() : "never"} - - - {!k.revokedAt && ( - - )} - {k.revokedAt && revoked} - - - ))} - -
-
- - )} -
- ); -} diff --git a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/settings/audit/page.tsx b/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/settings/audit/page.tsx deleted file mode 100644 index d68f0fb..0000000 --- a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/settings/audit/page.tsx +++ /dev/null @@ -1,617 +0,0 @@ -"use client"; - -import * as React from "react"; -import { useParams } from "next/navigation"; -import { - Bell, - Building2, - ChevronDown, - Download, - FolderKanban, - Gauge, - KeyRound, - Receipt, - RefreshCw, - ScrollText, - ShieldCheck, - SlidersHorizontal, - Users, - Webhook, - X, - type LucideIcon, -} from "lucide-react"; -import type { PublicAuditEntry } from "@saas/contracts/events"; -import { OrgScope } from "@/components/shell/org-scope"; -import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; -import { Skeleton } from "@/components/ui/skeleton"; -import { Badge } from "@/components/ui/badge"; -import { Button } from "@/components/ui/button"; -import { EmptyState } from "@/components/ui/empty-state"; -import { Input } from "@/components/ui/input"; -import { CopyButton } from "@/components/ui/copy-button"; -import { - Select, - SelectContent, - SelectItem, - SelectTrigger, - SelectValue, -} from "@/components/ui/select"; -import { cn } from "@/lib/cn"; -import { wrap } from "@/lib/api"; -import { useSession } from "@/lib/session"; -import { - appendAuditPage, - AUDIT_ACTOR_TYPE_OPTIONS, - AUDIT_CATEGORY_OPTIONS, - AUDIT_TIME_PRESETS, - buildAuditFilterChips, - buildAuditQuery, - categoryAccent, - EMPTY_AUDIT_LOG, - formatRelativeTime, - groupAuditEntriesByDay, - hasActiveAuditFilters, - hasMoreAudit, - presetFromIso, - type AuditFilterFormValues, - type AuditLogState, - type AuditTimePreset, - type CategoryAccent, -} from "@/components/audit/audit-log"; - -const ACCENT_ICONS: Record = { - KeyRound, - ShieldCheck, - Building2, - Users, - FolderKanban, - SlidersHorizontal, - Receipt, - Gauge, - Webhook, - Bell, - ScrollText, -}; - -const TONE_CLASSES: Record = { - violet: "bg-violet-500/10 text-violet-500", - blue: "bg-sky-500/10 text-sky-500", - green: "bg-emerald-500/10 text-emerald-500", - amber: "bg-amber-500/10 text-amber-500", - rose: "bg-rose-500/10 text-rose-500", - slate: "bg-muted text-muted-foreground", -}; - -/** Debounce a fast-changing text value before it drives refetches. */ -function useDebounced(value: T, delayMs = 400): T { - const [debounced, setDebounced] = React.useState(value); - React.useEffect(() => { - const t = setTimeout(() => setDebounced(value), delayMs); - return () => clearTimeout(t); - }, [value, delayMs]); - return debounced; -} - -/** datetime-local value → ISO Z (empty/invalid → empty string). */ -function localToIso(value: string): string { - if (!value) return ""; - const d = new Date(value); - return Number.isNaN(d.getTime()) ? "" : d.toISOString(); -} - -export default function AuditPage() { - const params = useParams<{ orgSlug: string }>(); - const slug = params?.orgSlug ?? ""; - return {(org) => }; -} - -function Inner({ orgId }: { orgId: string }) { - const { client } = useSession(); - - // Toolbar filter state. Selects apply instantly; text inputs are debounced. - const [category, setCategory] = React.useState("all"); - const [actorType, setActorType] = React.useState("all"); - const [preset, setPreset] = React.useState("any"); - const [customFrom, setCustomFrom] = React.useState(""); - const [customTo, setCustomTo] = React.useState(""); - const [eventTypeInput, setEventTypeInput] = React.useState(""); - const [advancedOpen, setAdvancedOpen] = React.useState(false); - const [actorIdInput, setActorIdInput] = React.useState(""); - const [subjectKindInput, setSubjectKindInput] = React.useState(""); - const [subjectIdInput, setSubjectIdInput] = React.useState(""); - // Bumped by Refresh; re-anchors relative presets ("last hour") to now. - const [refreshNonce, setRefreshNonce] = React.useState(0); - - const eventType = useDebounced(eventTypeInput); - const actorId = useDebounced(actorIdInput); - const subjectKind = useDebounced(subjectKindInput); - const subjectId = useDebounced(subjectIdInput); - - const applied: AuditFilterFormValues = React.useMemo( - () => ({ - category: category === "all" ? "" : category, - actorType: actorType === "all" ? "" : actorType, - eventType: eventType.trim(), - actorId: actorId.trim(), - subjectKind: subjectKind.trim(), - subjectId: subjectId.trim(), - from: preset === "custom" ? localToIso(customFrom) : (presetFromIso(preset) ?? ""), - to: preset === "custom" ? localToIso(customTo) : "", - }), - // refreshNonce intentionally re-derives `from` for relative presets. - [category, actorType, eventType, actorId, subjectKind, subjectId, preset, customFrom, customTo, refreshNonce], - ); - const appliedKey = JSON.stringify(applied); - - const [log, setLog] = React.useState(EMPTY_AUDIT_LOG); - const [loading, setLoading] = React.useState(true); - const [loadingMore, setLoadingMore] = React.useState(false); - const [error, setError] = React.useState<{ code: string; message: string } | null>(null); - const [exporting, setExporting] = React.useState(false); - const [expandedId, setExpandedId] = React.useState(null); - - const loadFirstPage = React.useCallback(async () => { - setLoading(true); - setError(null); - const res = await wrap(() => client.events.listAuditEntriesPage(orgId, buildAuditQuery(applied))); - if (res.ok) { - setLog(appendAuditPage(EMPTY_AUDIT_LOG, res.data, /* reset */ true)); - } else { - setError({ code: res.error.code, message: res.error.message }); - setLog(EMPTY_AUDIT_LOG); - } - setLoading(false); - }, [client, orgId, appliedKey]); - - React.useEffect(() => { - void loadFirstPage(); - }, [loadFirstPage]); - - const loadMore = React.useCallback(async () => { - if (log.cursor === null || loadingMore) return; - setLoadingMore(true); - const res = await wrap(() => - client.events.listAuditEntriesPage(orgId, buildAuditQuery(applied, log.cursor ?? undefined)), - ); - if (res.ok) setLog((prev) => appendAuditPage(prev, res.data)); - else setError({ code: res.error.code, message: res.error.message }); - setLoadingMore(false); - }, [client, orgId, appliedKey, log.cursor, loadingMore]); - - // Auto-load the next page when the sentinel scrolls into view; the button - // stays as the keyboard/AT-reachable fallback. - const sentinelRef = React.useRef(null); - React.useEffect(() => { - const node = sentinelRef.current; - if (!node || log.cursor === null) return; - const io = new IntersectionObserver( - (io_entries) => { - if (io_entries.some((x) => x.isIntersecting)) void loadMore(); - }, - { rootMargin: "240px" }, - ); - io.observe(node); - return () => io.disconnect(); - }, [loadMore, log.cursor]); - - const exportNdjson = React.useCallback(async () => { - setExporting(true); - setError(null); - try { - const lines: string[] = []; - for await (const line of client.events.exportAuditEntriesNdjson(orgId, buildAuditQuery(applied))) { - lines.push(line); - } - const blob = new Blob(lines.length > 0 ? lines : [""], { type: "application/x-ndjson" }); - const url = URL.createObjectURL(blob); - const a = document.createElement("a"); - a.href = url; - a.download = `audit-${orgId}-${Date.now()}.ndjson`; - document.body.appendChild(a); - a.click(); - a.remove(); - URL.revokeObjectURL(url); - } catch (e) { - setError({ code: "export_failed", message: e instanceof Error ? e.message : "export failed" }); - } finally { - setExporting(false); - } - }, [client, orgId, appliedKey]); - - const chips = buildAuditFilterChips(applied); - const filtersActive = hasActiveAuditFilters(applied); - - const clearChip = (key: keyof AuditFilterFormValues) => { - switch (key) { - case "category": - setCategory("all"); - break; - case "actorType": - setActorType("all"); - break; - case "eventType": - setEventTypeInput(""); - break; - case "actorId": - setActorIdInput(""); - break; - case "subjectKind": - setSubjectKindInput(""); - break; - case "subjectId": - setSubjectIdInput(""); - break; - case "from": - case "to": - setPreset("any"); - setCustomFrom(""); - setCustomTo(""); - break; - } - }; - - const clearAll = () => { - setCategory("all"); - setActorType("all"); - setPreset("any"); - setCustomFrom(""); - setCustomTo(""); - setEventTypeInput(""); - setActorIdInput(""); - setSubjectKindInput(""); - setSubjectIdInput(""); - }; - - const groups = groupAuditEntriesByDay(log.entries); - - return ( -
-
-
-

Audit log

-

- Immutable record of everything that happened in this organization. -

-
-
- - -
-
- - {/* Filter toolbar — selects apply instantly, text inputs debounce. */} -
-
- - - - - - - setEventTypeInput(e.target.value)} - placeholder="Filter by event type (member.role_changed)" - aria-label="Event type" - className="h-8 w-[260px] text-xs" - /> - - -
- - {preset === "custom" ? ( -
- setCustomFrom(e.target.value)} - aria-label="From" - className="h-8 w-[210px] text-xs" - /> - to - setCustomTo(e.target.value)} - aria-label="To" - className="h-8 w-[210px] text-xs" - /> -
- ) : null} - - {advancedOpen ? ( -
- setActorIdInput(e.target.value)} - placeholder="Actor ID (usr_… / svc_…)" - aria-label="Actor ID" - className="h-8 w-[220px] text-xs" - /> - setSubjectKindInput(e.target.value)} - placeholder="Subject kind (project, member…)" - aria-label="Subject kind" - className="h-8 w-[220px] text-xs" - /> - setSubjectIdInput(e.target.value)} - placeholder="Subject ID (prj_… / mem_…)" - aria-label="Subject ID" - className="h-8 w-[220px] text-xs" - /> -
- ) : null} - - {chips.length > 0 ? ( -
- {chips.map((chip) => ( - - ))} - -
- ) : null} -
- - {loading ? ( - - - {Array.from({ length: 6 }).map((_, i) => ( - - ))} - - - ) : error ? ( - - - {error.code} - {error.message} - - - ) : log.entries.length === 0 ? ( - - ) : ( -
- {groups.map((group) => ( -
-

- {group.label} -

- - {group.entries.map((e) => ( - setExpandedId((cur) => (cur === e.id ? null : e.id))} - onFilterEventType={() => setEventTypeInput(e.eventType)} - onFilterActor={() => { - setAdvancedOpen(true); - setActorIdInput(e.actorId); - }} - /> - ))} - -
- ))} - - {hasMoreAudit(log) ? ( -
- -
- ) : ( -

End of audit history for these filters.

- )} -
- )} -
- ); -} - -function AuditRow({ - entry, - expanded, - onToggle, - onFilterEventType, - onFilterActor, -}: { - entry: PublicAuditEntry; - expanded: boolean; - onToggle: () => void; - onFilterEventType: () => void; - onFilterActor: () => void; -}) { - const accent = categoryAccent(entry.category); - const Icon = ACCENT_ICONS[accent.icon] ?? ScrollText; - const absolute = new Date(entry.occurredAt).toLocaleString(); - - return ( -
- - - {expanded ? ( -
-
- - - - - - {entry.correlationId ? ( - - ) : null} -
- - {Object.keys(entry.payload).length > 0 ? ( -
-
- Payload - -
-
-                {JSON.stringify(entry.payload, null, 2)}
-              
-
- ) : null} - -
- - -
-
- ) : null} -
- ); -} - -function DetailPair({ - label, - value, - mono = false, - copyValue, -}: { - label: string; - value: string; - mono?: boolean; - copyValue?: string; -}) { - return ( -
-
{label}
-
- {value} -
- {copyValue ? : null} -
- ); -} diff --git a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/settings/billing/change-plan/page.tsx b/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/settings/billing/change-plan/page.tsx deleted file mode 100644 index 075321d..0000000 --- a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/settings/billing/change-plan/page.tsx +++ /dev/null @@ -1,34 +0,0 @@ -"use client"; - -import * as React from "react"; -import Link from "next/link"; -import { useParams } from "next/navigation"; -import { ArrowLeft } from "lucide-react"; -import { OrgScope } from "@/components/shell/org-scope"; -import { ChangePlanCards } from "@/components/billing/change-plan-cards"; - -export default function ChangePlanPage() { - const params = useParams<{ orgSlug: string }>(); - const slug = params?.orgSlug ?? ""; - return ( - - {(org) => ( -
-
- - Back to Billing - -

Change plan

-

- Pick a new plan for this organization. You can change again at any time. -

-
- -
- )} -
- ); -} diff --git a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/settings/billing/page.tsx b/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/settings/billing/page.tsx deleted file mode 100644 index a2e725c..0000000 --- a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/settings/billing/page.tsx +++ /dev/null @@ -1,281 +0,0 @@ -"use client"; - -import * as React from "react"; -import { useParams } from "next/navigation"; -import { Receipt, ExternalLink } from "lucide-react"; -import { OrgScope } from "@/components/shell/org-scope"; -import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; -import { Badge } from "@/components/ui/badge"; -import { Skeleton } from "@/components/ui/skeleton"; -import { EmptyState } from "@/components/ui/empty-state"; -import { Table, TableHeader, TableRow, TableHead, TableBody, TableCell } from "@/components/ui/table"; -import { PreconditionInsight } from "@/components/precondition/insight"; -import { BillingActions } from "@/components/billing/billing-actions"; -import { wrap } from "@/lib/api"; -import { useSession } from "@/lib/session"; -import { useApiQuery, qk } from "@/lib/query"; - -export default function BillingPage() { - const params = useParams<{ orgSlug: string }>(); - const slug = params?.orgSlug ?? ""; - return {(org) => }; -} - -function Inner({ orgId }: { orgId: string }) { - const { client } = useSession(); - const summary = useApiQuery(qk.billingSummary(orgId), () => wrap(() => client.billing.getSummary(orgId))); - const ents = useApiQuery(qk.entitlements(orgId), () => wrap(() => client.billing.getEntitlements(orgId))); - const inv = useApiQuery(qk.invoices(orgId), () => wrap(() => client.billing.listInvoices(orgId))); - - return ( -
-
-

Billing

-

Plan, entitlements, and invoices for this organization.

-
- - {/* Plan / customer */} - {summary.loading ? ( - - - - - - ) : summary.error ? ( - summary.error.code === "precondition_failed" ? ( - - ) : ( - - - {summary.error.code} - {summary.error.message} - - - ) - ) : summary.data ? ( - (() => { - const plan = summary.data.plan; - const sub = summary.data.activeSubscription; - const paidActive = - !!sub && (sub.status === "active" || sub.status === "trialing") && (plan?.priceAmountCents ?? 0) > 0; - const nextCharge = - paidActive && plan && sub?.currentPeriodEnd - ? `${formatMoney(plan.priceAmountCents, plan.priceCurrency)} on ${formatDate(sub.currentPeriodEnd)}` - : null; - return ( - - -
-
- {plan ? plan.name : "No active plan"} - {plan ? planPriceLabel(plan) : "No active subscription"} -
- {sub ? {sub.status} : null} -
-
- -
- - - - -
- {nextCharge ? ( -

- Estimated — applicable taxes are calculated at billing. -

- ) : null} -
-
- ); - })() - ) : null} - - {/* Manage plan: upgrade checkout + customer portal */} - {summary.loading ? ( - - - - - - ) : summary.data ? ( - - ) : null} - - {/* Entitlements */} -
-

- Entitlements -

- {ents.loading ? ( - - ) : ents.error ? ( - ents.error.code === "precondition_failed" ? ( - - ) : ( - - - {ents.error.code} - {ents.error.message} - - - ) - ) : !ents.data || ents.data.entitlements.length === 0 ? ( - - ) : ( - - - - - Key - Type - Enabled - Limit - Source - - - - {ents.data.entitlements.map((e) => ( - - {e.entitlementKey} - - {e.valueType} - - - - {e.enabled ? "yes" : "no"} - - - {e.limitValue === null ? "unlimited" : e.limitValue} - - {e.source} - - - ))} - -
-
- )} -
- - {/* Invoices */} -
-

Invoices

- {inv.loading ? ( - - ) : inv.error ? ( - - - {inv.error.code} - {inv.error.message} - - - ) : !inv.data || inv.data.invoices.length === 0 ? ( - - ) : ( - - - - - Number - Status - Due - Paid - Issued - Receipt - - - - {inv.data.invoices.map((i) => ( - - {i.number ?? i.id.slice(0, 12)} - - - {i.status} - - - {formatMoney(i.amountDueCents, i.currency)} - {formatMoney(i.amountPaidCents, i.currency)} - {formatDate(i.issuedAt)} - - {i.hostedUrl ? ( - - View - - ) : ( - — - )} - - - ))} - -
-
- )} -
-
- ); -} - -function Stat({ label, value }: { label: string; value: string }) { - return ( -
-
{label}
-
{value}
-
- ); -} - -/** Locale date, or an em dash when absent. */ -function formatDate(iso: string | null): string { - if (!iso) return "—"; - const d = new Date(iso); - return Number.isNaN(d.getTime()) - ? "—" - : d.toLocaleDateString(undefined, { year: "numeric", month: "short", day: "numeric" }); -} - -/** Money from minor units, e.g. (2000, "usd") → "$20.00". */ -function formatMoney(cents: number | null, currency: string): string { - if (cents == null) return "—"; - const symbol = currency.toLowerCase() === "usd" ? "$" : `${currency.toUpperCase()} `; - return `${symbol}${(cents / 100).toFixed(2)}`; -} - -/** Plan price with interval, e.g. "$20.00 / month". Free/contact tiers read plainly. */ -function planPriceLabel(plan: { priceAmountCents: number | null; priceCurrency: string; billingInterval: string }): string { - if (plan.billingInterval === "none") return "Custom — contact sales"; - if (!plan.priceAmountCents) return "Free"; - const per = plan.billingInterval === "year" ? "year" : "month"; - return `${formatMoney(plan.priceAmountCents, plan.priceCurrency)} / ${per}`; -} - -/** Badge variant for a subscription status. */ -function statusVariant(status: string): "success" | "warning" | "secondary" | "destructive" { - if (status === "active" || status === "trialing") return "success"; - if (status === "past_due") return "warning"; - if (status === "canceled" || status === "expired") return "destructive"; - return "secondary"; -} diff --git a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/settings/config/page.tsx b/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/settings/config/page.tsx deleted file mode 100644 index 63926bd..0000000 --- a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/settings/config/page.tsx +++ /dev/null @@ -1,59 +0,0 @@ -"use client"; - -import * as React from "react"; -import { useParams } from "next/navigation"; -import { Settings } from "lucide-react"; -import { OrgScope } from "@/components/shell/org-scope"; -import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; -import { Badge } from "@/components/ui/badge"; -import { ConfigSurface } from "@/components/config/config-surface"; - -export default function ConfigPage() { - const params = useParams<{ orgSlug: string }>(); - const slug = params?.orgSlug ?? ""; - return ( - - {(org) => ( -
-
-
- -

Configuration

-
-

- Organization-scoped settings, feature flags, and secrets. Project and environment - scopes live on their own pages. -

-
- - - - - - Organization identifiers - Stable references for use in API and SDK calls. - - -
-
-
Name
-
{org.name}
-
-
-
Slug
-
- {org.slug} -
-
-
-
Org ID
-
{org.id}
-
-
-
-
-
- )} -
- ); -} diff --git a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/settings/integrations/page.tsx b/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/settings/integrations/page.tsx deleted file mode 100644 index c2ba940..0000000 --- a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/settings/integrations/page.tsx +++ /dev/null @@ -1,216 +0,0 @@ -"use client"; - -import * as React from "react"; -import { useParams, useRouter } from "next/navigation"; -import { Github, GitBranch, Plug } from "lucide-react"; -import type { PublicConnection } from "@saas/contracts/integrations"; -import { OrgScope } from "@/components/shell/org-scope"; -import { Badge } from "@/components/ui/badge"; -import { Button } from "@/components/ui/button"; -import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; -import { ConfirmDialog } from "@/components/ui/confirm-dialog"; -import { EmptyState } from "@/components/ui/empty-state"; -import { Skeleton } from "@/components/ui/skeleton"; -import { PreconditionInsight } from "@/components/precondition/insight"; -import { useToast } from "@/components/ui/toast"; -import { wrap, type ApiErrorBody } from "@/lib/api"; -import { useSession } from "@/lib/session"; -import { useApiQuery, qk } from "@/lib/query"; -import { - connectionDisplayName, - connectionStatusMeta, - hasPendingConnection, - visibleConnections, -} from "@/components/integrations/connections"; - -const POLL_INTERVAL_MS = 2500; -const POLL_BUDGET_MS = 11 * 60 * 1000; // connect state TTL (10 min) + margin - -export default function IntegrationsPage() { - const params = useParams<{ orgSlug: string }>(); - const slug = params?.orgSlug ?? ""; - return {(org) => }; -} - -function Inner({ orgId, orgSlug }: { orgId: string; orgSlug: string }) { - const { client } = useSession(); - const { toast } = useToast(); - const router = useRouter(); - - const list = useApiQuery(qk.integrations(orgId), () => - wrap(async () => (await client.integrations.list(orgId)).connections), - ); - - const [connecting, setConnecting] = React.useState(false); - const [gateError, setGateError] = React.useState(null); - const [revokeTarget, setRevokeTarget] = React.useState(null); - const pollUntil = React.useRef(0); - - const connections = list.data ?? []; - const visible = visibleConnections(connections); - const hasActive = connections.some((c) => c.status === "active"); - - // While a connect popup is in flight (or a pending row exists), poll the - // list so the row flips to Active without a manual refresh. - const shouldPoll = - (connecting || hasPendingConnection(connections)) && Date.now() < pollUntil.current; - React.useEffect(() => { - if (!shouldPoll) return; - const t = setInterval(() => list.reload(), POLL_INTERVAL_MS); - return () => clearInterval(t); - }, [shouldPoll, list]); - - React.useEffect(() => { - if (connecting && hasActive) { - setConnecting(false); - toast({ kind: "success", title: "GitHub connected" }); - } - }, [connecting, hasActive, toast]); - - const connect = async () => { - setGateError(null); - const r = await wrap(() => client.integrations.connectGithub(orgId)); - if (!r.ok) { - if (r.status === 412) { - setGateError(r.error); - } else { - toast({ kind: "error", title: "Could not start the connection", description: r.error.message }); - } - return; - } - pollUntil.current = Date.now() + POLL_BUDGET_MS; - setConnecting(true); - list.reload(); - const popup = window.open(r.data.installUrl, "github-connect", "width=1020,height=780"); - if (!popup) { - // Popup blocked — same flow, same tab. - window.location.assign(r.data.installUrl); - } - }; - - const revoke = async (connection: PublicConnection) => { - const r = await wrap(() => client.integrations.revoke(orgId, connection.id)); - if (!r.ok) { - toast({ kind: "error", title: "Revoke failed", description: r.error.message }); - return; - } - toast({ kind: "success", title: "Connection revoked" }); - list.reload(); - }; - - return ( -
-
-
- -

Integrations

-
-

- Connect external providers to this organization. Repositories link to projects from each - project's Git settings once a provider is connected. -

-
- - {gateError ? ( - router.push(`/orgs/${orgSlug}/settings/billing`)} - onDismiss={() => setGateError(null)} - /> - ) : null} - - - -
-
- -
-
- GitHub - - Install the GitHub App to react to pushes and pull requests, link repositories to - projects, and act on GitHub without storing credentials. - -
-
- -
- - {list.loading ? ( -
- {Array.from({ length: 2 }).map((_, i) => ( - - ))} -
- ) : list.error ? ( -
-
Failed to load connections
-
{list.error.message}
-
- ) : visible.length === 0 ? ( - void connect() }} - /> - ) : ( -
    - {visible.map((connection) => { - const meta = connectionStatusMeta(connection.status); - return ( -
  • -
    -
    - - {connectionDisplayName(connection)} - - - {meta.label} - -
    -
    - {connection.externalAccountType ?? "GitHub"} - {connection.connectedAt - ? ` · connected ${new Date(connection.connectedAt).toLocaleDateString()}` - : connection.status === "pending" - ? " · waiting for the GitHub install to finish" - : ""} -
    -
    - {connection.status !== "revoked" ? ( - - ) : null} -
  • - ); - })} -
- )} -
-
- - { - if (!open) setRevokeTarget(null); - }} - title="Revoke GitHub connection?" - description="The platform stops receiving events for this installation and any linked repositories stop updating. This also uninstalls the App from GitHub when possible." - resourceName={revokeTarget ? connectionDisplayName(revokeTarget) : undefined} - confirmLabel="Revoke connection" - onConfirm={async () => { - if (revokeTarget) await revoke(revokeTarget); - }} - /> -
- ); -} diff --git a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/settings/invitations/page.tsx b/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/settings/invitations/page.tsx deleted file mode 100644 index 8b1282c..0000000 --- a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/settings/invitations/page.tsx +++ /dev/null @@ -1,196 +0,0 @@ -"use client"; - -import * as React from "react"; -import { useParams } from "next/navigation"; -import { z } from "zod"; -import { Plus, Mail } from "lucide-react"; -import { OrgScope } from "@/components/shell/org-scope"; -import { Button } from "@/components/ui/button"; -import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; -import { Skeleton } from "@/components/ui/skeleton"; -import { Badge } from "@/components/ui/badge"; -import { EmptyState } from "@/components/ui/empty-state"; -import { - Dialog, - DialogContent, - DialogDescription, - DialogHeader, - DialogTitle, - DialogTrigger, -} from "@/components/ui/dialog"; -import { ZodForm } from "@/components/ui/zod-form"; -import { Table, TableHeader, TableRow, TableHead, TableBody, TableCell } from "@/components/ui/table"; -import { PreconditionInsight } from "@/components/precondition/insight"; -import { useSession } from "@/lib/session"; -import { useApiQuery, qk } from "@/lib/query"; -import { useToast } from "@/components/ui/toast"; -import { ORGANIZATION_ROLES } from "@saas/contracts/membership"; -import { wrap, type ApiErrorBody } from "@/lib/api"; - -const schema = z.object({ - email: z.string().email("Enter a valid email"), - role: z.enum(ORGANIZATION_ROLES), -}); - -export default function InvitationsPage() { - const params = useParams<{ orgSlug: string }>(); - const slug = params?.orgSlug ?? ""; - return {(org) => }; -} - -function Inner({ orgId }: { orgId: string }) { - const { client } = useSession(); - const { toast } = useToast(); - const invs = useApiQuery(qk.invitations(orgId), () => - wrap(async () => (await client.memberships.listInvitations(orgId)).invitations), - ); - const [open, setOpen] = React.useState(false); - const [precondition, setPrecondition] = React.useState(null); - - return ( -
-
-
-

Invitations

-

Pending and historical invites for this organization.

-
- - - - - - - Send invitation - - Invite a teammate by email to join this organization. - - - setOpen(false) }} - onSubmit={async (v) => { - const r = await wrap(() => - client.memberships.createInvitation(orgId, { email: v.email, role: v.role }), - ); - if (!r.ok) { - if (r.error.code === "precondition_failed") setPrecondition(r.error); - else toast({ kind: "error", title: "Invite failed", description: r.error.message }); - return; - } - toast({ - kind: "success", - title: "Invitation sent", - description: r.data.delivery?.token ? `dev token: ${r.data.delivery.token}` : undefined, - }); - setOpen(false); - invs.reload(); - }} - /> - - -
- - {precondition && ( - setPrecondition(null)} /> - )} - - {invs.loading ? ( - - - {Array.from({ length: 3 }).map((_, i) => ( - - ))} - - - ) : invs.error ? ( - - - {invs.error.code} - {invs.error.message} - - - ) : !invs.data || invs.data.length === 0 ? ( - setOpen(true) }} - /> - ) : ( - - - - - Email - Role - Status - Created - Expires - Actions - - - - {invs.data.map((i) => ( - - {i.email} - - {i.role} - - - - {i.status} - - - - {new Date(i.createdAt).toLocaleDateString()} - - - {new Date(i.expiresAt).toLocaleDateString()} - - - {i.status === "pending" && ( - - )} - - - ))} - -
-
- )} -
- ); -} diff --git a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/settings/layout.tsx b/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/settings/layout.tsx deleted file mode 100644 index 2977ab5..0000000 --- a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/settings/layout.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import * as React from "react"; -import { SettingsMobileSwitcher } from "@/components/settings/settings-mobile-switcher"; - -/** - * Settings content frame. The settings navigation itself lives in the left - * sidebar (it replaces the product nav while inside `/settings`, à la Vercel), - * so the content area is just a comfortably-wide, centered column that holds the - * stacked settings cards. On mobile, where the sidebar is a drawer, a section - * switcher is shown above the content. - */ -export default function SettingsLayout({ children }: { children: React.ReactNode }) { - return ( -
- - {children} -
- ); -} diff --git a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/settings/members/page.tsx b/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/settings/members/page.tsx deleted file mode 100644 index 85c03eb..0000000 --- a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/settings/members/page.tsx +++ /dev/null @@ -1,167 +0,0 @@ -"use client"; - -import * as React from "react"; -import { useParams } from "next/navigation"; -import { Users } from "lucide-react"; -import { OrgScope } from "@/components/shell/org-scope"; -import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card"; -import { Table, TableHeader, TableRow, TableHead, TableBody, TableCell } from "@/components/ui/table"; -import { Badge } from "@/components/ui/badge"; -import { Button } from "@/components/ui/button"; -import { Skeleton } from "@/components/ui/skeleton"; -import { EmptyState } from "@/components/ui/empty-state"; -import { ConfirmDialog } from "@/components/ui/confirm-dialog"; -import { wrap } from "@/lib/api"; -import { useSession } from "@/lib/session"; -import { useApiQuery, qk } from "@/lib/query"; -import { useToast } from "@/components/ui/toast"; - -export default function MembersPage() { - const params = useParams<{ orgSlug: string }>(); - const slug = params?.orgSlug ?? ""; - return {(org) => }; -} - -function Inner({ orgId }: { orgId: string }) { - const { client } = useSession(); - const { toast } = useToast(); - const members = useApiQuery(qk.members(orgId), () => - wrap(async () => (await client.memberships.listMembers(orgId)).members), - ); - - const [pendingRemove, setPendingRemove] = React.useState<{ id: string; subjectId: string } | null>( - null, - ); - - const removeMember = async (id: string) => { - const r = await wrap(() => client.memberships.removeMember(orgId, id)); - if (!r.ok) { - toast({ kind: "error", title: "Remove failed", description: r.error.message }); - return; - } - toast({ kind: "success", title: "Member removed" }); - members.reload(); - }; - - return ( -
- !open && setPendingRemove(null)} - title="Remove member" - description="They immediately lose access to this organization and all of its projects. You can re-invite them later." - resourceName={pendingRemove?.subjectId} - confirmLabel="Remove member" - onConfirm={() => (pendingRemove ? removeMember(pendingRemove.id) : undefined)} - /> -
-

Members

-

Users and service principals attached to this organization.

-
- - {members.loading ? ( - - - {Array.from({ length: 4 }).map((_, i) => ( - - ))} - - - ) : members.error ? ( - - - {members.error.code} - {members.error.message} - - - ) : !members.data || members.data.length === 0 ? ( - - ) : ( - <> - {/* Mobile: stacked cards */} -
- {members.data.map((m) => ( - -
-
-
{m.subjectId}
-
- {m.subjectType} - {m.status} -
-
- -
- {m.roles.length > 0 && ( -
- {m.roles.map((r, i) => ( - - {r.role} - - ))} -
- )} -
- Joined {new Date(m.joinedAt).toLocaleDateString()} -
-
- ))} -
- - {/* Desktop: table */} - - - - - Subject - Type - Roles - Status - Joined - Actions - - - - {members.data.map((m) => ( - - {m.subjectId} - - {m.subjectType} - - -
- {m.roles.map((r, i) => ( - - {r.role} - - ))} -
-
- - {m.status} - - - {new Date(m.joinedAt).toLocaleDateString()} - - - - -
- ))} -
-
-
- - )} -
- ); -} diff --git a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/settings/notifications/page.tsx b/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/settings/notifications/page.tsx deleted file mode 100644 index 726eb7f..0000000 --- a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/settings/notifications/page.tsx +++ /dev/null @@ -1,121 +0,0 @@ -"use client"; - -import * as React from "react"; -import { useParams } from "next/navigation"; -import { BellRing } from "lucide-react"; -import type { NotificationCategory } from "@saas/contracts/notifications"; -import { OrgScope } from "@/components/shell/org-scope"; -import { Card, CardContent } from "@/components/ui/card"; -import { Skeleton } from "@/components/ui/skeleton"; -import { Switch } from "@/components/ui/switch"; -import { wrap } from "@/lib/api"; -import { useSession } from "@/lib/session"; -import { useApiQuery, qk } from "@/lib/query"; -import { useToast } from "@/components/ui/toast"; -import { - PREFERENCE_CATEGORIES, - effectiveCategories, - buildUpdatedCategories, -} from "@/components/notifications/preferences"; - -export default function NotificationsPage() { - const params = useParams<{ orgSlug: string }>(); - const slug = params?.orgSlug ?? ""; - return {(org) => }; -} - -function Inner({ orgId }: { orgId: string }) { - const { client } = useSession(); - const { toast } = useToast(); - // The edge pins the subject to the session actor; we only scope by org. - const prefs = useApiQuery(qk.notificationPrefs(orgId), () => - wrap(async () => (await client.notifications.getPreferences({ orgId })).preferences), - ); - const profile = useApiQuery(qk.profile(), () => - wrap(async () => (await client.auth.getProfile()).user), - ); - - const stored = effectiveCategories(prefs.data); - // Optimistic per-category overrides while an update is in flight. - const [overrides, setOverrides] = React.useState>>( - {}, - ); - const current = { ...stored, ...overrides }; - - const toggle = async (category: NotificationCategory, enabled: boolean) => { - if (!profile.data) return; - setOverrides((o) => ({ ...o, [category]: enabled })); - const r = await wrap(() => - client.notifications.updatePreferences({ - orgId, - subjectKind: "user", - subjectId: profile.data!.id, - channel: "email", - categories: buildUpdatedCategories(current, category, enabled), - }), - ); - if (!r.ok) { - setOverrides((o) => { - const next = { ...o }; - delete next[category]; - return next; - }); - toast({ kind: "error", title: "Update failed", description: r.error.message }); - return; - } - prefs.reload(); - }; - - return ( -
-
-
- -

Notifications

-
-

- Which categories of email you receive for this organization. Applies to your account - only. -

-
- - {prefs.loading || profile.loading ? ( - - - {Array.from({ length: 5 }).map((_, i) => ( - - ))} - - - ) : prefs.error ? ( - - -
Failed to load preferences
-
{prefs.error.message}
-
-
- ) : ( - - - {PREFERENCE_CATEGORIES.map((c) => ( -
-
-
- {c.label} -
-
{c.description}
-
- void toggle(c.key, on)} - aria-labelledby={`pref-${c.key}`} - disabled={!profile.data} - /> -
- ))} -
-
- )} -
- ); -} diff --git a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/settings/page.tsx b/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/settings/page.tsx deleted file mode 100644 index 0f21708..0000000 --- a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/settings/page.tsx +++ /dev/null @@ -1,74 +0,0 @@ -"use client"; - -import * as React from "react"; -import { useParams } from "next/navigation"; -import { OrgScope } from "@/components/shell/org-scope"; -import { Button } from "@/components/ui/button"; -import { Input } from "@/components/ui/input"; -import { CopyButton } from "@/components/ui/copy-button"; -import { SettingsCard } from "@/components/settings/settings-card"; -import { appConfig } from "@/lib/app-config"; -import { TENANT_NOUN } from "@/lib/solo-mode"; - -export default function OrgSettingsPage() { - const params = useParams<{ orgSlug: string }>(); - const slug = params?.orgSlug ?? ""; - return {(org) => }; -} - -function Inner({ org }: { org: { id: string; name: string; slug: string } }) { - // Solo relabels the tenant noun: in M0 the org reads as the user's "Account". - const noun = TENANT_NOUN; // "Organization" (baseline) | "Account" (solo) - const nounLower = noun.toLowerCase(); - return ( -
- - - - - } - > -
- - /orgs/ - - -
-
- - } - > - - - - - Delete… - - } - /> -
- ); -} diff --git a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/settings/webhooks/[endpointId]/page.tsx b/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/settings/webhooks/[endpointId]/page.tsx deleted file mode 100644 index 1f30f19..0000000 --- a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/settings/webhooks/[endpointId]/page.tsx +++ /dev/null @@ -1,487 +0,0 @@ -"use client"; - -import * as React from "react"; -import Link from "next/link"; -import { useParams, useRouter } from "next/navigation"; -import { - ChevronLeft, - RefreshCcw, - Webhook as WebhookIcon, - Pencil, - ShieldOff, - ShieldCheck, - Trash2, -} from "lucide-react"; -import { OrgScope } from "@/components/shell/org-scope"; -import { Card, CardHeader, CardTitle, CardDescription, CardContent } from "@/components/ui/card"; -import { Skeleton } from "@/components/ui/skeleton"; -import { Badge } from "@/components/ui/badge"; -import { Button } from "@/components/ui/button"; -import { EmptyState } from "@/components/ui/empty-state"; -import { - Table, - TableHeader, - TableBody, - TableRow, - TableHead, - TableCell, -} from "@/components/ui/table"; -import { useSession } from "@/lib/session"; -import { useAsync } from "@/lib/use-async"; -import { useApiQuery, qk } from "@/lib/query"; -import { wrap } from "@/lib/api"; -import { RotateSecretDialog } from "@/components/webhooks/rotate-secret-dialog"; -import { EditEndpointDialog } from "@/components/webhooks/edit-endpoint-dialog"; -import { DisableEndpointDialog } from "@/components/webhooks/disable-endpoint-dialog"; -import { EnableEndpointDialog } from "@/components/webhooks/enable-endpoint-dialog"; -import { DeleteEndpointDialog } from "@/components/webhooks/delete-endpoint-dialog"; -import { - appendDeliveryPage, - hasMoreDeliveries, - toDeliveryRow, - canReplayAttempt, - EMPTY_DELIVERY_HISTORY, - type DeliveryHistoryState, -} from "@/components/webhooks/delivery-history"; -import { useToast } from "@/components/ui/toast"; - -export default function WebhookEndpointDetailPage() { - const params = useParams<{ orgSlug: string; endpointId: string }>(); - const slug = params?.orgSlug ?? ""; - const endpointId = params?.endpointId ?? ""; - return ( - - {(org) => } - - ); -} - -function Inner({ - orgId, - orgSlug, - endpointId, -}: { - orgId: string; - orgSlug: string; - endpointId: string; -}) { - const { client } = useSession(); - const router = useRouter(); - const endpoints = useApiQuery(qk.webhooks(orgId), () => - wrap(async () => (await client.webhooks.listEndpoints(orgId)).endpoints), - ); - const [rotateOpen, setRotateOpen] = React.useState(false); - const [editOpen, setEditOpen] = React.useState(false); - const [disableOpen, setDisableOpen] = React.useState(false); - const [enableOpen, setEnableOpen] = React.useState(false); - const [deleteOpen, setDeleteOpen] = React.useState(false); - - const endpoint = React.useMemo( - () => endpoints.data?.find((e) => e.id === endpointId) ?? null, - [endpoints.data, endpointId], - ); - - if (endpoints.loading) { - return ( -
- - - - - - - -
- ); - } - - if (endpoints.error) { - return ( - - - {endpoints.error.code} - {endpoints.error.message} - - - ); - } - - if (!endpoint) { - return ( - - ); - } - - const label = endpoint.name ?? endpoint.url; - const isDisabled = endpoint.status === "disabled"; - - return ( -
-
- - - Webhooks - -
- -
-
-

- {endpoint.name ?? "Webhook endpoint"} -

-

- {endpoint.url} -

-
-
- - {!isDisabled && ( - - )} - {isDisabled && ( - - )} - - -
-
- - {isDisabled && ( - - - This endpoint is disabled - - No deliveries are being attempted. Use{" "} - Re-enable endpoint above - to resume delivery on the next matching event — the signing - secret is preserved. - - - - )} - - - - Endpoint metadata - - Read-only fields. The signing secret is never displayed here — it is - shown exactly once at rotation time. - - - -
- {endpoint.id}} /> - - {endpoint.status} - - } - /> - - - - org-scoped} - /> - {endpoint.disabledAt && ( - - )} - {endpoint.description && ( - {endpoint.description}} - /> - )} -
-
-
- - - - endpoints.reload()} - /> - endpoints.reload()} - /> - endpoints.reload()} - /> - endpoints.reload()} - /> - router.push(`/orgs/${orgSlug}/settings/webhooks`)} - /> -
- ); -} - -function DeliveryHistoryPanel({ - orgId, - endpointId, -}: { - orgId: string; - endpointId: string; -}) { - const { client } = useSession(); - const { toast } = useToast(); - const [state, setState] = React.useState( - EMPTY_DELIVERY_HISTORY, - ); - const [loadingMore, setLoadingMore] = React.useState(false); - const [replayingId, setReplayingId] = React.useState(null); - - const initial = useAsync( - () => - wrap(async () => { - const page = await client.webhooks.listDeliveryAttemptsPage( - orgId, - endpointId, - ); - setState((prev) => appendDeliveryPage(prev, page, true)); - return page; - }), - [client, orgId, endpointId], - ); - - const reloadFirstPage = React.useCallback(async () => { - const r = await wrap(() => - client.webhooks.listDeliveryAttemptsPage(orgId, endpointId), - ); - if (r.ok) { - setState((prev) => appendDeliveryPage(prev, r.data, true)); - } - }, [client, orgId, endpointId]); - - const replay = React.useCallback( - async (attemptId: string) => { - setReplayingId(attemptId); - const r = await wrap(() => - client.webhooks.replayDelivery(orgId, attemptId), - ); - setReplayingId(null); - if (!r.ok) { - toast({ - kind: "error", - title: "Redeliver failed", - description: r.error.message, - }); - return; - } - toast({ - kind: "success", - title: "Delivery replayed", - description: `New attempt ${r.data.deliveryAttempt.status}.`, - }); - // Re-fetch the first page so the fresh attempt appears at the top. - await reloadFirstPage(); - }, - [client, orgId, toast, reloadFirstPage], - ); - - const loadMore = React.useCallback(async () => { - if (state.cursor === null || loadingMore) return; - const cursor = state.cursor; - setLoadingMore(true); - try { - const result = await wrap(() => - client.webhooks.listDeliveryAttemptsPage(orgId, endpointId, { - cursor, - }), - ); - if (result.ok) { - setState((prev) => appendDeliveryPage(prev, result.data)); - } - } finally { - setLoadingMore(false); - } - }, [client, orgId, endpointId, state.cursor, loadingMore]); - - const rows = React.useMemo( - () => state.attempts.map(toDeliveryRow), - [state.attempts], - ); - - return ( - - - Delivery history - - Recent delivery attempts for this endpoint, newest first. Failure - summaries are safe — no raw response bodies or event payloads are - shown. - - - - {initial.loading ? ( -
- - - -
- ) : initial.error ? ( -
- {initial.error.code}{" "} - {initial.error.message} -
- ) : rows.length === 0 ? ( - - ) : ( -
-
- - - - Event - Status - Attempt - HTTP - Completed - Detail - Actions - - - - {rows.map((row) => ( - - - {row.eventType} - - - {row.badge.label} - - - #{row.attemptNumber} - - {row.httpStatus} - - {row.completedAtLabel} - - - {row.failureReason - ? row.failureReason - : row.nextRetryAtLabel - ? `next retry ${row.nextRetryAtLabel}` - : "—"} - - - {canReplayAttempt(row.status) ? ( - - ) : ( - — - )} - - - ))} - -
-
- {hasMoreDeliveries(state) && ( -
- -
- )} -
- )} -
-
- ); -} - -function Field({ label, value }: { label: string; value: React.ReactNode }) { - return ( -
-
{label}
-
{value}
-
- ); -} diff --git a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/settings/webhooks/page.tsx b/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/settings/webhooks/page.tsx deleted file mode 100644 index f809b46..0000000 --- a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/settings/webhooks/page.tsx +++ /dev/null @@ -1,178 +0,0 @@ -"use client"; - -import * as React from "react"; -import Link from "next/link"; -import { useParams, useRouter } from "next/navigation"; -import { Webhook, ArrowRight, Plus } from "lucide-react"; -import { OrgScope } from "@/components/shell/org-scope"; -import { Button } from "@/components/ui/button"; -import { Card, CardHeader, CardTitle, CardDescription, CardContent } from "@/components/ui/card"; -import { Skeleton } from "@/components/ui/skeleton"; -import { Badge } from "@/components/ui/badge"; -import { EmptyState } from "@/components/ui/empty-state"; -import { Table, TableHeader, TableRow, TableHead, TableBody, TableCell } from "@/components/ui/table"; -import { useSession } from "@/lib/session"; -import { useApiQuery, qk } from "@/lib/query"; -import { wrap } from "@/lib/api"; -import { CreateEndpointDialog } from "@/components/webhooks/create-endpoint-dialog"; - -export default function WebhooksListPage() { - const params = useParams<{ orgSlug: string }>(); - const slug = params?.orgSlug ?? ""; - return ( - - {(org) => } - - ); -} - -function Inner({ orgId, orgSlug }: { orgId: string; orgSlug: string }) { - const { client } = useSession(); - const router = useRouter(); - const endpoints = useApiQuery(qk.webhooks(orgId), () => - wrap(async () => (await client.webhooks.listEndpoints(orgId)).endpoints), - ); - const [createOpen, setCreateOpen] = React.useState(false); - - const handleCreated = React.useCallback( - (endpointId: string) => { - router.push(`/orgs/${orgSlug}/settings/webhooks/${endpointId}`); - }, - [router, orgSlug], - ); - - return ( -
-
-
-

Webhooks

-

- Endpoints that receive signed event deliveries from this organization. - Open an endpoint to inspect its signing-secret version or rotate it. -

-
- -
- - {endpoints.loading ? ( - - - {Array.from({ length: 3 }).map((_, i) => ( - - ))} - - - ) : endpoints.error ? ( - - - {endpoints.error.code} - {endpoints.error.message} - - - ) : !endpoints.data || endpoints.data.length === 0 ? ( - setCreateOpen(true) }} - /> - ) : ( - <> - {/* Mobile: stacked cards */} -
- {endpoints.data.map((ep) => ( - - -
-
- {ep.name &&
{ep.name}
} -
{ep.url}
-
- - {ep.status} - -
-
- secret v{ep.secretVersion} - - rotated{" "} - {ep.secretLastRotatedAt - ? new Date(ep.secretLastRotatedAt).toLocaleDateString() - : "never"} - -
-
- - ))} -
- - {/* Desktop: table */} - - - - - URL - Status - Secret version - Last rotated - Actions - - - - {endpoints.data.map((ep) => ( - - - {ep.name ? ( - - {ep.name} - · - {ep.url} - - ) : ( - ep.url - )} - - - - {ep.status} - - - v{ep.secretVersion} - - {ep.secretLastRotatedAt - ? new Date(ep.secretLastRotatedAt).toLocaleDateString() - : "never"} - - - - Open - - - - - ))} - -
-
- - )} - - -
- ); -} diff --git a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/usage/page.tsx b/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/usage/page.tsx deleted file mode 100644 index ea342df..0000000 --- a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/usage/page.tsx +++ /dev/null @@ -1,387 +0,0 @@ -"use client"; - -import * as React from "react"; -import { useParams } from "next/navigation"; -import { Gauge, AlertTriangle, BarChart3 } from "lucide-react"; -import { OrgScope } from "@/components/shell/org-scope"; -import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; -import { Skeleton } from "@/components/ui/skeleton"; -import { Badge } from "@/components/ui/badge"; -import { Button } from "@/components/ui/button"; -import { Input } from "@/components/ui/input"; -import { Label } from "@/components/ui/label"; -import { EmptyState } from "@/components/ui/empty-state"; -import { - Table, - TableBody, - TableCell, - TableHead, - TableHeader, - TableRow, -} from "@/components/ui/table"; -import { - Select, - SelectContent, - SelectItem, - SelectTrigger, - SelectValue, -} from "@/components/ui/select"; -import { wrap } from "@/lib/api"; -import { useSession } from "@/lib/session"; -import { - DEFAULT_USAGE_FORM, - RANGE_PRESETS, - METRIC_SUGGESTIONS, - buildUsageQuery, - canQueryUsage, - sortRollups, - usageBarPercents, - formatQuantity, - formatBucket, - buildViolationsQuery, - appendViolationsPage, - hasMoreViolations, - isViolationOpen, - formatPeriod, - overagePercent, - EMPTY_VIOLATIONS, - type UsageFormValues, - type BucketType, - type RangePreset, - type ViolationsState, -} from "@/components/usage/usage"; -import type { GetUsageSummaryResponse } from "@saas/contracts/metering"; - -export default function UsagePage() { - const params = useParams<{ orgSlug: string }>(); - const slug = params?.orgSlug ?? ""; - return {(org) => }; -} - -function Inner({ orgId }: { orgId: string }) { - return ( -
-
-

Usage & quota

-

- Metered consumption and quota status for this organization. -

-
- - -
- ); -} - -// --- Usage summary ---------------------------------------------------------- - -function UsageSummary({ orgId }: { orgId: string }) { - const { client } = useSession(); - const [draft, setDraft] = React.useState(DEFAULT_USAGE_FORM); - const [applied, setApplied] = React.useState(null); - const [data, setData] = React.useState(null); - const [loading, setLoading] = React.useState(false); - const [error, setError] = React.useState<{ code: string; message: string } | null>(null); - - React.useEffect(() => { - if (!applied || !canQueryUsage(applied)) return; - let cancelled = false; - setLoading(true); - setError(null); - void wrap(() => client.metering.getUsageSummary(orgId, buildUsageQuery(applied))).then((r) => { - if (cancelled) return; - if (r.ok) setData(r.data); - else setError({ code: r.error.code, message: r.error.message }); - setLoading(false); - }); - return () => { - cancelled = true; - }; - }, [client, orgId, applied]); - - const rollups = data ? sortRollups(data.rollups) : []; - const bars = usageBarPercents(rollups); - - return ( - - - - Consumption - - - Pick a metric and window to summarize recorded usage. Metrics are - product-defined keys (e.g. api_requests). - - - -
{ - e.preventDefault(); - setApplied(draft); - }} - > -
- - setDraft((d) => ({ ...d, metric: e.target.value }))} - /> - - {METRIC_SUGGESTIONS.map((m) => ( - -
-
- - -
-
- - -
-
- -
-
- - {!applied ? ( - - ) : loading ? ( -
- {Array.from({ length: 4 }).map((_, i) => )} -
- ) : error ? ( -
-
{error.code}
-
{error.message}
-
- ) : data && rollups.length > 0 ? ( -
-
- - - -
- - - - Bucket - Quantity - Records - - - - {rollups.map((r, i) => ( - - - {formatBucket(r.bucketStart, r.bucketType)} - - -
-
-
-
- - {formatQuantity(r.quantity)} - -
- - - {r.recordCount} - - - ))} - -
-
- ) : ( - - )} -
-
- ); -} - -function Metric({ label, value }: { label: string; value: string }) { - return ( -
-
{value}
-
{label}
-
- ); -} - -// --- Quota violations ------------------------------------------------------- - -function QuotaViolations({ orgId }: { orgId: string }) { - const { client } = useSession(); - const [metricDraft, setMetricDraft] = React.useState(""); - const [metricFilter, setMetricFilter] = React.useState(""); - const [state, setState] = React.useState(EMPTY_VIOLATIONS); - const [loading, setLoading] = React.useState(true); - const [loadingMore, setLoadingMore] = React.useState(false); - const [error, setError] = React.useState<{ code: string; message: string } | null>(null); - - const loadFirst = React.useCallback(async () => { - setLoading(true); - setError(null); - const r = await wrap(() => - client.metering.listQuotaViolations(orgId, buildViolationsQuery(metricFilter)), - ); - if (r.ok) setState(appendViolationsPage(EMPTY_VIOLATIONS, r.data, true)); - else { - setError({ code: r.error.code, message: r.error.message }); - setState(EMPTY_VIOLATIONS); - } - setLoading(false); - }, [client, orgId, metricFilter]); - - React.useEffect(() => { - void loadFirst(); - }, [loadFirst]); - - const loadMore = React.useCallback(async () => { - if (state.cursor === null) return; - setLoadingMore(true); - const r = await wrap(() => - client.metering.listQuotaViolations(orgId, buildViolationsQuery(metricFilter, state.cursor)), - ); - if (r.ok) setState((prev) => appendViolationsPage(prev, r.data)); - else setError({ code: r.error.code, message: r.error.message }); - setLoadingMore(false); - }, [client, orgId, metricFilter, state.cursor]); - - return ( - - - - Quota violations - - Recorded breaches of a configured quota limit. - - -
{ - e.preventDefault(); - setMetricFilter(metricDraft); - }} - > -
- - setMetricDraft(e.target.value)} - /> -
- - {metricFilter ? ( - - ) : null} -
- - {loading ? ( -
- {Array.from({ length: 3 }).map((_, i) => )} -
- ) : error ? ( -
-
{error.code}
-
{error.message}
-
- ) : state.violations.length === 0 ? ( - - ) : ( -
- {state.violations.map((v) => { - const pct = overagePercent(v); - return ( -
-
-
- {v.metric} - - {isViolationOpen(v) ? "open" : "resolved"} - - {v.enforcement} -
-
- {formatQuantity(v.actualValue)} / {formatQuantity(v.limitValue)} {formatPeriod(v.period)} - {pct !== null ? ` · ${pct}% of limit` : ""} -
-
-
- {new Date(v.violatedAt).toLocaleString()} -
-
- ); - })} - {hasMoreViolations(state) ? ( -
- -
- ) : null} -
- )} -
-
- ); -} diff --git a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/webhooks/[endpointId]/page.tsx b/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/webhooks/[endpointId]/page.tsx deleted file mode 100644 index 470a6e7..0000000 --- a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/webhooks/[endpointId]/page.tsx +++ /dev/null @@ -1,13 +0,0 @@ -import { redirect } from "next/navigation"; - -/** - * Compatibility redirect for deep links to a specific webhook endpoint, which - * now lives under the Settings surface. - */ -export default function LegacyWebhookEndpointRedirect({ - params, -}: { - params: { orgSlug: string; endpointId: string }; -}) { - redirect(`/orgs/${params.orgSlug}/settings/webhooks/${params.endpointId}`); -} diff --git a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/webhooks/page.tsx b/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/webhooks/page.tsx deleted file mode 100644 index 6dedc02..0000000 --- a/apps/web-console-next/src/app/(app)/orgs/[orgSlug]/webhooks/page.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import { redirect } from "next/navigation"; - -/** - * Compatibility redirect. Webhooks moved under the dedicated Settings surface; - * this keeps old links to `/orgs/[slug]/webhooks` working. - */ -export default function LegacyWebhooksRedirect({ params }: { params: { orgSlug: string } }) { - redirect(`/orgs/${params.orgSlug}/settings/webhooks`); -} diff --git a/apps/web-console-next/src/app/(app)/orgs/new/page.tsx b/apps/web-console-next/src/app/(app)/orgs/new/page.tsx deleted file mode 100644 index 91404c0..0000000 --- a/apps/web-console-next/src/app/(app)/orgs/new/page.tsx +++ /dev/null @@ -1,70 +0,0 @@ -"use client"; - -import * as React from "react"; -import { useRouter } from "next/navigation"; -import { Skeleton } from "@/components/ui/skeleton"; -import { Card, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; -import { pickAccountBillingOrg } from "@/components/billing/account-org"; -import { CreateOrgFlow } from "@/components/orgs/create-org-flow"; -import { useSession } from "@/lib/session"; -import { useApiQuery, qk } from "@/lib/query"; -import { wrap } from "@/lib/api"; -import { SOLO_MODE } from "@/lib/solo-mode"; - -/** - * Guided create-organization flow for ADDITIONAL (child) organizations. The - * account's first (parent) organization is always created through the - * full-screen `/onboarding` flow, so an account with zero orgs is forwarded - * there; the page resolves the org list before mounting the flow to decide. - */ -export default function NewOrgPage() { - const router = useRouter(); - const { client } = useSession(); - const orgs = useApiQuery(qk.orgs(), () => - wrap(async () => (await client.organizations.list()).organizations), - ); - - const needsOnboarding = orgs.data?.length === 0; - React.useEffect(() => { - // Solo: the user is the tenant and cannot create a second org — bounce home. - // (The API edge also 404s POST /v1/organizations; this is the UI guard.) - if (SOLO_MODE) { - router.replace("/"); - return; - } - if (needsOnboarding) router.replace("/onboarding"); - }, [needsOnboarding, router]); - - if (SOLO_MODE || orgs.loading || needsOnboarding) { - return ( -
- -
- - -
-
-
- {[0, 1, 2].map((i) => ( - - ))} -
- -
-
- ); - } - - if (orgs.error) { - return ( - - - Failed to load your account - {orgs.error.message} - - - ); - } - - return ; -} diff --git a/apps/web-console-next/src/app/(app)/orgs/page.tsx b/apps/web-console-next/src/app/(app)/orgs/page.tsx deleted file mode 100644 index 55bfd8d..0000000 --- a/apps/web-console-next/src/app/(app)/orgs/page.tsx +++ /dev/null @@ -1,186 +0,0 @@ -"use client"; - -import * as React from "react"; -import Link from "next/link"; -import { useRouter } from "next/navigation"; -import { Building2, Plus } from "lucide-react"; -import { Button } from "@/components/ui/button"; -import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; -import { Badge } from "@/components/ui/badge"; -import { Skeleton } from "@/components/ui/skeleton"; -import { EmptyState } from "@/components/ui/empty-state"; -import { pickAccountBillingOrg } from "@/components/billing/account-org"; -import { useSession } from "@/lib/session"; -import { readLastOrgSlug, clearLastOrgSlug, defaultOrgDestination } from "@/lib/last-org"; -import { SOLO_MODE } from "@/lib/solo-mode"; -import { useApiQuery, qk, usePrefetch } from "@/lib/query"; -import { useToast } from "@/components/ui/toast"; -import { wrap } from "@/lib/api"; - -export default function OrgsPage() { - const { client } = useSession(); - const { toast } = useToast(); - const router = useRouter(); - const prefetch = usePrefetch(); - const orgs = useApiQuery(qk.orgs(), () => - wrap(async () => (await client.organizations.list()).organizations), - ); - - // Solo profile: there is no org chooser — the personal workspace is invisible. - // Auto-resolve it and forward to its dashboard. Off the profile this is inert. - React.useEffect(() => { - if (!SOLO_MODE || !orgs.data || orgs.data.length === 0) return; - const home = pickAccountBillingOrg(orgs.data)!; - router.replace(defaultOrgDestination(home.slug)); - }, [orgs.data, router]); - // Multi-org is gated on the account's billing parent (its earliest-created - // org — same choice the membership-worker MO2 gate makes). The paywall's - // "Upgrade plan" CTA starts a Business checkout for that org. - const billingParent = React.useMemo( - () => pickAccountBillingOrg(orgs.data ?? []), - [orgs.data], - ); - const onUpgrade = React.useCallback(async () => { - if (!billingParent) return; - const r = await wrap(() => client.billing.createCheckout(billingParent.id, { planCode: "business" })); - if (!r.ok) { - toast({ kind: "error", title: "Could not start checkout", description: r.error.message }); - return; - } - window.location.assign(r.data.checkoutUrl); - }, [billingParent, client, toast]); - - // The org list is authoritative: if the remembered org isn't in it anymore, - // forget it so the default landing doesn't point at an inaccessible org. - React.useEffect(() => { - const last = readLastOrgSlug(); - if (orgs.data && last && !orgs.data.some((o) => o.slug === last)) { - clearLastOrgSlug(); - } - }, [orgs.data]); - - // Solo: the org chooser is never shown — the personal workspace is invisible - // and the effect above forwards to it. Render a neutral placeholder (no org - // wording, no "create" CTA) while that resolves, matching /orgs/new. Off the - // profile this is dead and the full chooser below renders unchanged. - if (SOLO_MODE) { - return ( -
- {Array.from({ length: 3 }).map((_, i) => ( - - - - - - - - - - ))} -
- ); - } - - return ( -
-
-
-

Organizations

-

- Tenant root. Pick an org or create a new one. -

-
- -
- - {(orgs.data ?? []).some((o) => o.status === "suspended") && ( - - - Some organizations are suspended - - One or more organizations are frozen because your account plan no longer includes - multiple organizations. Upgrade to restore access to them. - - - - - - - )} - - {orgs.loading ? ( -
- {Array.from({ length: 3 }).map((_, i) => ( - - - - - - - - - - ))} -
- ) : orgs.error ? ( - - - Failed to load organizations - {orgs.error.message} - - - ) : !orgs.data || orgs.data.length === 0 ? ( - // Transient: the shell's OnboardingGate redirects zero-org accounts to - // /onboarding; this renders only for the moment before it fires. - - ) : ( -
- {orgs.data.map((o) => ( - - prefetch(qk.projects(o.id), () => - wrap(async () => (await client.projects.list(o.id)).projects), - ) - } - > - - -
-
- {o.name.charAt(0).toUpperCase()} -
-
- {o.name} - {o.slug} -
-
-
- -
- Created {new Date(o.createdAt).toLocaleDateString()} -
- {o.status === "suspended" ? ( - Suspended - ) : null} -
-
- - ))} -
- )} -
- ); -} diff --git a/apps/web-console-next/src/app/auth/callback/page.tsx b/apps/web-console-next/src/app/auth/callback/page.tsx deleted file mode 100644 index ee982e9..0000000 --- a/apps/web-console-next/src/app/auth/callback/page.tsx +++ /dev/null @@ -1,78 +0,0 @@ -"use client"; - -import * as React from "react"; -import { useRouter } from "next/navigation"; -import { useSession } from "@/lib/session"; -import { resolvePostAuthDestination } from "@/lib/last-org"; -import { createClient } from "@/lib/api"; -import { useToast } from "@/components/ui/toast"; -import { Button } from "@/components/ui/button"; - -// Human-readable copy for the `error` codes the identity-worker callback may -// return in the URL fragment. -const ERROR_COPY: Record = { - access_denied: "Sign-in was cancelled.", - email_required: - "Your provider account has no email. Add an email with the provider, or sign in with an email code.", - email_unverified: - "Your provider email isn't verified. Verify it with the provider, or sign in with an email code.", - exchange_failed: "Could not complete the handshake with the provider. Please try again.", - identity_failed: "Could not read your profile from the provider. Please try again.", - missing_code: "The provider did not return an authorization code. Please try again.", - provider_unavailable: "This sign-in method is temporarily unavailable.", - oauth_failed: "Something went wrong during sign-in. Please try again.", - server_error: "Something went wrong on our side. Please try again.", -}; - -export default function OAuthCallbackPage() { - const router = useRouter(); - const { setToken, target } = useSession(); - const { toast } = useToast(); - const [error, setError] = React.useState(null); - - React.useEffect(() => { - if (typeof window === "undefined") return; - - const raw = window.location.hash.startsWith("#") - ? window.location.hash.slice(1) - : window.location.hash; - const params = new URLSearchParams(raw); - const token = params.get("token"); - const err = params.get("error"); - - // Scrub the fragment from the address bar / history so the token does not - // linger in the URL. - window.history.replaceState(null, "", window.location.pathname); - - if (token) { - setToken(token); - toast({ kind: "success", title: "Signed in" }); - void resolvePostAuthDestination(createClient(target, token)).then((dest) => - router.replace(dest), - ); - return; - } - - setError(err ?? "oauth_failed"); - }, [router, setToken, toast, target]); - - if (error) { - return ( -
-
-

Sign-in failed

-

- {ERROR_COPY[error] ?? ERROR_COPY.oauth_failed} -

- -
-
- ); - } - - return ( -
- Completing sign-in… -
- ); -} diff --git a/apps/web-console-next/src/app/demo/page.tsx b/apps/web-console-next/src/app/demo/page.tsx deleted file mode 100644 index 61d3370..0000000 --- a/apps/web-console-next/src/app/demo/page.tsx +++ /dev/null @@ -1,284 +0,0 @@ -"use client"; - -import * as React from "react"; -import { Building2, Boxes, FolderKanban, KeyRound, Mail, Search, ScrollText, Receipt } from "lucide-react"; -import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; -import { Badge } from "@/components/ui/badge"; -import { Skeleton } from "@/components/ui/skeleton"; -import { EmptyState } from "@/components/ui/empty-state"; -import { Table, TableHeader, TableRow, TableHead, TableBody, TableCell } from "@/components/ui/table"; -import { PreconditionInsight } from "@/components/precondition/insight"; -import { ZodForm } from "@/components/ui/zod-form"; -import { z } from "zod"; -import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs"; - -/** - * /demo — a token-free showcase route. Renders all major UI states - * (skeletons, empty states, precondition variants, palette, forms, tables) - * with mock data so the screenshot capture step doesn't need an API token. - */ -export default function DemoPage() { - return ( -
-
-
-
- S -
-
-
web-console-next · demo gallery
-
- Mock data. Screenshots captured here for the task verifier. -
-
-
-
- -
- - - Precondition - Lists & tables - Forms - States - - - -
- alert("upgrade")} - onTalkToSales={() => alert("sales")} - /> -
- -
- alert("upgrade")} - /> -
- -
- alert("sales")} - /> -
- -
- -
-
- - -
-
- {mockOrgs.map((o) => ( - - -
-
- {o.name[0]} -
-
- {o.name} - {o.slug} -
-
-
- -
Created {o.created}
-
-
- ))} -
-
- -
- - - - - Subject - Type - Roles - Status - Joined - - - - {mockMembers.map((m) => ( - - {m.id} - - {m.subjectType} - - -
- {m.roles.map((r) => ( - - {r} - - ))} -
-
- - {m.status} - - {m.joined} -
- ))} -
-
-
-
-
- - -
- - - Create project - Validated by Zod, shape mirrors @saas/contracts. - - - alert("demo only")} - /> - - -
-
- - -
- - - {Array.from({ length: 4 }).map((_, i) => ( - - ))} - - -
- -
-
- - -
-
- -
- - -
- - Search actions, pages, scopes… - ⌘K -
-
    - - - - - - - -
-
-
-
-
-
-
-
- ); -} - -function Section({ title, children }: { title: string; children: React.ReactNode }) { - return ( -
-

- {title} -

- {children} -
- ); -} - -function PaletteRow({ icon: Icon, label }: { icon: React.ComponentType<{ className?: string }>; label: string }) { - return ( -
  • - - {label} -
  • - ); -} - -const mockOrgs = [ - { name: "Acme Inc", slug: "acme", created: "2026-02-14" }, - { name: "Northwind", slug: "northwind", created: "2026-03-02" }, - { name: "Globex", slug: "globex", created: "2026-05-11" }, -]; - -const mockMembers = [ - { id: "usr_8h2k…", subjectType: "user", roles: ["owner"], status: "active", joined: "2026-02-14" }, - { id: "usr_q1pA…", subjectType: "user", roles: ["admin", "billing_admin"], status: "active", joined: "2026-03-01" }, - { id: "sp_71fK…", subjectType: "service_principal", roles: ["builder"], status: "active", joined: "2026-05-22" }, - { id: "usr_LmZx…", subjectType: "user", roles: ["viewer"], status: "invited", joined: "—" }, -]; diff --git a/apps/web-console-next/src/app/error.tsx b/apps/web-console-next/src/app/error.tsx deleted file mode 100644 index a5d0e5a..0000000 --- a/apps/web-console-next/src/app/error.tsx +++ /dev/null @@ -1,53 +0,0 @@ -"use client"; - -import * as React from "react"; -import { useRouter } from "next/navigation"; - -/** - * Root segment error boundary — catches errors that escape the app shell - * (e.g. thrown by `(app)/layout.tsx` itself). Rendered inside the root layout, - * so the app's styles are available. Keeps a single page fault from - * white-screening the whole console. - */ -export default function RootError({ - error, - reset, -}: { - error: Error & { digest?: string }; - reset: () => void; -}) { - const router = useRouter(); - React.useEffect(() => { - console.error("Root error boundary:", error); - }, [error]); - - return ( -
    -
    -

    Something went wrong

    -

    - The console hit an unexpected error. Retry, or return to your organizations. -

    - {error.digest && ( -

    ref: {error.digest}

    - )} -
    - - -
    -
    -
    - ); -} diff --git a/apps/web-console-next/src/app/global-error.tsx b/apps/web-console-next/src/app/global-error.tsx deleted file mode 100644 index 06aaf44..0000000 --- a/apps/web-console-next/src/app/global-error.tsx +++ /dev/null @@ -1,78 +0,0 @@ -"use client"; - -import * as React from "react"; - -/** - * Last-resort boundary for errors in the root layout itself. It replaces the - * whole document, so it can't rely on the app's CSS/providers — inline styles - * only. This is the safety net that prevents a bare "Application error". - */ -export default function GlobalError({ - error, - reset, -}: { - error: Error & { digest?: string }; - reset: () => void; -}) { - React.useEffect(() => { - console.error("Global error boundary:", error); - }, [error]); - - return ( - - -
    -

    Something went wrong

    -

    - The console hit an unexpected error. Please retry. -

    -
    - - - Back to organizations - -
    -
    - - - ); -} diff --git a/apps/web-console-next/src/app/layout.tsx b/apps/web-console-next/src/app/layout.tsx deleted file mode 100644 index 3f6db2c..0000000 --- a/apps/web-console-next/src/app/layout.tsx +++ /dev/null @@ -1,74 +0,0 @@ -import type { Metadata, Viewport } from "next"; -import "../styles/globals.css"; -import { Providers } from "./providers"; -import { headers } from "next/headers"; -import { consoleTitle, rememberRequestHost, resolveAppConfig, type AppConfig } from "@/lib/app-config"; - -// The product's identity for this request, from the Worker's `vars` (OpenNext -// copies them into process.env per request), falling back to the compiled-in -// defaults (saas-console-artifact CA1); the deploy environment falls back to -// the one the host names (CA2). Server only: the client receives it through -// . -async function requestConfig(): Promise { - const host = (await headers()).get("host"); - rememberRequestHost(host); - return resolveAppConfig(process.env, undefined, host); -} - -export async function generateMetadata(): Promise { - const config = await requestConfig(); - return { - title: consoleTitle(config), - description: config.productDescription, - manifest: "/manifest.webmanifest", - appleWebApp: { - capable: true, - title: config.productName, - statusBarStyle: "black-translucent", - }, - }; -} - -// `viewport-fit=cover` enables `env(safe-area-inset-*)` on notched devices; -// theme-color tints the mobile browser chrome to match light/dark surfaces. -export const viewport: Viewport = { - width: "device-width", - initialScale: 1, - viewportFit: "cover", - themeColor: [ - { media: "(prefers-color-scheme: light)", color: "#ffffff" }, - { media: "(prefers-color-scheme: dark)", color: "#09090b" }, - ], -}; - -// The whole console is session-authenticated and renders nothing of value -// statically — the root Providers tree (SessionProvider, theme, CommandPalette) -// is fully client-only and trips Next.js 15's static export with -// `TypeError: Cannot read properties of undefined (reading 'url')` inside -// useMemo on every route including /_not-found. Opt the entire app out of -// static prerender at the root; per-route fixes don't help because the -// failing code paths live in the layout's Providers. -export const dynamic = "force-dynamic"; - -export default async function RootLayout({ children }: { children: React.ReactNode }) { - const config = await requestConfig(); - return ( - - - {/* - esbuild's `keepNames` helper (`__name`) is referenced by the - next-themes inline theme script in the @opennextjs/cloudflare build, - but it isn't defined in the browser — so without this shim every page - throws `ReferenceError: __name is not defined` and crashes before - hydration. Define a no-op (returning the target) ahead of that script. - */} -