diff --git a/docs/content/docs/plugins/media.mdx b/docs/content/docs/plugins/media.mdx index fb73c47bd..8f84d76dd 100644 --- a/docs/content/docs/plugins/media.mdx +++ b/docs/content/docs/plugins/media.mdx @@ -78,45 +78,64 @@ development use. ### 2. Add Plugin to Client -Register the media client plugin in your `stack-client.tsx` file: +Configure the shared client runtime once, then give Media only its own upload +and lifecycle choices: ```tsx title="lib/stack-client.tsx" -import { createStackClient } from "@btst/stack/client" +import { createClientStack } from "@btst/stack/client" import { mediaClientPlugin } from "@btst/stack/plugins/media/client" import { QueryClient } from "@tanstack/react-query" -const getBaseURL = () => - process.env.BASE_URL || "http://localhost:3000" - -export const getStackClient = (queryClient: QueryClient) => { - const baseURL = getBaseURL() - - return createStackClient({ +const getBaseURL = (serverOrigin?: string) => + typeof window !== "undefined" + ? process.env.NEXT_PUBLIC_SITE_URL || window.location.origin + : serverOrigin || + process.env.BTST_SITE_URL || + process.env.BASE_URL || + "http://localhost:3000" + +export const getStackClient = ( + queryClient: QueryClient, + options?: { + headers?: Headers + identity?: { readonly id: string; readonly [key: string]: unknown } + origin?: string + }, +) => { + const baseURL = getBaseURL(options?.origin) + + return createClientStack({ + api: { + baseURL, + basePath: "/api/data", + ...(options?.headers ? { headers: options.headers } : {}), + }, + site: { baseURL, basePath: "/pages" }, + queryClient, plugins: { media: mediaClientPlugin({ - apiBaseURL: baseURL, - apiBasePath: "/api/data", - siteBaseURL: baseURL, - siteBasePath: "/pages", - queryClient, + uploadMode: "direct", + identityPartition: options?.identity, }), }, }) } ``` -**Required configuration:** -- `apiBaseURL`: Base URL for server-side API requests -- `apiBasePath`: Path where your BTST API is mounted -- `siteBaseURL`: Base URL of your site for route metadata -- `siteBasePath`: Path where your BTST pages are mounted -- `queryClient`: React Query client used for prefetching and caching +`uploadMode` must match the backend storage adapter. `identityPartition` is the +optional request identity snapshot used to align protected SSR cache keys with +the browser's hydrated identity. API/site locations, request headers, and the +React Query client belong to `createClientStack()` and are inherited by Media. +Pass the request URL's origin as `options.origin` during SSR when a canonical +`BTST_SITE_URL` or `BASE_URL` is not configured; browser stacks use the public +site variable or `window.location.origin`. The media client plugin registers the `/media` page route and prefetches the -initial asset grid and folder tree during SSR. Browser-side API calls and -navigation use the top-level `StackProvider.api` and -`StackProvider.router` values below. +initial asset grid and folder tree during SSR. Create a request-specific stack +with `headers` on the server, and a separate browser stack without request +headers. The browser projection never serializes cookies or authorization +headers. ### 3. Import Plugin CSS @@ -131,137 +150,42 @@ This includes the built-in media library UI, picker layout, folder tree, upload ### 4. Configure the Provider -Configure top-level framework wiring and media-specific overrides in your `StackProvider`: - - - - ```tsx title="app/pages/layout.tsx" - import { StackProvider } from "@btst/stack/context" - import { nextRouter } from "@btst/stack/next" - import type { MediaPluginOverrides } from "@btst/stack/plugins/media/client" - import { useQueryClient } from "@tanstack/react-query" - - const getBaseURL = () => - typeof window !== "undefined" - ? process.env.NEXT_PUBLIC_BASE_URL || window.location.origin - : process.env.BASE_URL || "http://localhost:3000" - - type PluginOverrides = { - media: MediaPluginOverrides - } - - export default function Layout({ children }) { - const queryClient = useQueryClient() - const baseURL = getBaseURL() - - return ( - - basePath="/pages" - router={nextRouter()} - api={{ baseURL, basePath: "/api/data" }} - overrides={{ - media: { - queryClient, - uploadMode: "direct", - }, - }} - > - {children} - - ) - } - ``` - +Pass the resolved browser stack to `StackProvider`. No Media override block is +required for the built-in experience: - - ```tsx title="app/routes/pages/_layout.tsx" - import { Outlet } from "react-router" - import { StackProvider } from "@btst/stack/context" - import { reactRouter } from "@btst/stack/react-router" - import type { MediaPluginOverrides } from "@btst/stack/plugins/media/client" - import { useQueryClient } from "@tanstack/react-query" - - const getBaseURL = () => - typeof window !== "undefined" - ? import.meta.env.VITE_BASE_URL || window.location.origin - : process.env.BASE_URL || "http://localhost:5173" - - type PluginOverrides = { - media: MediaPluginOverrides - } - - export default function Layout() { - const queryClient = useQueryClient() - const baseURL = getBaseURL() - - return ( - - basePath="/pages" - router={reactRouter()} - api={{ baseURL, basePath: "/api/data" }} - overrides={{ - media: { - queryClient, - uploadMode: "direct", - }, - }} - > - - - ) - } - ``` - +```tsx title="app/pages/client-layout.tsx" +"use client" - - ```tsx title="src/routes/pages/route.tsx" - import { StackProvider } from "@btst/stack/context" - import { tanstackRouter } from "@btst/stack/tanstack" - import type { MediaPluginOverrides } from "@btst/stack/plugins/media/client" - import { Outlet } from "@tanstack/react-router" - import { useQueryClient } from "@tanstack/react-query" - - const getBaseURL = () => - typeof window !== "undefined" - ? import.meta.env.VITE_BASE_URL || window.location.origin - : process.env.BASE_URL || "http://localhost:3000" - - type PluginOverrides = { - media: MediaPluginOverrides - } - - function Layout() { - const queryClient = useQueryClient() - const baseURL = getBaseURL() - - return ( - - basePath="/pages" - router={tanstackRouter()} - api={{ baseURL, basePath: "/api/data" }} - overrides={{ - media: { - queryClient, - uploadMode: "direct", - }, - }} - > - - - ) - } - ``` - - +import { useMemo, useState } from "react" +import { QueryClient, QueryClientProvider } from "@tanstack/react-query" +import { StackProvider } from "@btst/stack/context" +import { nextRouter } from "@btst/stack/next" +import { getStackClient } from "@/lib/stack-client" -**Required overrides:** -- `queryClient` +export function ClientLayout({ children }) { + const [queryClient] = useState(() => new QueryClient()) + const stack = useMemo(() => getStackClient(queryClient), [queryClient]) -**Optional overrides:** -- `uploadMode`: Must match your backend storage adapter -- `headers`: Additional request headers -- `imageCompression`: Compression settings or `false` to disable compression -- `onRouteRender`, `onRouteError`: Route lifecycle hooks + return ( + + + {children} + + + ) +} +``` + +Use the corresponding `reactRouter()` or `tanstackRouter()` adapter in those +frameworks. `overrides.media` is reserved for genuine browser presentation and +behavior choices such as `imageCompression`, `onRouteRender`, and +`onRouteError`; it no longer accepts query clients, transport headers, or the +upload mode. For a protected library, follow the [Permissions](#permissions) +example below, which supplies both `auth={clientAuth}` and `initialIdentity`; +an identity snapshot is intentionally ignored when no auth adapter is present. ### 5. Generate and Apply Database Changes @@ -305,6 +229,7 @@ Your media plugin is now configured and ready to use. Here is a quick reference | --- | --- | | `MediaPicker` | Embed the full media browser in your own forms and editors | | `ImageInputField` | Drop-in image field with preview, change, and remove actions | +| `createMediaUploadConfig()` | Binds imperative uploads to the Media runtime resolved by the client stack | | `uploadAsset()` | Imperative upload helper for editors and non-React callbacks | | `useRegisterAssetForm()` | URL registration lifecycle with inline server field errors | | `useCreateFolderForm()` | Folder form lifecycle with notification and invalidation handling | @@ -313,16 +238,18 @@ Your media plugin is now configured and ready to use. Here is a quick reference ### Imperative uploads for editor callbacks -When you need to upload an image outside React hooks, use `uploadAsset()`: +When you need to upload an image outside React hooks, bind `uploadAsset()` to +the Media runtime already resolved by your client stack: ```tsx title="app/pages/layout.tsx" -import { uploadAsset } from "@btst/stack/plugins/media/client" +import { + createMediaUploadConfig, + uploadAsset, +} from "@btst/stack/plugins/media/client" -const mediaClientConfig = { - apiBaseURL: baseURL, - apiBasePath: "/api/data", - uploadMode: "direct" as const, -} +const mediaClientConfig = createMediaUploadConfig( + stack.provider.plugins.media, +) const uploadImage = async (file: File) => { const asset = await uploadAsset(mediaClientConfig, { file }) @@ -330,7 +257,9 @@ const uploadImage = async (file: File) => { } ``` -This is the same pattern used in the example apps to connect Blog, CMS, and Kanban image uploads to the shared Media plugin. +This preserves Media endpoint overrides, public browser headers, explicit +credentials, and the configured upload mode. The generated apps use the same +pattern to connect Blog, CMS, and Kanban image uploads to Media. ### Embedding the picker in your own UI @@ -504,17 +433,23 @@ export const clientAuth = createClientAuth({ }) // Framework layout helpers resolve this once on the server. Pass the same -// snapshot both to StackProvider and the Media SSR query partition. - - {children} - - -mediaClientPlugin({ - // ...route and API configuration - queryClient, +// snapshot to the Media SSR query partition. +const requestStack = getStackClient(queryClient, { headers: requestHeaders, - identityPartition: initialIdentity ?? undefined, + identity: initialIdentity ?? undefined, }) +await requestStack.router.getRoute("/media")?.loader?.() + +// Create a separate, header-free stack for the browser provider. +const browserStack = getStackClient(queryClient) + + + {children} + ``` The Next.js, React Router, and TanStack framework helpers hydrate @@ -744,7 +679,8 @@ BTST's Vercel Blob adapter uses `handleUpload` from `@vercel/blob/client` for th #### MediaClientConfig -The client plugin accepts the required route, site, and React Query configuration: +The factory accepts only Media-specific choices. Shared transport, site, and +React Query values come from `createClientStack()`. @@ -752,6 +688,9 @@ The client plugin accepts the required route, site, and React Query configuratio These hooks run around the media library SSR loader: +In v3, rename `onLoadError` to `onErrorLoad`. The error observer runs at most +once per loader execution, and observer failures cannot make SSR reject. + #### MediaLoaderContext @@ -852,10 +791,45 @@ The Media plugin exposes React Query-powered hooks for reading and mutating asse ### Query keys (`@btst/stack/plugins/media/query-keys`) -`mediaResources` is the shared declaration used by client hooks and SSR query factories. `createMediaQueryKeys(client, headers?)` returns these corrected v3 cache prefixes: +`mediaResources` is the shared declaration used by client hooks and SSR query factories. Media list keys include the resolved service location so stacks that share a `QueryClient` cannot read or invalidate another Media endpoint's data: + +- Asset lists: `["mediaAssets", "list", discriminator, { identity?, endpoint: { baseURL, basePath } }]` +- Folder lists: `["mediaFolders", "list", "all" | "root" | parentId, { identity?, endpoint: { baseURL, basePath } }]` + +Pass the same browser-safe endpoint partition to resource factories and raw key builders: + +```ts +import { + MEDIA_QUERY_KEYS, + type MediaEndpointPartition, +} from "@btst/stack/plugins/media/api" +import { createMediaQueryKeys } from "@btst/stack/plugins/media/query-keys" + +const endpoint: MediaEndpointPartition = { + baseURL: "https://media.example.com", + basePath: "/api/data", +} -- Asset lists: `["mediaAssets", "list", discriminator]` -- Folder lists: `["mediaFolders", "list", "all" | "root" | parentId]` +const queries = createMediaQueryKeys(client, headers) +const assetsQuery = queries.mediaAssets.list( + { limit: 40 }, + undefined, // anonymous identity partition + endpoint, +) +const foldersQuery = queries.mediaFolders.list(undefined, undefined, endpoint) + +const assetsKey = MEDIA_QUERY_KEYS.assetsList( + { limit: 40 }, + undefined, + endpoint, +) +``` + +In v3, the endpoint is a required third list argument. When migrating manual SSR or SSG prefetch code, use the exact `baseURL` and `basePath` resolved for Media in the browser stack so hydration reuses the same cache. The partition deliberately accepts no headers, credentials, or API client; keep those transport values in the client/factory configuration. For authenticated data, pass the same identity partition used by `MediaClientConfig.identityPartition` as the second argument. + +#### MediaEndpointPartition + + `useFolders(undefined)` lists all folders, while `useFolders(null)` lists only root folders. The two calls intentionally have distinct cache keys and HTTP semantics. @@ -918,13 +892,19 @@ Standalone getter and mutation exports remain lower-level adapter primitives for The raw SSG helper can prefetch the initial library without a live HTTP server: ```ts -await appStack.raw.media.prefetchForRoute("library", queryClient) +await appStack.raw.media.prefetchForRoute("library", queryClient, { + baseURL: "https://app.example.com", + basePath: "/api/data", +}) ``` This seeds the same anonymous asset/folder keys used by the browser and strips -tenant fields. It deliberately performs no request authorization. Use it only -when the generated page is intentionally public and protected at the deployment -boundary; never put private or per-user Media data into a shared static build. +tenant fields. The endpoint must exactly match the Media API location resolved +by the browser stack; it scopes the cache and resolves local-adapter asset URLs, +but accepts no headers or credentials. The helper deliberately performs no +request authorization. Use it only when the generated page is intentionally +public and protected at the deployment boundary; never put private or per-user +Media data into a shared static build. Authenticated SSR should instead forward request headers, hydrate `initialIdentity`, and pass that identity as `MediaClientConfig.identityPartition`. @@ -965,17 +945,13 @@ import { mediaClientPlugin } from "@btst/stack/plugins/media/client" import { LibraryPageComponent } from "@/components/btst/media/client/components/pages/library-page" mediaClientPlugin({ - apiBaseURL: "...", - apiBasePath: "/api/data", - siteBaseURL: "...", - siteBasePath: "/pages", - queryClient, + uploadMode: "direct", pageComponents: { library: LibraryPageComponent, // replaces the media library page }, }) ``` -The ejected library page reads API and navigation services from the top-level -`StackProvider` and media-specific upload mode, headers, and hooks from the -`media` override. +The ejected library page reads the resolved API/site/query runtime and upload +mode from the registered stack. Optional image compression and route lifecycle +customization remain in the inferred `media` provider override. diff --git a/docs/content/docs/plugins/route-docs.mdx b/docs/content/docs/plugins/route-docs.mdx index d2ee1df03..58f91aaa7 100644 --- a/docs/content/docs/plugins/route-docs.mdx +++ b/docs/content/docs/plugins/route-docs.mdx @@ -37,17 +37,21 @@ Ensure you followed the general [framework installation guide](/installation) fi Import and register the Route Docs client plugin in your client configuration: ```tsx title="lib/stack-client.tsx" -import { createStackClient } from "@btst/stack/client" +import { createClientStack } from "@btst/stack/client" import { routeDocsClientPlugin } from "@btst/stack/plugins/route-docs/client" import type { QueryClient } from "@tanstack/react-query" -export const getStackClient = (queryClient: QueryClient) => - createStackClient({ +export const getStackClient = ( + queryClient: QueryClient, + baseURL: string, +) => + createClientStack({ + api: { baseURL, basePath: "/api/data" }, + site: { baseURL, basePath: "/pages" }, + queryClient, plugins: { // Keep your other client plugin entries here. Route Docs introspects them. routeDocs: routeDocsClientPlugin({ - queryClient, - siteBasePath: "/pages", title: "Client Route Documentation", description: "Documentation for all client routes in this application", }), @@ -59,9 +63,31 @@ export const getStackClient = (queryClient: QueryClient) => The Route Docs plugin is client-only. There is no backend plugin required. -Render it under the standard provider-only layout from the -[installation guide](/installation): one top-level router and API config, with -no Route Docs override block. +Route Docs consumes only the resolved query client, site location, and +registered client definitions it needs for introspection. It does not call a +Route Docs API, require a fake backend plugin, or accept transport configuration +for symmetry. + +Render it under the standard layout from the [installation guide](/installation) +by passing the resolved stack to `StackProvider`. No Route Docs override block +is required: + +```tsx + + {children} + +``` + +Inside `StackProvider`, `useRegisteredRoutes()` is automatically bound to that +stack, so multiple stacks cannot leak route definitions into one another. Pass +the resolved stack explicitly when the hook is rendered outside the provider: + +```tsx +import { useRegisteredRoutes } from "@btst/stack/plugins/route-docs/client" + +const routes = useRegisteredRoutes() +const explicitRoutes = useRegisteredRoutes(stack) +``` ## Accessing the Documentation @@ -77,20 +103,29 @@ Replace `/pages` with your configured `siteBasePath`. ```tsx routeDocsClientPlugin({ - // React Query client for data fetching - queryClient: queryClient, - // Custom title for the documentation page title: "Client Route Documentation", - + // Description shown on the page description: "Documentation for all client routes", - - // Base path for generating URLs (default: "/pages") - siteBasePath: "/pages", - - // Custom route path (default: "/route-docs") - basePath: "/docs/routes", +}) +``` + +The canonical programmatic ID is `routeDocs`; the npm package and route keep +the `route-docs` slug. Site-origin and mount-path replacements belong to the +stack endpoint map and drive metadata plus every rendered Visit link together: + +```tsx +createClientStack({ + api, + site, + queryClient, + plugins: { routeDocs: routeDocsClientPlugin() }, + endpoints: { + routeDocs: { + site: { baseURL: "https://docs.example.com", basePath: "/" }, + }, + }, }) ``` @@ -143,14 +178,14 @@ The Route Docs page exposes your application's route structure. Consider these m const routeDocs = process.env.NODE_ENV === "development" ? { - routeDocs: routeDocsClientPlugin({ - queryClient, - siteBasePath: "/pages", - }), + routeDocs: routeDocsClientPlugin(), } : {} -createStackClient({ +createClientStack({ + api, + site, + queryClient, plugins: { // ...your other client plugins, ...routeDocs, diff --git a/docs/content/docs/shadcn-registry.mdx b/docs/content/docs/shadcn-registry.mdx index 1db5505c1..02f7ceb9f 100644 --- a/docs/content/docs/shadcn-registry.mdx +++ b/docs/content/docs/shadcn-registry.mdx @@ -251,11 +251,7 @@ import { mediaClientPlugin } from "@btst/stack/plugins/media/client" import { LibraryPageComponent } from "@/components/btst/media/client/components/pages/library-page" mediaClientPlugin({ - apiBaseURL: "...", - apiBasePath: "/api/data", - siteBaseURL: "...", - siteBasePath: "/pages", - queryClient, + uploadMode: "direct", pageComponents: { library: LibraryPageComponent, // media library page }, @@ -264,8 +260,9 @@ mediaClientPlugin({ Keep the top-level `createClientStack({ api, site, queryClient })` runtime, pass its resolved browser stack to `StackProvider.stack`, and keep the provider -router plus media-specific upload mode and hooks configured so the ejected -component uses the same runtime services as the built-in page. +router configured so the ejected component uses the same runtime services as +the built-in page. Upload mode belongs to `mediaClientPlugin()`; optional image +compression and route lifecycle callbacks remain inferred provider overrides. ## Available `pageComponents` keys diff --git a/packages/cli/src/templates/shared/lib/stack-client.tsx.hbs b/packages/cli/src/templates/shared/lib/stack-client.tsx.hbs index 2b3a9ff43..597040008 100644 --- a/packages/cli/src/templates/shared/lib/stack-client.tsx.hbs +++ b/packages/cli/src/templates/shared/lib/stack-client.tsx.hbs @@ -6,9 +6,9 @@ import { QueryClient } from "@tanstack/react-query" export function getStackClient( queryClient: QueryClient, - options?: { headers?: Headers }, + options?: { headers?: Headers; origin?: string }, ) { - const baseURL = getBaseURL() + const baseURL = getBaseURL(options?.origin) return createStackClient({ api: { baseURL, @@ -27,10 +27,11 @@ export function getStackClient( }) } -function getBaseURL() { +function getBaseURL(serverOrigin?: string) { if (typeof window !== "undefined") { - return window.location.origin + return {{{browserSiteURLExpression}}} || window.location.origin } + if (serverOrigin) return serverOrigin // Use literal process.env.XXX so bundlers (Vite define, Next.js, etc.) // can statically replace these at build/transform time. diff --git a/packages/cli/src/utils/__tests__/scaffold-plan.test.ts b/packages/cli/src/utils/__tests__/scaffold-plan.test.ts index 594186e60..33aac5527 100644 --- a/packages/cli/src/utils/__tests__/scaffold-plan.test.ts +++ b/packages/cli/src/utils/__tests__/scaffold-plan.test.ts @@ -156,7 +156,9 @@ describe("scaffold plan", () => { (f) => f.path === "lib/stack-client.tsx", ); expect(stackClientFile?.content).toContain("blogClientPlugin"); - expect(stackClientFile?.content).toContain("const baseURL = getBaseURL()"); + expect(stackClientFile?.content).toContain( + "const baseURL = getBaseURL(options?.origin)", + ); expect(stackClientFile?.content).toContain( "...(options?.headers ? { headers: options.headers } : {})", ); @@ -262,7 +264,7 @@ describe("scaffold plan", () => { ); expect(stackClientFile?.content).toBeDefined(); expect(stackClientFile?.content).toContain( - "const baseURL = getBaseURL()", + "const baseURL = getBaseURL(options?.origin)", ); expect(stackClientFile?.content).toContain( 'if (typeof window !== "undefined")', @@ -475,6 +477,52 @@ describe("scaffold plan", () => { ); }); + it.each(["nextjs", "react-router", "tanstack"] as const)( + "emits plugin-only Media and Route Docs factories for %s", + async (framework) => { + const browserSiteURLExpression = + framework === "nextjs" + ? "process.env.NEXT_PUBLIC_SITE_URL" + : "import.meta.env.VITE_PUBLIC_SITE_URL"; + const plan = await buildScaffoldPlan({ + framework, + adapter: "memory", + plugins: ["media", "route-docs"], + alias: "@/", + cssFile: + framework === "nextjs" ? "app/globals.css" : "src/styles/app.css", + }); + const stackClientFile = plan.files.find((file) => + file.path.endsWith("stack-client.tsx"), + ); + const pagesLayoutFile = plan.files.find((file) => + file.content.includes(" { const plan = await buildScaffoldPlan({ framework: "react-router", diff --git a/packages/cli/src/utils/scaffold-plan.ts b/packages/cli/src/utils/scaffold-plan.ts index eb35e7993..2a0a1c37e 100644 --- a/packages/cli/src/utils/scaffold-plan.ts +++ b/packages/cli/src/utils/scaffold-plan.ts @@ -25,6 +25,8 @@ const CANONICAL_CLIENT_PLUGIN_KEYS = new Set([ "comments", "form-builder", "kanban", + "media", + "route-docs", ]); function getFrameworkPaths(framework: Framework, cssFile: string) { @@ -66,10 +68,14 @@ function getFrameworkPaths(framework: Framework, cssFile: string) { function getPublicSiteURLVar(framework: Framework) { if (framework === "nextjs") return "NEXT_PUBLIC_SITE_URL"; - if (framework === "react-router") return "PUBLIC_SITE_URL"; return "VITE_PUBLIC_SITE_URL"; } +function getBrowserSiteURLExpression(framework: Framework) { + if (framework === "nextjs") return "process.env.NEXT_PUBLIC_SITE_URL"; + return "import.meta.env.VITE_PUBLIC_SITE_URL"; +} + function getPagesLayoutFilePath(framework: Framework): string { if (framework === "nextjs") return "app/pages/layout.tsx"; if (framework === "react-router") return "app/routes/pages/_layout.tsx"; @@ -179,9 +185,6 @@ function buildPluginTemplateContext( if (CANONICAL_CLIENT_PLUGIN_KEYS.has(m.key)) { return `\t\t\t${m.configKey}: ${m.clientSymbol}(),`; } - if (m.key === "route-docs") { - return `\t\t\t${m.configKey}: ${m.clientSymbol}({\n\t\t\t\tqueryClient,\n\t\t\t\tsiteBasePath: "/pages",\n\t\t\t}),`; - } const siteBase = "/pages"; return `\t\t\t${m.configKey}: ${m.clientSymbol}({ \t\t\t\tapiBaseURL: baseURL, @@ -194,18 +197,13 @@ function buildPluginTemplateContext( .join("\n"), pagesLayoutOverrides: clientMetas .map((m) => { - if (m.key === "route-docs") { + if (m.key === "route-docs" || m.key === "media") { return ""; } const layoutFile = getPagesLayoutFilePath(framework); if (m.key === "comments") { return ""; } - if (m.key === "media") { - return `\t\t\t\t\t"${m.key}": { -\t\t\t\t\t\tqueryClient, -\t\t\t\t\t},`; - } if (m.key === "blog") { return `\t\t\t\t\t"${m.key}": { \t\t\t\t\t\tuploadImage: async () => { @@ -329,6 +327,7 @@ export async function buildScaffoldPlan( const sharedContext = { alias: input.alias, providerApiLiteral: '{{ baseURL, basePath: "/api/data" }}', + browserSiteURLExpression: getBrowserSiteURLExpression(input.framework), publicSiteURLVar: getPublicSiteURLVar(input.framework), useGlobalSingleton: input.framework === "nextjs" && input.adapter === "memory", diff --git a/packages/stack/registry/btst-media.json b/packages/stack/registry/btst-media.json index ff367d217..2e7373fe1 100644 --- a/packages/stack/registry/btst-media.json +++ b/packages/stack/registry/btst-media.json @@ -34,6 +34,12 @@ "content": "import { definePermissions, permission } from \"@btst/stack/authorization\";\nimport { z } from \"zod\";\n\nconst tenantFact = { tenantId: z.string().optional() };\nconst folderFact = {\n\tfolderId: z.string(),\n\tparentId: z.string().optional(),\n\t...tenantFact,\n};\nconst assetFact = {\n\tassetId: z.string(),\n\tfolderId: z.string().optional(),\n\tmimeType: z.string(),\n\t...tenantFact,\n};\n\n/** Browser-safe, schema-backed permissions published by Media. */\nexport const mediaPermissions = definePermissions(\"media\", {\n\tlibrary: {\n\t\t/** Read the server-scoped asset/folder collection used by the library and picker. */\n\t\tread: permission(),\n\t},\n\tasset: {\n\t\t/** Receive, present, or select one asset from an authorized collection read. */\n\t\tread: permission(z.object(assetFact)),\n\t\t/**\n\t\t * Start or finish an upload. `callback` is reserved for a provider-verified\n\t\t * completion callback whose context was bound into the server-issued token.\n\t\t */\n\t\tupload: permission(\n\t\t\tz.object({\n\t\t\t\tphase: z.enum([\"initialize\", \"direct\", \"finalize\", \"callback\"]),\n\t\t\t\tfolderId: z.string().optional(),\n\t\t\t\t/** Omitted by pre-file browser gates; server operations always derive it. */\n\t\t\t\tmimeType: z.string().optional(),\n\t\t\t\t...tenantFact,\n\t\t\t}),\n\t\t),\n\t\t/** Update a server-resolved asset. */\n\t\tupdate: permission(\n\t\t\tz.object({\n\t\t\t\t...assetFact,\n\t\t\t\t/** `null` means moving to root; omitted means the folder is unchanged. */\n\t\t\t\ttargetFolderId: z.string().nullable().optional(),\n\t\t\t}),\n\t\t),\n\t\t/** Delete a server-resolved asset and its storage object. */\n\t\tdelete: permission(z.object(assetFact)),\n\t},\n\tfolder: {\n\t\t/** Create a folder beneath a server-resolved parent. */\n\t\tcreate: permission(\n\t\t\tz.object({\n\t\t\t\tparentId: z.string().optional(),\n\t\t\t\t...tenantFact,\n\t\t\t}),\n\t\t),\n\t\t/** Delete a server-resolved folder after authorizing every folder in its subtree. */\n\t\tdelete: permission(z.object(folderFact)),\n\t},\n});\n", "target": "src/components/btst/media/permissions.ts" }, + { + "path": "btst/media/asset-url.ts", + "type": "registry:lib", + "content": "import type { SerializedAsset } from \"./types\";\n\nexport function resolveMediaAsset(\n\tasset: SerializedAsset,\n\tapiBaseURL: string | undefined,\n): SerializedAsset {\n\tif (!apiBaseURL) return asset;\n\ttry {\n\t\tconst url = new URL(asset.url, apiBaseURL).href;\n\t\treturn url === asset.url ? asset : { ...asset, url };\n\t} catch {\n\t\treturn asset;\n\t}\n}\n", + "target": "src/components/btst/media/asset-url.ts" + }, { "path": "btst/media/client/components/media-picker/asset-card.tsx", "type": "registry:component", @@ -61,7 +67,7 @@ { "path": "btst/media/client/components/media-picker/index.tsx", "type": "registry:component", - "content": "\"use client\";\nimport { useState, type ReactNode } from \"react\";\nimport {\n\tPopover,\n\tPopoverContent,\n\tPopoverTrigger,\n} from \"@/components/ui/popover\";\nimport { Button } from \"@/components/ui/button\";\nimport {\n\tTabs,\n\tTabsContent,\n\tTabsList,\n\tTabsTrigger,\n} from \"@/components/ui/tabs\";\nimport { Image, Upload, Link, X } from \"lucide-react\";\nimport type { SerializedAsset } from \"../../../types\";\nimport { FolderTree } from \"./folder-tree\";\nimport { BrowseTab } from \"./browse-tab\";\nimport { UploadTab } from \"./upload-tab\";\nimport { UrlTab } from \"./url-tab\";\nimport {\n\tPermissionAccess,\n\tusePluginOverrides,\n\tuseStack,\n\tuseTranslate,\n} from \"@btst/stack/context\";\nimport { mediaPermissions } from \"../../../permissions\";\nimport type { MediaPluginOverrides } from \"../../overrides\";\nimport {\n\tMediaFinalizePermissionCheck,\n\tMediaUploadPermissionCheck,\n} from \"../upload-permission-check\";\n\nexport interface MediaPickerProps {\n\t/**\n\t * Element that triggers opening the picker. Required.\n\t */\n\ttrigger: ReactNode;\n\t/**\n\t * Called when the user confirms their selection.\n\t */\n\tonSelect: (assets: SerializedAsset[]) => void;\n\t/**\n\t * Allow multiple selection.\n\t * @default false\n\t */\n\tmultiple?: boolean;\n\t/**\n\t * Filter displayed assets by MIME type prefix (e.g. \"image/\").\n\t */\n\taccept?: string[];\n}\n\nfunction AssetSelectionAccess({\n\tassets,\n\tchildren,\n}: {\n\tassets: readonly SerializedAsset[];\n\tchildren: ReactNode;\n}) {\n\tconst [asset, ...rest] = assets;\n\tif (!asset) return children;\n\treturn (\n\t\t\n\t\t\t{children}\n\t\t\n\t);\n}\n\n/**\n * MediaPicker — a Popover-based media browser.\n *\n * Reads API and router config from `StackProvider`.\n *\n * @example\n * ```tsx\n * Browse media}\n * accept={[\"image/*\"]}\n * onSelect={(assets) => form.setValue(\"image\", assets[0].url)}\n * />\n * ```\n */\nexport function MediaPicker({\n\ttrigger,\n\tonSelect,\n\tmultiple = false,\n\taccept,\n}: MediaPickerProps) {\n\tconst t = useTranslate();\n\tconst { uploadMode = \"direct\" } =\n\t\tusePluginOverrides(\"media\");\n\tconst [open, setOpen] = useState(false);\n\tconst [selectedFolder, setSelectedFolder] = useState(null);\n\tconst [selectedAssets, setSelectedAssets] = useState([]);\n\tconst [activeTab, setActiveTab] = useState<\"browse\" | \"upload\" | \"url\">(\n\t\t\"browse\",\n\t);\n\n\tconst handleClose = () => {\n\t\tsetOpen(false);\n\t\tsetSelectedAssets([]);\n\t};\n\n\tconst handleConfirm = () => {\n\t\tif (selectedAssets.length === 0) return;\n\t\t// Copy selection before clearing; defer onSelect so the popover has time\n\t\t// to start its close animation before any parent state updates that might\n\t\t// unmount this component (e.g. CMSFileUpload hiding when previewUrl is set).\n\t\tconst toSelect = [...selectedAssets];\n\t\thandleClose();\n\t\tsetTimeout(() => onSelect(toSelect), 0);\n\t};\n\n\tconst handleToggleAsset = (asset: SerializedAsset) => {\n\t\tif (multiple) {\n\t\t\tsetSelectedAssets((prev) =>\n\t\t\t\tprev.some((a) => a.id === asset.id)\n\t\t\t\t\t? prev.filter((a) => a.id !== asset.id)\n\t\t\t\t\t: [...prev, asset],\n\t\t\t);\n\t\t} else {\n\t\t\tsetSelectedAssets([asset]);\n\t\t}\n\t};\n\n\tconst handleUploaded = (asset: SerializedAsset) => {\n\t\tif (multiple) {\n\t\t\tsetSelectedAssets((prev) => [...prev, asset]);\n\t\t} else {\n\t\t\tsetSelectedAssets([asset]);\n\t\t\tsetActiveTab(\"browse\");\n\t\t}\n\t};\n\n\tconst handleUrlRegistered = (asset: SerializedAsset) => {\n\t\t// URL registration grants upload-finalize permission, not read/select\n\t\t// permission. Send the result through the same asset.read-gated confirmation\n\t\t// path as browsed and uploaded assets.\n\t\thandleUploaded(asset);\n\t\tsetActiveTab(\"browse\");\n\t};\n\n\treturn (\n\t\t\n\t\t\t\n\t\t\t\t{({ can: canUpload, isPending, error }) => {\n\t\t\t\t\tif (error) throw error;\n\t\t\t\t\tconst uploadAllowed = canUpload && !isPending;\n\t\t\t\t\treturn (\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t{({ can: canFinalize, isPending: finalizePending, error }) => {\n\t\t\t\t\t\t\t\tif (error) throw error;\n\t\t\t\t\t\t\t\tconst finalizeAllowed = canFinalize && !finalizePending;\n\t\t\t\t\t\t\t\tconst visibleTab =\n\t\t\t\t\t\t\t\t\t(activeTab === \"upload\" && !uploadAllowed) ||\n\t\t\t\t\t\t\t\t\t(activeTab === \"url\" && !finalizeAllowed)\n\t\t\t\t\t\t\t\t\t\t? \"browse\"\n\t\t\t\t\t\t\t\t\t\t: activeTab;\n\t\t\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\t\t\t {\n\t\t\t\t\t\t\t\t\t\t\tif (!v) handleClose();\n\t\t\t\t\t\t\t\t\t\t\telse setOpen(true);\n\t\t\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t{trigger}\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\t\t\t{/* Header */}\n\t\t\t\t\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t{t(\"media.picker.title\", \"Media Library\")}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t
\n\n\t\t\t\t\t\t\t\t\t\t\t\t{/* Body */}\n\t\t\t\t\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\t\t\t\t{/* Folder sidebar */}\n\t\t\t\t\t\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t
\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t{/* Main panel */}\n\t\t\t\t\t\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t setActiveTab(v as any)}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tclassName=\"flex flex-1 flex-col min-h-0\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{t(\"media.tabs.browse\", \"Browse\")}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{uploadAllowed ? (\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{t(\"media.tabs.upload\", \"Upload\")}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t) : null}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{finalizeAllowed ? (\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{t(\"media.tabs.url\", \"URL\")}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t) : null}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{uploadAllowed ? (\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t) : null}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{finalizeAllowed ? (\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t) : null}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\t\t\t
\n\n\t\t\t\t\t\t\t\t\t\t\t\t{/* Footer */}\n\t\t\t\t\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t{selectedAssets.length > 0\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t? t(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"media.picker.selected\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"{{count}} selected\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcount: selectedAssets.length,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t: t(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"media.picker.selectHint\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"Click a file to select it\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{t(\"media.actions.cancel\", \"Cancel\")}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{multiple\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t? t(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"media.actions.selectMany\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"Select ({{count}})\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcount: selectedAssets.length,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t: t(\"media.actions.select\", \"Select\")}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\n\t\t\t\t\t);\n\t\t\t\t}}\n\t\t\t\n\t\t
\n\t);\n}\n\n/**\n * ImageInputField — displays an image preview with change/remove actions, or a\n * \"Browse Media\" button that opens the full MediaPicker popover (Browse / Upload / URL tabs).\n *\n * Upload mode, folder selection, and multi-mode cloud support are all handled inside\n * the MediaPicker's UploadTab — this component is purely a thin wrapper.\n */\nexport function ImageInputField({\n\tvalue,\n\tonChange,\n}: {\n\tvalue: string;\n\tonChange: (v: string) => void;\n}) {\n\tconst t = useTranslate();\n\tconst { router } = useStack();\n\tconst ImageComponent = router?.Image;\n\n\tif (value) {\n\t\treturn (\n\t\t\t
\n\t\t\t\t{ImageComponent ? (\n\t\t\t\t\t\n\t\t\t\t) : (\n\t\t\t\t\t\n\t\t\t\t)}\n\t\t\t\t
\n\t\t\t\t\t\n\t\t\t\t\t\t\t\t{t(\"media.image.change\", \"Change Image\")}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t}\n\t\t\t\t\t\taccept={[\"image/*\"]}\n\t\t\t\t\t\tonSelect={(assets) => onChange(assets[0]?.url ?? \"\")}\n\t\t\t\t\t/>\n\t\t\t\t\t onChange(\"\")}\n\t\t\t\t\t>\n\t\t\t\t\t\t{t(\"media.image.remove\", \"Remove\")}\n\t\t\t\t\t\n\t\t\t\t
\n\t\t\t
\n\t\t);\n\t}\n\n\treturn (\n\t\t
\n\t\t\t\n\t\t\t\t\t\t{t(\"media.image.browse\", \"Browse Media\")}\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\taccept={[\"image/*\"]}\n\t\t\t\tonSelect={(assets) => onChange(assets[0]?.url ?? \"\")}\n\t\t\t/>\n\t\t
\n\t);\n}\n", + "content": "\"use client\";\nimport { useState, type ReactNode } from \"react\";\nimport {\n\tPopover,\n\tPopoverContent,\n\tPopoverTrigger,\n} from \"@/components/ui/popover\";\nimport { Button } from \"@/components/ui/button\";\nimport {\n\tTabs,\n\tTabsContent,\n\tTabsList,\n\tTabsTrigger,\n} from \"@/components/ui/tabs\";\nimport { Image, Upload, Link, X } from \"lucide-react\";\nimport type { SerializedAsset } from \"../../../types\";\nimport { FolderTree } from \"./folder-tree\";\nimport { BrowseTab } from \"./browse-tab\";\nimport { UploadTab } from \"./upload-tab\";\nimport { UrlTab } from \"./url-tab\";\nimport { PermissionAccess, useStack, useTranslate } from \"@btst/stack/context\";\nimport { mediaPermissions } from \"../../../permissions\";\nimport type { MediaProviderConfig } from \"../../overrides\";\nimport { MEDIA_PLUGIN_ID } from \"../../constants\";\nimport {\n\tMediaFinalizePermissionCheck,\n\tMediaUploadPermissionCheck,\n} from \"../upload-permission-check\";\n\nexport interface MediaPickerProps {\n\t/**\n\t * Element that triggers opening the picker. Required.\n\t */\n\ttrigger: ReactNode;\n\t/**\n\t * Called when the user confirms their selection.\n\t */\n\tonSelect: (assets: SerializedAsset[]) => void;\n\t/**\n\t * Allow multiple selection.\n\t * @default false\n\t */\n\tmultiple?: boolean;\n\t/**\n\t * Filter displayed assets by MIME type prefix (e.g. \"image/\").\n\t */\n\taccept?: string[];\n}\n\nfunction AssetSelectionAccess({\n\tassets,\n\tchildren,\n}: {\n\tassets: readonly SerializedAsset[];\n\tchildren: ReactNode;\n}) {\n\tconst [asset, ...rest] = assets;\n\tif (!asset) return children;\n\treturn (\n\t\t\n\t\t\t{children}\n\t\t\n\t);\n}\n\n/**\n * MediaPicker — a Popover-based media browser.\n *\n * Reads API and router config from `StackProvider`.\n *\n * @example\n * ```tsx\n * Browse media}\n * accept={[\"image/*\"]}\n * onSelect={(assets) => form.setValue(\"image\", assets[0].url)}\n * />\n * ```\n */\nexport function MediaPicker({\n\ttrigger,\n\tonSelect,\n\tmultiple = false,\n\taccept,\n}: MediaPickerProps) {\n\tconst t = useTranslate();\n\tconst { plugins } = useStack();\n\tconst providerConfig = plugins?.[MEDIA_PLUGIN_ID]?.config as\n\t\t| MediaProviderConfig\n\t\t| undefined;\n\tconst uploadMode = providerConfig?.uploadMode ?? \"direct\";\n\tconst [open, setOpen] = useState(false);\n\tconst [selectedFolder, setSelectedFolder] = useState(null);\n\tconst [selectedAssets, setSelectedAssets] = useState([]);\n\tconst [activeTab, setActiveTab] = useState<\"browse\" | \"upload\" | \"url\">(\n\t\t\"browse\",\n\t);\n\n\tconst handleClose = () => {\n\t\tsetOpen(false);\n\t\tsetSelectedAssets([]);\n\t};\n\n\tconst handleConfirm = () => {\n\t\tif (selectedAssets.length === 0) return;\n\t\t// Copy selection before clearing; defer onSelect so the popover has time\n\t\t// to start its close animation before any parent state updates that might\n\t\t// unmount this component (e.g. CMSFileUpload hiding when previewUrl is set).\n\t\tconst toSelect = [...selectedAssets];\n\t\thandleClose();\n\t\tsetTimeout(() => onSelect(toSelect), 0);\n\t};\n\n\tconst handleToggleAsset = (asset: SerializedAsset) => {\n\t\tif (multiple) {\n\t\t\tsetSelectedAssets((prev) =>\n\t\t\t\tprev.some((a) => a.id === asset.id)\n\t\t\t\t\t? prev.filter((a) => a.id !== asset.id)\n\t\t\t\t\t: [...prev, asset],\n\t\t\t);\n\t\t} else {\n\t\t\tsetSelectedAssets([asset]);\n\t\t}\n\t};\n\n\tconst handleUploaded = (asset: SerializedAsset) => {\n\t\tif (multiple) {\n\t\t\tsetSelectedAssets((prev) => [...prev, asset]);\n\t\t} else {\n\t\t\tsetSelectedAssets([asset]);\n\t\t\tsetActiveTab(\"browse\");\n\t\t}\n\t};\n\n\tconst handleUrlRegistered = (asset: SerializedAsset) => {\n\t\t// URL registration grants upload-finalize permission, not read/select\n\t\t// permission. Send the result through the same asset.read-gated confirmation\n\t\t// path as browsed and uploaded assets.\n\t\thandleUploaded(asset);\n\t\tsetActiveTab(\"browse\");\n\t};\n\n\treturn (\n\t\t\n\t\t\t\n\t\t\t\t{({ can: canUpload, isPending, error }) => {\n\t\t\t\t\tif (error) throw error;\n\t\t\t\t\tconst uploadAllowed = canUpload && !isPending;\n\t\t\t\t\treturn (\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t{({ can: canFinalize, isPending: finalizePending, error }) => {\n\t\t\t\t\t\t\t\tif (error) throw error;\n\t\t\t\t\t\t\t\tconst finalizeAllowed = canFinalize && !finalizePending;\n\t\t\t\t\t\t\t\tconst visibleTab =\n\t\t\t\t\t\t\t\t\t(activeTab === \"upload\" && !uploadAllowed) ||\n\t\t\t\t\t\t\t\t\t(activeTab === \"url\" && !finalizeAllowed)\n\t\t\t\t\t\t\t\t\t\t? \"browse\"\n\t\t\t\t\t\t\t\t\t\t: activeTab;\n\t\t\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\t\t\t {\n\t\t\t\t\t\t\t\t\t\t\tif (!v) handleClose();\n\t\t\t\t\t\t\t\t\t\t\telse setOpen(true);\n\t\t\t\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t{trigger}\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\t\t\t{/* Header */}\n\t\t\t\t\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t{t(\"media.picker.title\", \"Media Library\")}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t
\n\n\t\t\t\t\t\t\t\t\t\t\t\t{/* Body */}\n\t\t\t\t\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\t\t\t\t{/* Folder sidebar */}\n\t\t\t\t\t\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t
\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t{/* Main panel */}\n\t\t\t\t\t\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t setActiveTab(v as any)}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tclassName=\"flex flex-1 flex-col min-h-0\"\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{t(\"media.tabs.browse\", \"Browse\")}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{uploadAllowed ? (\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{t(\"media.tabs.upload\", \"Upload\")}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t) : null}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{finalizeAllowed ? (\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{t(\"media.tabs.url\", \"URL\")}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t) : null}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{uploadAllowed ? (\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t) : null}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{finalizeAllowed ? (\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t) : null}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\t\t\t
\n\n\t\t\t\t\t\t\t\t\t\t\t\t{/* Footer */}\n\t\t\t\t\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t{selectedAssets.length > 0\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t? t(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"media.picker.selected\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"{{count}} selected\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcount: selectedAssets.length,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t: t(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"media.picker.selectHint\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"Click a file to select it\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{t(\"media.actions.cancel\", \"Cancel\")}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{multiple\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t? t(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"media.actions.selectMany\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"Select ({{count}})\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcount: selectedAssets.length,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t: t(\"media.actions.select\", \"Select\")}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\n\t\t\t\t\t);\n\t\t\t\t}}\n\t\t\t\n\t\t
\n\t);\n}\n\n/**\n * ImageInputField — displays an image preview with change/remove actions, or a\n * \"Browse Media\" button that opens the full MediaPicker popover (Browse / Upload / URL tabs).\n *\n * Upload mode, folder selection, and multi-mode cloud support are all handled inside\n * the MediaPicker's UploadTab — this component is purely a thin wrapper.\n */\nexport function ImageInputField({\n\tvalue,\n\tonChange,\n}: {\n\tvalue: string;\n\tonChange: (v: string) => void;\n}) {\n\tconst t = useTranslate();\n\tconst { router } = useStack();\n\tconst ImageComponent = router?.Image;\n\n\tif (value) {\n\t\treturn (\n\t\t\t
\n\t\t\t\t{ImageComponent ? (\n\t\t\t\t\t\n\t\t\t\t) : (\n\t\t\t\t\t\n\t\t\t\t)}\n\t\t\t\t
\n\t\t\t\t\t\n\t\t\t\t\t\t\t\t{t(\"media.image.change\", \"Change Image\")}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t}\n\t\t\t\t\t\taccept={[\"image/*\"]}\n\t\t\t\t\t\tonSelect={(assets) => onChange(assets[0]?.url ?? \"\")}\n\t\t\t\t\t/>\n\t\t\t\t\t onChange(\"\")}\n\t\t\t\t\t>\n\t\t\t\t\t\t{t(\"media.image.remove\", \"Remove\")}\n\t\t\t\t\t\n\t\t\t\t
\n\t\t\t
\n\t\t);\n\t}\n\n\treturn (\n\t\t
\n\t\t\t\n\t\t\t\t\t\t{t(\"media.image.browse\", \"Browse Media\")}\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\taccept={[\"image/*\"]}\n\t\t\t\tonSelect={(assets) => onChange(assets[0]?.url ?? \"\")}\n\t\t\t/>\n\t\t
\n\t);\n}\n", "target": "src/components/btst/media/client/components/media-picker/index.tsx" }, { @@ -85,13 +91,13 @@ { "path": "btst/media/client/components/pages/library-page.internal.tsx", "type": "registry:component", - "content": "\"use client\";\nimport { useState, useCallback, useEffect, useRef } from \"react\";\nimport { useDeleteAsset, useUploadAsset } from \"@btst/stack/plugins/media/client/hooks\";\nimport { Button } from \"@/components/ui/button\";\nimport { Upload, Loader2 } from \"lucide-react\";\nimport { cn } from \"@/lib/utils\";\nimport {\n\tuseNotify,\n\tusePluginOverrides,\n\tuseTranslate,\n} from \"@btst/stack/context\";\nimport { useListState, type ListStateSchema } from \"@btst/stack/client/hooks\";\nimport type { MediaPluginOverrides } from \"../../overrides\";\nimport { useRouteLifecycle } from \"@/hooks/use-route-lifecycle\";\nimport { BrowseTab } from \"../media-picker/browse-tab\";\nimport { FolderTree } from \"../media-picker/folder-tree\";\nimport { MediaUploadPermissionCheck } from \"../upload-permission-check\";\n\nexport function LibraryPage() {\n\tconst t = useTranslate();\n\tconst notify = useNotify();\n\tconst overrides = usePluginOverrides<\n\t\tMediaPluginOverrides,\n\t\tPartial\n\t>(\"media\", {});\n\tuseRouteLifecycle({\n\t\trouteName: \"library\",\n\t\tcontext: {\n\t\t\tpath: \"/media\",\n\t\t\tisSSR: typeof window === \"undefined\",\n\t\t},\n\t\toverrides,\n\t});\n\n\tconst [{ folder, q: search }, setListState] = useListState(\"media-library\", {\n\t\tfolder: { type: \"string\", default: \"\" },\n\t\tq: { type: \"string\", default: \"\", history: \"replace\" },\n\t} as const satisfies ListStateSchema);\n\tconst selectedFolder = folder || null;\n\tconst [searchInput, setSearchInput] = useState(search);\n\tconst lastSyncedSearch = useRef(search);\n\n\tuseEffect(() => {\n\t\tif (search !== lastSyncedSearch.current) {\n\t\t\tlastSyncedSearch.current = search;\n\t\t\tsetSearchInput(search);\n\t\t}\n\t}, [search]);\n\n\tuseEffect(() => {\n\t\tif (searchInput === search) return;\n\t\tconst timeout = setTimeout(() => {\n\t\t\tlastSyncedSearch.current = searchInput;\n\t\t\tsetListState({ q: searchInput });\n\t\t}, 300);\n\t\treturn () => clearTimeout(timeout);\n\t}, [searchInput, search, setListState]);\n\n\tconst setSelectedFolder = useCallback(\n\t\t(id: string | null) => setListState({ folder: id ?? \"\" }),\n\t\t[setListState],\n\t);\n\tconst [dragging, setDragging] = useState(false);\n\tconst fileInputRef = useRef(null);\n\tconst { mutateAsync: uploadAsset, isPending: isUploading } = useUploadAsset();\n\tconst { mutateAsync: deleteAsset } = useDeleteAsset();\n\tconst handleUpload = useCallback(\n\t\tasync (files: FileList | File[]) => {\n\t\t\tconst arr = Array.from(files);\n\t\t\tfor (const file of arr) {\n\t\t\t\ttry {\n\t\t\t\t\tawait uploadAsset({ file, folderId: selectedFolder ?? undefined });\n\t\t\t\t\tnotify.success(\n\t\t\t\t\t\tt(\"media.toasts.uploadSuccess\", \"Uploaded {{filename}}\", {\n\t\t\t\t\t\t\tfilename: file.name,\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tnotify.error(\n\t\t\t\t\t\terr instanceof Error\n\t\t\t\t\t\t\t? err.message\n\t\t\t\t\t\t\t: t(\"media.toasts.uploadError\", \"Upload failed\"),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t[notify, selectedFolder, t, uploadAsset],\n\t);\n\n\tconst handleDelete = async (id: string) => {\n\t\tif (!confirm(t(\"media.assets.deleteConfirm\", \"Delete this asset?\"))) return;\n\t\ttry {\n\t\t\tawait deleteAsset(id);\n\t\t\tnotify.success(t(\"media.toasts.deleteSuccess\", \"Asset deleted\"));\n\t\t} catch (err) {\n\t\t\tnotify.error(\n\t\t\t\terr instanceof Error\n\t\t\t\t\t? err.message\n\t\t\t\t\t: t(\"media.toasts.deleteError\", \"Delete failed\"),\n\t\t\t);\n\t\t}\n\t};\n\n\treturn (\n\t\t\n\t\t\t{({ can: canUpload, isPending, error }) => {\n\t\t\t\tif (error) throw error;\n\t\t\t\tconst uploadAllowed = canUpload && !isPending;\n\t\t\t\treturn (\n\t\t\t\t\t
\n\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t
\n\n\t\t\t\t\t\t {\n\t\t\t\t\t\t\t\tif (!uploadAllowed) return;\n\t\t\t\t\t\t\t\te.preventDefault();\n\t\t\t\t\t\t\t\tsetDragging(true);\n\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\tonDragLeave={() => setDragging(false)}\n\t\t\t\t\t\t\tonDrop={(e) => {\n\t\t\t\t\t\t\t\tif (!uploadAllowed) return;\n\t\t\t\t\t\t\t\te.preventDefault();\n\t\t\t\t\t\t\t\tsetDragging(false);\n\t\t\t\t\t\t\t\tvoid handleUpload(e.dataTransfer.files);\n\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t{/* Toolbar */}\n\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t{uploadAllowed ? (\n\t\t\t\t\t\t\t\t\t<>\n\t\t\t\t\t\t\t\t\t\t fileInputRef.current?.click()}\n\t\t\t\t\t\t\t\t\t\t\tdisabled={isUploading}\n\t\t\t\t\t\t\t\t\t\t\tclassName=\"w-full sm:w-auto\"\n\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t{isUploading ? (\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t) : (\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t\t\t\t\t\t{t(\"media.actions.upload\", \"Upload\")}\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\te.target.files && handleUpload(e.target.files)\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t) : null}\n\t\t\t\t\t\t\t
\n\n\t\t\t\t\t\t\t{/* Drop overlay */}\n\t\t\t\t\t\t\t{dragging && uploadAllowed && (\n\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t

\n\t\t\t\t\t\t\t\t\t\t\t{t(\"media.upload.dropFiles\", \"Drop files to upload\")}\n\t\t\t\t\t\t\t\t\t\t

\n\t\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t)}\n\n\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t
\n\t\t\t\t\t\t
\n\t\t\t\t\t\n\t\t\t\t);\n\t\t\t}}\n\t\t\n\t);\n}\n", + "content": "\"use client\";\nimport { useState, useCallback, useEffect, useRef } from \"react\";\nimport { useDeleteAsset, useUploadAsset } from \"@btst/stack/plugins/media/client/hooks\";\nimport { Button } from \"@/components/ui/button\";\nimport { Upload, Loader2 } from \"lucide-react\";\nimport { cn } from \"@/lib/utils\";\nimport {\n\tuseNotify,\n\tusePluginOverrides,\n\tuseStack,\n\tuseTranslate,\n} from \"@btst/stack/context\";\nimport { useListState, type ListStateSchema } from \"@btst/stack/client/hooks\";\nimport type {\n\tMediaPluginOverrides,\n\tMediaProviderConfig,\n} from \"../../overrides\";\nimport { MEDIA_PLUGIN_ID } from \"../../constants\";\nimport { useRouteLifecycle } from \"@/hooks/use-route-lifecycle\";\nimport { BrowseTab } from \"../media-picker/browse-tab\";\nimport { FolderTree } from \"../media-picker/folder-tree\";\nimport { MediaUploadPermissionCheck } from \"../upload-permission-check\";\n\nexport function LibraryPage() {\n\tconst t = useTranslate();\n\tconst notify = useNotify();\n\tconst overrides = usePluginOverrides<\n\t\tMediaPluginOverrides,\n\t\tPartial\n\t>(MEDIA_PLUGIN_ID, {});\n\tconst { plugins } = useStack();\n\tconst providerConfig = plugins?.[MEDIA_PLUGIN_ID]?.config as\n\t\t| MediaProviderConfig\n\t\t| undefined;\n\tconst uploadMode = providerConfig?.uploadMode ?? \"direct\";\n\tuseRouteLifecycle({\n\t\trouteName: \"library\",\n\t\tcontext: {\n\t\t\tpath: \"/media\",\n\t\t\tisSSR: typeof window === \"undefined\",\n\t\t},\n\t\toverrides,\n\t});\n\n\tconst [{ folder, q: search }, setListState] = useListState(\"media-library\", {\n\t\tfolder: { type: \"string\", default: \"\" },\n\t\tq: { type: \"string\", default: \"\", history: \"replace\" },\n\t} as const satisfies ListStateSchema);\n\tconst selectedFolder = folder || null;\n\tconst [searchInput, setSearchInput] = useState(search);\n\tconst lastSyncedSearch = useRef(search);\n\n\tuseEffect(() => {\n\t\tif (search !== lastSyncedSearch.current) {\n\t\t\tlastSyncedSearch.current = search;\n\t\t\tsetSearchInput(search);\n\t\t}\n\t}, [search]);\n\n\tuseEffect(() => {\n\t\tif (searchInput === search) return;\n\t\tconst timeout = setTimeout(() => {\n\t\t\tlastSyncedSearch.current = searchInput;\n\t\t\tsetListState({ q: searchInput });\n\t\t}, 300);\n\t\treturn () => clearTimeout(timeout);\n\t}, [searchInput, search, setListState]);\n\n\tconst setSelectedFolder = useCallback(\n\t\t(id: string | null) => setListState({ folder: id ?? \"\" }),\n\t\t[setListState],\n\t);\n\tconst [dragging, setDragging] = useState(false);\n\tconst fileInputRef = useRef(null);\n\tconst { mutateAsync: uploadAsset, isPending: isUploading } = useUploadAsset();\n\tconst { mutateAsync: deleteAsset } = useDeleteAsset();\n\tconst handleUpload = useCallback(\n\t\tasync (files: FileList | File[]) => {\n\t\t\tconst arr = Array.from(files);\n\t\t\tfor (const file of arr) {\n\t\t\t\ttry {\n\t\t\t\t\tawait uploadAsset({ file, folderId: selectedFolder ?? undefined });\n\t\t\t\t\tnotify.success(\n\t\t\t\t\t\tt(\"media.toasts.uploadSuccess\", \"Uploaded {{filename}}\", {\n\t\t\t\t\t\t\tfilename: file.name,\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tnotify.error(\n\t\t\t\t\t\terr instanceof Error\n\t\t\t\t\t\t\t? err.message\n\t\t\t\t\t\t\t: t(\"media.toasts.uploadError\", \"Upload failed\"),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t[notify, selectedFolder, t, uploadAsset],\n\t);\n\n\tconst handleDelete = async (id: string) => {\n\t\tif (!confirm(t(\"media.assets.deleteConfirm\", \"Delete this asset?\"))) return;\n\t\ttry {\n\t\t\tawait deleteAsset(id);\n\t\t\tnotify.success(t(\"media.toasts.deleteSuccess\", \"Asset deleted\"));\n\t\t} catch (err) {\n\t\t\tnotify.error(\n\t\t\t\terr instanceof Error\n\t\t\t\t\t? err.message\n\t\t\t\t\t: t(\"media.toasts.deleteError\", \"Delete failed\"),\n\t\t\t);\n\t\t}\n\t};\n\n\treturn (\n\t\t\n\t\t\t{({ can: canUpload, isPending, error }) => {\n\t\t\t\tif (error) throw error;\n\t\t\t\tconst uploadAllowed = canUpload && !isPending;\n\t\t\t\treturn (\n\t\t\t\t\t
\n\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t
\n\n\t\t\t\t\t\t {\n\t\t\t\t\t\t\t\tif (!uploadAllowed) return;\n\t\t\t\t\t\t\t\te.preventDefault();\n\t\t\t\t\t\t\t\tsetDragging(true);\n\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t\tonDragLeave={() => setDragging(false)}\n\t\t\t\t\t\t\tonDrop={(e) => {\n\t\t\t\t\t\t\t\tif (!uploadAllowed) return;\n\t\t\t\t\t\t\t\te.preventDefault();\n\t\t\t\t\t\t\t\tsetDragging(false);\n\t\t\t\t\t\t\t\tvoid handleUpload(e.dataTransfer.files);\n\t\t\t\t\t\t\t}}\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t{/* Toolbar */}\n\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t{uploadAllowed ? (\n\t\t\t\t\t\t\t\t\t<>\n\t\t\t\t\t\t\t\t\t\t fileInputRef.current?.click()}\n\t\t\t\t\t\t\t\t\t\t\tdisabled={isUploading}\n\t\t\t\t\t\t\t\t\t\t\tclassName=\"w-full sm:w-auto\"\n\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t{isUploading ? (\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t) : (\n\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t\t\t\t\t\t{t(\"media.actions.upload\", \"Upload\")}\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\te.target.files && handleUpload(e.target.files)\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t) : null}\n\t\t\t\t\t\t\t
\n\n\t\t\t\t\t\t\t{/* Drop overlay */}\n\t\t\t\t\t\t\t{dragging && uploadAllowed && (\n\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t

\n\t\t\t\t\t\t\t\t\t\t\t{t(\"media.upload.dropFiles\", \"Drop files to upload\")}\n\t\t\t\t\t\t\t\t\t\t

\n\t\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t)}\n\n\t\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t
\n\t\t\t\t\t\t
\n\t\t\t\t\t\n\t\t\t\t);\n\t\t\t}}\n\t\t\n\t);\n}\n", "target": "src/components/btst/media/client/components/pages/library-page.internal.tsx" }, { "path": "btst/media/client/components/pages/library-page.tsx", "type": "registry:page", - "content": "\"use client\";\nimport { lazy } from \"react\";\nimport type { FallbackProps } from \"react-error-boundary\";\nimport { usePluginOverrides } from \"@btst/stack/context\";\nimport { ComposedRoute } from \"@btst/stack/client/components\";\nimport type { MediaPluginOverrides } from \"../../overrides\";\nimport { Loader2 } from \"lucide-react\";\nimport { mediaPermissions } from \"../../../permissions\";\n\nconst LibraryPage = lazy(() =>\n\timport(\"./library-page.internal\").then((m) => ({ default: m.LibraryPage })),\n);\n\nfunction LibraryLoading() {\n\treturn (\n\t\t
\n\t\t\t\n\t\t
\n\t);\n}\n\nfunction LibraryError({ error }: FallbackProps) {\n\tconst message = error instanceof Error ? error.message : String(error);\n\treturn (\n\t\t
\n\t\t\t

{message}

\n\t\t
\n\t);\n}\n\nexport function LibraryPageComponent() {\n\tusePluginOverrides(\"media\");\n\treturn (\n\t\t null}\n\t\t\tonError={(error) => console.error(\"[btst/media] Library error:\", error)}\n\t\t/>\n\t);\n}\n", + "content": "\"use client\";\nimport { lazy } from \"react\";\nimport type { FallbackProps } from \"react-error-boundary\";\nimport { usePluginOverrides } from \"@btst/stack/context\";\nimport { ComposedRoute } from \"@btst/stack/client/components\";\nimport type { MediaPluginOverrides } from \"../../overrides\";\nimport { MEDIA_PLUGIN_ID } from \"../../constants\";\nimport { Loader2 } from \"lucide-react\";\nimport { mediaPermissions } from \"../../../permissions\";\n\nconst LibraryPage = lazy(() =>\n\timport(\"./library-page.internal\").then((m) => ({ default: m.LibraryPage })),\n);\n\nfunction LibraryLoading() {\n\treturn (\n\t\t
\n\t\t\t\n\t\t
\n\t);\n}\n\nfunction LibraryError({ error }: FallbackProps) {\n\tconst message = error instanceof Error ? error.message : String(error);\n\treturn (\n\t\t
\n\t\t\t

{message}

\n\t\t
\n\t);\n}\n\nexport function LibraryPageComponent() {\n\tusePluginOverrides(MEDIA_PLUGIN_ID);\n\treturn (\n\t\t null}\n\t\t\tonError={(error) => console.error(\"[btst/media] Library error:\", error)}\n\t\t/>\n\t);\n}\n", "target": "src/components/btst/media/client/components/pages/library-page.tsx" }, { @@ -100,16 +106,22 @@ "content": "\"use client\";\n\nimport {\n\tPermissionCheck,\n\ttype PermissionCheckState,\n} from \"@btst/stack/context\";\nimport type { ReactNode } from \"react\";\nimport { mediaPermissions } from \"../../permissions\";\nimport type { MediaUploadMode } from \"../overrides\";\n\nfunction UploadPhaseCheck({\n\tphases,\n\tfolderId,\n\tchildren,\n}: {\n\tphases: readonly (\"initialize\" | \"direct\" | \"finalize\")[];\n\tfolderId?: string;\n\tchildren: (state: PermissionCheckState) => ReactNode;\n}) {\n\tconst [phase, ...rest] = phases;\n\tif (!phase) return children({ can: true, isPending: false });\n\treturn (\n\t\t\n\t\t\t{(state) => {\n\t\t\t\tif (state.error || state.isPending || !state.can)\n\t\t\t\t\treturn children(state);\n\t\t\t\treturn (\n\t\t\t\t\t\n\t\t\t\t\t\t{children}\n\t\t\t\t\t\n\t\t\t\t);\n\t\t\t}}\n\t\t\n\t);\n}\n\n/** Gate a browser upload flow through every server phase it will invoke. */\nexport function MediaUploadPermissionCheck({\n\tmode,\n\tfolderId,\n\tchildren,\n}: {\n\tmode: MediaUploadMode;\n\tfolderId?: string;\n\tchildren: (state: PermissionCheckState) => ReactNode;\n}) {\n\treturn (\n\t\t\n\t\t\t{children}\n\t\t\n\t);\n}\n\n/** Gate URL registration through the exact finalization descriptor. */\nexport function MediaFinalizePermissionCheck({\n\tfolderId,\n\tchildren,\n}: {\n\tfolderId?: string;\n\tchildren: (state: PermissionCheckState) => ReactNode;\n}) {\n\treturn (\n\t\t\n\t\t\t{children}\n\t\t\n\t);\n}\n", "target": "src/components/btst/media/client/components/upload-permission-check.tsx" }, + { + "path": "btst/media/client/constants.ts", + "type": "registry:lib", + "content": "/** Stable programmatic ID used by Media registration, resources, and overrides. */\nexport const MEDIA_PLUGIN_ID = \"media\" as const;\n", + "target": "src/components/btst/media/client/constants.ts" + }, { "path": "btst/media/client/overrides.ts", "type": "registry:lib", - "content": "import type { QueryClient } from \"@tanstack/react-query\";\nimport type { ImageCompressionOptions } from \"./utils/image-compression\";\n\n/**\n * Upload mode — must match the storage adapter configured in mediaBackendPlugin.\n * - `\"direct\"` — local filesystem adapter, files are uploaded via `POST /media/upload`\n * - `\"s3\"` — AWS S3 / R2 / MinIO, the client fetches a presigned token then PUTs directly to S3\n * - `\"vercel-blob\"` — Vercel Blob, uses the `@vercel/blob/client` SDK for direct upload\n */\nexport type MediaUploadMode = \"direct\" | \"s3\" | \"vercel-blob\";\n\n/**\n * Overridable components and functions for the Media plugin.\n *\n * External consumers provide these when registering the media client plugin\n * via the StackProvider overrides.\n */\nexport interface MediaPluginOverrides {\n\t/**\n\t * React Query client — used by the MediaPicker to cache and fetch assets.\n\t */\n\tqueryClient: QueryClient;\n\n\t/**\n\t * Upload mode — must match the storageAdapter configured in mediaBackendPlugin.\n\t * @default \"direct\"\n\t */\n\tuploadMode?: MediaUploadMode;\n\n\t/**\n\t * Optional headers to pass with API requests (e.g., for SSR auth).\n\t */\n\theaders?: HeadersInit;\n\n\t/**\n\t * Client-side image compression applied before upload via the Canvas API.\n\t *\n\t * Images are scaled down to fit within `maxWidth` × `maxHeight` (preserving\n\t * aspect ratio) and re-encoded at `quality`. SVG and GIF files are always\n\t * passed through unchanged.\n\t *\n\t * Set to `false` to disable compression entirely.\n\t *\n\t * @default { maxWidth: 2048, maxHeight: 2048, quality: 0.85 }\n\t */\n\timageCompression?: ImageCompressionOptions | false;\n\n\t// ============ Lifecycle Hooks ============\n\n\t/**\n\t * Called when a media route is rendered.\n\t */\n\tonRouteRender?: (\n\t\trouteName: string,\n\t\tcontext: MediaRouteContext,\n\t) => void | Promise;\n\n\t/**\n\t * Called when a media route encounters an error.\n\t */\n\tonRouteError?: (\n\t\trouteName: string,\n\t\terror: Error,\n\t\tcontext: MediaRouteContext,\n\t) => void | Promise;\n}\n\nexport interface MediaRouteContext {\n\t/** Current route path */\n\tpath: string;\n\t/** Route parameters */\n\tparams?: Record;\n\t/** Whether rendering on server (true) or client (false) */\n\tisSSR: boolean;\n\t[key: string]: unknown;\n}\n", + "content": "import type { ImageCompressionOptions } from \"./utils/image-compression\";\n\n/**\n * Upload mode — must match the storage adapter configured in mediaBackendPlugin.\n * - `\"direct\"` — local filesystem adapter, files are uploaded via `POST /media/upload`\n * - `\"s3\"` — AWS S3 / R2 / MinIO, the client fetches a presigned token then PUTs directly to S3\n * - `\"vercel-blob\"` — Vercel Blob, uses the `@vercel/blob/client` SDK for direct upload\n */\nexport type MediaUploadMode = \"direct\" | \"s3\" | \"vercel-blob\";\n\n/** Browser-safe Media factory values carried by the resolved client stack. */\nexport interface MediaProviderConfig {\n\t/** Upload transport matching the server-side storage adapter. */\n\treadonly uploadMode?: MediaUploadMode;\n}\n\n/**\n * Overridable components and functions for the Media plugin.\n *\n * External consumers provide these when registering the media client plugin\n * via the StackProvider overrides.\n */\nexport interface MediaPluginOverrides {\n\t/**\n\t * Client-side image compression applied before upload via the Canvas API.\n\t *\n\t * Images are scaled down to fit within `maxWidth` × `maxHeight` (preserving\n\t * aspect ratio) and re-encoded at `quality`. SVG and GIF files are always\n\t * passed through unchanged.\n\t *\n\t * Set to `false` to disable compression entirely.\n\t *\n\t * @default { maxWidth: 2048, maxHeight: 2048, quality: 0.85 }\n\t */\n\timageCompression?: ImageCompressionOptions | false;\n\n\t// ============ Lifecycle Hooks ============\n\n\t/**\n\t * Called when a media route is rendered.\n\t */\n\tonRouteRender?: (\n\t\trouteName: string,\n\t\tcontext: MediaRouteContext,\n\t) => void | Promise;\n\n\t/**\n\t * Called when a media route encounters an error.\n\t */\n\tonRouteError?: (\n\t\trouteName: string,\n\t\terror: Error,\n\t\tcontext: MediaRouteContext,\n\t) => void | Promise;\n}\n\nexport interface MediaRouteContext {\n\t/** Current route path */\n\tpath: string;\n\t/** Route parameters */\n\tparams?: Record;\n\t/** Whether rendering on server (true) or client (false) */\n\tisSSR: boolean;\n\t[key: string]: unknown;\n}\n", "target": "src/components/btst/media/client/overrides.ts" }, { "path": "btst/media/client/upload.ts", "type": "registry:lib", - "content": "\"use client\";\n\nimport type { SerializedAsset } from \"../types\";\nimport type { MediaUploadMode } from \"./overrides\";\nimport { compressImage } from \"./utils/image-compression\";\nimport type { ImageCompressionOptions } from \"./utils/image-compression\";\n\nexport interface MediaUploadClientConfig {\n\tapiBaseURL: string;\n\tapiBasePath: string;\n\theaders?: HeadersInit;\n\tuploadMode?: MediaUploadMode;\n\timageCompression?: ImageCompressionOptions | false;\n}\n\nexport interface UploadAssetInput {\n\tfile: File;\n\tfolderId?: string;\n}\n\nconst DEFAULT_IMAGE_COMPRESSION = {\n\tmaxWidth: 2048,\n\tmaxHeight: 2048,\n\tquality: 0.85,\n} as const;\n\n/**\n * Upload an asset using the media plugin's configured storage mode.\n *\n * Use this in non-React contexts like editor `uploadImage` callbacks. React\n * components should usually prefer `useUploadAsset()`, which wraps this helper\n * and handles cache invalidation.\n */\nexport async function uploadAsset(\n\tconfig: MediaUploadClientConfig,\n\tinput: UploadAssetInput,\n): Promise {\n\tconst {\n\t\tapiBaseURL,\n\t\tapiBasePath,\n\t\theaders,\n\t\tuploadMode = \"direct\",\n\t\timageCompression,\n\t} = config;\n\tconst { file, folderId } = input;\n\n\tconst processedFile =\n\t\timageCompression === false\n\t\t\t? file\n\t\t\t: await compressImage(\n\t\t\t\t\tfile,\n\t\t\t\t\timageCompression ?? DEFAULT_IMAGE_COMPRESSION,\n\t\t\t\t);\n\n\tconst base = `${apiBaseURL}${apiBasePath}`;\n\tconst headersObj = new Headers(headers as HeadersInit | undefined);\n\n\tif (uploadMode === \"direct\") {\n\t\tconst formData = new FormData();\n\t\tformData.append(\"file\", processedFile);\n\t\tif (folderId) formData.append(\"folderId\", folderId);\n\n\t\tconst res = await fetch(`${base}/media/upload`, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: headersObj,\n\t\t\tbody: formData,\n\t\t});\n\t\tif (!res.ok) {\n\t\t\tconst err = await res.json().catch(() => ({ message: res.statusText }));\n\t\t\tthrow new Error(err.message ?? \"Upload failed\");\n\t\t}\n\t\treturn res.json();\n\t}\n\n\tif (uploadMode === \"s3\") {\n\t\tconst tokenRes = await fetch(`${base}/media/upload/token`, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: {\n\t\t\t\t...Object.fromEntries(headersObj.entries()),\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t},\n\t\t\tbody: JSON.stringify({\n\t\t\t\tfilename: processedFile.name,\n\t\t\t\tmimeType: processedFile.type,\n\t\t\t\tsize: processedFile.size,\n\t\t\t\tfolderId,\n\t\t\t}),\n\t\t});\n\t\tif (!tokenRes.ok) {\n\t\t\tconst err = await tokenRes\n\t\t\t\t.json()\n\t\t\t\t.catch(() => ({ message: tokenRes.statusText }));\n\t\t\tthrow new Error(err.message ?? \"Failed to get upload token\");\n\t\t}\n\n\t\tconst token = (await tokenRes.json()) as {\n\t\t\ttype: \"presigned-url\";\n\t\t\tpayload: {\n\t\t\t\tuploadUrl: string;\n\t\t\t\tpublicUrl: string;\n\t\t\t\tkey: string;\n\t\t\t\tmethod: \"PUT\";\n\t\t\t\theaders: Record;\n\t\t\t};\n\t\t};\n\n\t\tconst putRes = await fetch(token.payload.uploadUrl, {\n\t\t\tmethod: \"PUT\",\n\t\t\theaders: token.payload.headers,\n\t\t\tbody: processedFile,\n\t\t});\n\t\tif (!putRes.ok) throw new Error(\"Failed to upload to S3\");\n\n\t\tconst assetRes = await fetch(`${base}/media/assets`, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: {\n\t\t\t\t...Object.fromEntries(headersObj.entries()),\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t},\n\t\t\tbody: JSON.stringify({\n\t\t\t\tfilename: processedFile.name,\n\t\t\t\toriginalName: file.name,\n\t\t\t\tmimeType: processedFile.type,\n\t\t\t\tsize: processedFile.size,\n\t\t\t\turl: token.payload.publicUrl,\n\t\t\t\tfolderId,\n\t\t\t}),\n\t\t});\n\t\tif (!assetRes.ok) {\n\t\t\tconst err = await assetRes\n\t\t\t\t.json()\n\t\t\t\t.catch(() => ({ message: assetRes.statusText }));\n\t\t\tthrow new Error(err.message ?? \"Failed to register asset\");\n\t\t}\n\t\treturn assetRes.json();\n\t}\n\n\tif (uploadMode === \"vercel-blob\") {\n\t\t// Dynamic import keeps @vercel/blob/client optional.\n\t\tconst { upload } = await import(\"@vercel/blob/client\");\n\t\tconst blob = await upload(processedFile.name, processedFile, {\n\t\t\taccess: \"public\",\n\t\t\thandleUploadUrl: `${base}/media/upload/vercel-blob`,\n\t\t\tclientPayload: JSON.stringify({\n\t\t\t\tmimeType: processedFile.type,\n\t\t\t\tsize: processedFile.size,\n\t\t\t\t...(folderId ? { folderId } : {}),\n\t\t\t}),\n\t\t});\n\n\t\tconst assetRes = await fetch(`${base}/media/assets`, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: {\n\t\t\t\t...Object.fromEntries(headersObj.entries()),\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t},\n\t\t\tbody: JSON.stringify({\n\t\t\t\tfilename: processedFile.name,\n\t\t\t\toriginalName: file.name,\n\t\t\t\tmimeType: processedFile.type,\n\t\t\t\tsize: processedFile.size,\n\t\t\t\turl: blob.url,\n\t\t\t\tfolderId,\n\t\t\t}),\n\t\t});\n\t\tif (!assetRes.ok) {\n\t\t\tconst err = await assetRes\n\t\t\t\t.json()\n\t\t\t\t.catch(() => ({ message: assetRes.statusText }));\n\t\t\tthrow new Error(err.message ?? \"Failed to register asset\");\n\t\t}\n\t\treturn assetRes.json();\n\t}\n\n\tthrow new Error(`Unknown uploadMode: ${uploadMode}`);\n}\n", + "content": "\"use client\";\n\nimport { normalizePath } from \"@btst/stack/client\";\nimport type { SerializedAsset } from \"../types\";\nimport type { MediaProviderConfig, MediaUploadMode } from \"./overrides\";\nimport { resolveMediaAsset } from \"../asset-url\";\nimport { compressImage } from \"./utils/image-compression\";\nimport type { ImageCompressionOptions } from \"./utils/image-compression\";\n\n/** Transport and preprocessing options for an imperative Media upload. */\nexport interface MediaUploadClientConfig {\n\t/** Resolved Media API base URL. */\n\tapiBaseURL: string;\n\t/** Mount path of the resolved Media API endpoint. */\n\tapiBasePath: string;\n\t/** Browser-safe headers sent with Media API requests. Never include secrets. */\n\theaders?: HeadersInit;\n\t/**\n\t * Fetch credentials mode applied only to Media API requests.\n\t * Configure this explicitly when a cross-origin Media endpoint accepts\n\t * browser credentials. It is not forwarded to storage upload URLs and does\n\t * not make server-only headers safe to expose.\n\t */\n\tcredentials?: RequestCredentials;\n\t/** Upload transport matching the backend Media storage adapter. Defaults to `\"direct\"`. */\n\tuploadMode?: MediaUploadMode;\n\t/** Client-side image compression options, or `false` to skip compression. */\n\timageCompression?: ImageCompressionOptions | false;\n}\n\n/** Browser-safe Media runtime exposed as `stack.provider.plugins.media`. */\nexport interface MediaUploadProviderRuntime {\n\t/** Resolved browser transport for the Media API. */\n\treadonly api: {\n\t\t/** Resolved Media API base URL. */\n\t\treadonly baseURL: string;\n\t\t/** Media API mount path. */\n\t\treadonly basePath: string;\n\t\t/** Explicitly public headers safe to expose to browser code. */\n\t\treadonly browserHeaders?: HeadersInit;\n\t\t/** Explicit browser Fetch credentials behavior. */\n\t\treadonly credentials?: RequestCredentials;\n\t};\n\t/** Browser-safe Media factory configuration. */\n\treadonly config?: MediaProviderConfig;\n}\n\nexport interface UploadAssetInput {\n\tfile: File;\n\tfolderId?: string;\n}\n\nconst DEFAULT_IMAGE_COMPRESSION = {\n\tmaxWidth: 2048,\n\tmaxHeight: 2048,\n\tquality: 0.85,\n} as const;\n\n/**\n * Bind imperative uploads to the Media endpoint resolved by `createClientStack`.\n */\nexport function createMediaUploadConfig(\n\truntime: MediaUploadProviderRuntime,\n\toverrides: Pick = {},\n): MediaUploadClientConfig {\n\treturn {\n\t\tapiBaseURL: runtime.api.baseURL,\n\t\tapiBasePath: runtime.api.basePath,\n\t\theaders: runtime.api.browserHeaders,\n\t\tcredentials: runtime.api.credentials,\n\t\tuploadMode: runtime.config?.uploadMode ?? \"direct\",\n\t\t...overrides,\n\t};\n}\n\nfunction createMediaApiURL(\n\tapiBaseURL: string,\n\tapiBasePath: string,\n\tpath: string,\n): string {\n\treturn `${apiBaseURL}${normalizePath([apiBasePath, path].join(\"/\"))}`;\n}\n\n/**\n * Upload an asset using the media plugin's configured storage mode.\n *\n * Use this in non-React contexts like editor `uploadImage` callbacks. React\n * components should usually prefer `useUploadAsset()`, which wraps this helper\n * and handles cache invalidation.\n */\nexport async function uploadAsset(\n\tconfig: MediaUploadClientConfig,\n\tinput: UploadAssetInput,\n): Promise {\n\tconst {\n\t\tapiBaseURL,\n\t\tapiBasePath,\n\t\theaders,\n\t\tcredentials,\n\t\tuploadMode = \"direct\",\n\t\timageCompression,\n\t} = config;\n\tconst { file, folderId } = input;\n\n\tconst processedFile =\n\t\timageCompression === false\n\t\t\t? file\n\t\t\t: await compressImage(\n\t\t\t\t\tfile,\n\t\t\t\t\timageCompression ?? DEFAULT_IMAGE_COMPRESSION,\n\t\t\t\t);\n\n\tconst headersObj = new Headers(headers as HeadersInit | undefined);\n\n\tif (uploadMode === \"direct\") {\n\t\tconst formData = new FormData();\n\t\tformData.append(\"file\", processedFile);\n\t\tif (folderId) formData.append(\"folderId\", folderId);\n\n\t\tconst res = await fetch(\n\t\t\tcreateMediaApiURL(apiBaseURL, apiBasePath, \"/media/upload\"),\n\t\t\t{\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: headersObj,\n\t\t\t\tcredentials,\n\t\t\t\tbody: formData,\n\t\t\t},\n\t\t);\n\t\tif (!res.ok) {\n\t\t\tconst err = await res.json().catch(() => ({ message: res.statusText }));\n\t\t\tthrow new Error(err.message ?? \"Upload failed\");\n\t\t}\n\t\treturn resolveMediaAsset((await res.json()) as SerializedAsset, apiBaseURL);\n\t}\n\n\tif (uploadMode === \"s3\") {\n\t\tconst tokenRes = await fetch(\n\t\t\tcreateMediaApiURL(apiBaseURL, apiBasePath, \"/media/upload/token\"),\n\t\t\t{\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\t...Object.fromEntries(headersObj.entries()),\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t},\n\t\t\t\tcredentials,\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tfilename: processedFile.name,\n\t\t\t\t\tmimeType: processedFile.type,\n\t\t\t\t\tsize: processedFile.size,\n\t\t\t\t\tfolderId,\n\t\t\t\t}),\n\t\t\t},\n\t\t);\n\t\tif (!tokenRes.ok) {\n\t\t\tconst err = await tokenRes\n\t\t\t\t.json()\n\t\t\t\t.catch(() => ({ message: tokenRes.statusText }));\n\t\t\tthrow new Error(err.message ?? \"Failed to get upload token\");\n\t\t}\n\n\t\tconst token = (await tokenRes.json()) as {\n\t\t\ttype: \"presigned-url\";\n\t\t\tpayload: {\n\t\t\t\tuploadUrl: string;\n\t\t\t\tpublicUrl: string;\n\t\t\t\tkey: string;\n\t\t\t\tmethod: \"PUT\";\n\t\t\t\theaders: Record;\n\t\t\t};\n\t\t};\n\n\t\tconst putRes = await fetch(token.payload.uploadUrl, {\n\t\t\tmethod: \"PUT\",\n\t\t\theaders: token.payload.headers,\n\t\t\tbody: processedFile,\n\t\t});\n\t\tif (!putRes.ok) throw new Error(\"Failed to upload to S3\");\n\n\t\tconst assetRes = await fetch(\n\t\t\tcreateMediaApiURL(apiBaseURL, apiBasePath, \"/media/assets\"),\n\t\t\t{\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\t...Object.fromEntries(headersObj.entries()),\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t},\n\t\t\t\tcredentials,\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tfilename: processedFile.name,\n\t\t\t\t\toriginalName: file.name,\n\t\t\t\t\tmimeType: processedFile.type,\n\t\t\t\t\tsize: processedFile.size,\n\t\t\t\t\turl: token.payload.publicUrl,\n\t\t\t\t\tfolderId,\n\t\t\t\t}),\n\t\t\t},\n\t\t);\n\t\tif (!assetRes.ok) {\n\t\t\tconst err = await assetRes\n\t\t\t\t.json()\n\t\t\t\t.catch(() => ({ message: assetRes.statusText }));\n\t\t\tthrow new Error(err.message ?? \"Failed to register asset\");\n\t\t}\n\t\treturn resolveMediaAsset(\n\t\t\t(await assetRes.json()) as SerializedAsset,\n\t\t\tapiBaseURL,\n\t\t);\n\t}\n\n\tif (uploadMode === \"vercel-blob\") {\n\t\tconst handleUploadUrl = createMediaApiURL(\n\t\t\tapiBaseURL,\n\t\t\tapiBasePath,\n\t\t\t\"/media/upload/vercel-blob\",\n\t\t);\n\t\tconst clientPayload = JSON.stringify({\n\t\t\tmimeType: processedFile.type,\n\t\t\tsize: processedFile.size,\n\t\t\t...(folderId ? { folderId } : {}),\n\t\t});\n\t\tconst tokenRes = await fetch(handleUploadUrl, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: {\n\t\t\t\t...Object.fromEntries(headersObj.entries()),\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t},\n\t\t\tcredentials,\n\t\t\tbody: JSON.stringify({\n\t\t\t\ttype: \"blob.generate-client-token\",\n\t\t\t\tpayload: {\n\t\t\t\t\tpathname: processedFile.name,\n\t\t\t\t\tcallbackUrl: handleUploadUrl,\n\t\t\t\t\tclientPayload,\n\t\t\t\t\tmultipart: false,\n\t\t\t\t},\n\t\t\t}),\n\t\t});\n\t\tif (!tokenRes.ok) {\n\t\t\tconst err = await tokenRes\n\t\t\t\t.json()\n\t\t\t\t.catch(() => ({ message: tokenRes.statusText }));\n\t\t\tthrow new Error(err.message ?? \"Failed to get Vercel Blob upload token\");\n\t\t}\n\t\tconst { clientToken } = (await tokenRes.json()) as {\n\t\t\tclientToken?: string;\n\t\t};\n\t\tif (!clientToken) {\n\t\t\tthrow new Error(\"Failed to get Vercel Blob upload token\");\n\t\t}\n\n\t\t// Dynamic import keeps @vercel/blob/client optional. The app-authenticated\n\t\t// token exchange stays under our fetch control; the scoped token alone is\n\t\t// then sent to Vercel's storage origin.\n\t\tconst { put } = await import(\"@vercel/blob/client\");\n\t\tconst blob = await put(processedFile.name, processedFile, {\n\t\t\taccess: \"public\",\n\t\t\ttoken: clientToken,\n\t\t});\n\n\t\tconst assetRes = await fetch(\n\t\t\tcreateMediaApiURL(apiBaseURL, apiBasePath, \"/media/assets\"),\n\t\t\t{\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\t...Object.fromEntries(headersObj.entries()),\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t},\n\t\t\t\tcredentials,\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tfilename: processedFile.name,\n\t\t\t\t\toriginalName: file.name,\n\t\t\t\t\tmimeType: processedFile.type,\n\t\t\t\t\tsize: processedFile.size,\n\t\t\t\t\turl: blob.url,\n\t\t\t\t\tfolderId,\n\t\t\t\t}),\n\t\t\t},\n\t\t);\n\t\tif (!assetRes.ok) {\n\t\t\tconst err = await assetRes\n\t\t\t\t.json()\n\t\t\t\t.catch(() => ({ message: assetRes.statusText }));\n\t\t\tthrow new Error(err.message ?? \"Failed to register asset\");\n\t\t}\n\t\treturn resolveMediaAsset(\n\t\t\t(await assetRes.json()) as SerializedAsset,\n\t\t\tapiBaseURL,\n\t\t);\n\t}\n\n\tthrow new Error(`Unknown uploadMode: ${uploadMode}`);\n}\n", "target": "src/components/btst/media/client/upload.ts" }, { diff --git a/packages/stack/scripts/build-registry.ts b/packages/stack/scripts/build-registry.ts index ee254ab23..18e28b371 100644 --- a/packages/stack/scripts/build-registry.ts +++ b/packages/stack/scripts/build-registry.ts @@ -320,7 +320,12 @@ const PLUGINS: PluginConfig[] = [ // the package must be present at build time. extraNpmDeps: ["@vercel/blob"], extraRegistryDeps: [], - pluginRootFiles: ["types.ts", "schemas.ts", "permissions.ts"], + pluginRootFiles: [ + "types.ts", + "schemas.ts", + "permissions.ts", + "asset-url.ts", + ], }, ]; diff --git a/packages/stack/src/__tests__/client-plugin-ssr-loaders.test.ts b/packages/stack/src/__tests__/client-plugin-ssr-loaders.test.ts index 6e5d3d0b2..b8329c2f0 100644 --- a/packages/stack/src/__tests__/client-plugin-ssr-loaders.test.ts +++ b/packages/stack/src/__tests__/client-plugin-ssr-loaders.test.ts @@ -378,32 +378,64 @@ describe("client plugin SSR loaders", () => { requestedUrls.push(url); return new Response( JSON.stringify( - url.includes("/media/assets") ? { items: [], total: 0 } : [], + url.includes("/media/assets") + ? { + items: [ + { + id: "asset-ssr", + filename: "ssr.jpg", + originalName: "ssr.jpg", + mimeType: "image/jpeg", + size: 1, + url: "/uploads/ssr.jpg", + createdAt: "2026-01-01T00:00:00.000Z", + }, + ], + total: 1, + } + : [], ), { status: 200, headers: { "content-type": "application/json" } }, ); }); - const plugin = mediaClientPlugin({ - apiBaseURL: API_BASE_URL, - apiBasePath: API_BASE_PATH, - siteBaseURL: SITE_BASE_URL, - siteBasePath: SITE_BASE_PATH, + const stack = createClientStack({ + api: { + baseURL: API_BASE_URL, + basePath: API_BASE_PATH, + headers: TEST_HEADERS, + }, + site: { baseURL: SITE_BASE_URL, basePath: SITE_BASE_PATH }, queryClient, - headers: TEST_HEADERS, - identityPartition: identity, + plugins: { + media: mediaClientPlugin({ identityPartition: identity }), + }, }); - await plugin.routes().library().loader?.(); + await stack.router.getRoute("/media")?.loader?.(); const client = createApiClient({ baseURL: API_BASE_URL, basePath: API_BASE_PATH, }); + const endpoint = { + baseURL: API_BASE_URL, + basePath: API_BASE_PATH, + }; const foldersQuery = createMediaQueryKeys( client, TEST_HEADERS, - ).mediaFolders.list(undefined, identity); + ).mediaFolders.list(undefined, identity, endpoint); expect(queryClient.getQueryData(foldersQuery.queryKey)).toEqual([]); + const assetsQuery = createMediaQueryKeys( + client, + TEST_HEADERS, + ).mediaAssets.list({ limit: 40 }, identity, endpoint); + const assets = queryClient.getQueryData<{ + pages: Array<{ items: Array<{ url: string }> }>; + }>(assetsQuery.queryKey); + expect(assets?.pages[0]?.items[0]?.url).toBe( + "http://localhost:3000/uploads/ssr.jpg", + ); const folderUrl = new URL( requestedUrls.find((url) => url.includes("/media/folders")) ?? "", ); @@ -412,7 +444,7 @@ describe("client plugin SSR loaders", () => { it("media library loader reports a stored folder-prefetch error", async () => { const queryClient = new QueryClient(); - const onLoadError = vi.fn(); + const onErrorLoad = vi.fn(); vi.spyOn(globalThis, "fetch").mockImplementation(async (input) => { const url = typeof input === "string" @@ -430,20 +462,23 @@ describe("client plugin SSR loaders", () => { headers: { "content-type": "application/json" }, }); }); - const plugin = mediaClientPlugin({ - apiBaseURL: API_BASE_URL, - apiBasePath: API_BASE_PATH, - siteBaseURL: SITE_BASE_URL, - siteBasePath: SITE_BASE_PATH, + const stack = createClientStack({ + api: { + baseURL: API_BASE_URL, + basePath: API_BASE_PATH, + headers: TEST_HEADERS, + }, + site: { baseURL: SITE_BASE_URL, basePath: SITE_BASE_PATH }, queryClient, - headers: TEST_HEADERS, - hooks: { onLoadError }, + plugins: { + media: mediaClientPlugin({ hooks: { onErrorLoad } }), + }, }); - await plugin.routes().library().loader?.(); + await stack.router.getRoute("/media")?.loader?.(); - expect(onLoadError).toHaveBeenCalledTimes(1); - const [errorArg] = onLoadError.mock.calls[0] ?? []; + expect(onErrorLoad).toHaveBeenCalledTimes(1); + const [errorArg] = onErrorLoad.mock.calls[0] ?? []; expect(errorArg).toBeInstanceOf(Error); expect((errorArg as Error).message).toBe("folders unavailable"); }); diff --git a/packages/stack/src/__tests__/media-query-keys.test.ts b/packages/stack/src/__tests__/media-query-keys.test.ts index 23cda955e..6b44146b7 100644 --- a/packages/stack/src/__tests__/media-query-keys.test.ts +++ b/packages/stack/src/__tests__/media-query-keys.test.ts @@ -13,15 +13,20 @@ import { } from "../plugins/media/query-keys"; import { ROOT_FOLDER_QUERY_VALUE } from "../plugins/media/schemas"; +const ENDPOINT = { + baseURL: "https://media.example.com", + basePath: "/api/data", +}; + describe("media resource query keys", () => { it("matches the shared asset-list builder and normalizes search", () => { const client = vi.fn() as any; const queries = createMediaQueryKeys(client); const params = { folderId: "photos", query: " beach ", limit: 40 }; - expect([...queries.mediaAssets.list(params).queryKey]).toEqual([ - ...MEDIA_QUERY_KEYS.assetsList(params), - ]); + expect([ + ...queries.mediaAssets.list(params, undefined, ENDPOINT).queryKey, + ]).toEqual([...MEDIA_QUERY_KEYS.assetsList(params, undefined, ENDPOINT)]); expect(assetListDiscriminator(params).query).toBe("beach"); }); @@ -31,45 +36,82 @@ describe("media resource query keys", () => { const identity = { id: "member-a", role: "member" }; const params = { limit: 40 }; - expect(queries.mediaAssets.list(params, identity).queryKey).toEqual( - MEDIA_QUERY_KEYS.assetsList(params, identity), + expect( + queries.mediaAssets.list(params, identity, ENDPOINT).queryKey, + ).toEqual(MEDIA_QUERY_KEYS.assetsList(params, identity, ENDPOINT)); + expect( + queries.mediaFolders.list(null, identity, ENDPOINT).queryKey, + ).toEqual(MEDIA_QUERY_KEYS.foldersList(null, identity, ENDPOINT)); + }); + + it("partitions asset and folder lists by Media origin and mount path", () => { + const client = vi.fn() as any; + const queries = createMediaQueryKeys(client); + const otherOrigin = { ...ENDPOINT, baseURL: "https://other.example.com" }; + const otherPath = { ...ENDPOINT, basePath: "/media-api" }; + + for (const endpoint of [otherOrigin, otherPath]) { + expect( + queries.mediaAssets.list({}, undefined, ENDPOINT).queryKey, + ).not.toEqual(queries.mediaAssets.list({}, undefined, endpoint).queryKey); + expect( + queries.mediaFolders.list(undefined, undefined, ENDPOINT).queryKey, + ).not.toEqual( + queries.mediaFolders.list(undefined, undefined, endpoint).queryKey, + ); + } + expect( + JSON.stringify( + queries.mediaAssets.list({}, undefined, ENDPOINT).queryKey, + ), + ).toBe( + JSON.stringify(MEDIA_QUERY_KEYS.assetsList({}, undefined, ENDPOINT)), ); - expect(queries.mediaFolders.list(null, identity).queryKey).toEqual( - MEDIA_QUERY_KEYS.foldersList(null, identity), + const noisyEndpoint = { + ...ENDPOINT, + headers: { authorization: "Bearer server-secret" }, + credentials: "include", + }; + const serializedKey = JSON.stringify( + MEDIA_QUERY_KEYS.assetsList({}, undefined, noisyEndpoint), ); + expect(serializedKey).not.toContain("server-secret"); + expect(serializedKey).not.toContain("credentials"); }); it("uses distinct keys for all folders, root folders, and a parent", () => { const client = vi.fn() as any; const queries = createMediaQueryKeys(client); - expect([...queries.mediaFolders.list(undefined).queryKey]).toEqual([ - ...MEDIA_QUERY_KEYS.foldersList(undefined), + expect([ + ...queries.mediaFolders.list(undefined, undefined, ENDPOINT).queryKey, + ]).toEqual([ + ...MEDIA_QUERY_KEYS.foldersList(undefined, undefined, ENDPOINT), ]); - expect([...queries.mediaFolders.list(null).queryKey]).toEqual([ - ...MEDIA_QUERY_KEYS.foldersList(null), - ]); - expect(queries.mediaFolders.list(undefined).queryKey).not.toEqual( - queries.mediaFolders.list(null).queryKey, + expect([ + ...queries.mediaFolders.list(null, undefined, ENDPOINT).queryKey, + ]).toEqual([...MEDIA_QUERY_KEYS.foldersList(null, undefined, ENDPOINT)]); + expect( + queries.mediaFolders.list(undefined, undefined, ENDPOINT).queryKey, + ).not.toEqual( + queries.mediaFolders.list(null, undefined, ENDPOINT).queryKey, ); - expect([...queries.mediaFolders.list("parent-1").queryKey]).toEqual([ - "mediaFolders", - "list", - "parent-1", - ]); + expect([ + ...queries.mediaFolders.list("parent-1", undefined, ENDPOINT).queryKey, + ]).toEqual(MEDIA_QUERY_KEYS.foldersList("parent-1", undefined, ENDPOINT)); }); it("sends the root sentinel only for an explicit null parent", async () => { const client = vi.fn().mockResolvedValue({ data: [] }) as any; const queries = createMediaQueryKeys(client); - await queries.mediaFolders.list(undefined).queryFn(); + await queries.mediaFolders.list(undefined, undefined, ENDPOINT).queryFn(); expect(client).toHaveBeenLastCalledWith( "/media/folders", expect.objectContaining({ query: {} }), ); - await queries.mediaFolders.list(null).queryFn(); + await queries.mediaFolders.list(null, undefined, ENDPOINT).queryFn(); expect(client).toHaveBeenLastCalledWith( "/media/folders", expect.objectContaining({ @@ -78,6 +120,24 @@ describe("media resource query keys", () => { ); }); + it("normalizes relative asset URLs in the server-safe query pipeline", async () => { + const client = vi.fn().mockResolvedValue({ + data: { + items: [{ url: "/uploads/asset.jpg" }], + total: 1, + }, + }) as any; + const queries = createMediaQueryKeys(client); + + const result = await queries.mediaAssets + .list({}, undefined, ENDPOINT) + .queryFn(); + + expect(result.items[0]?.url).toBe( + "https://media.example.com/uploads/asset.jpg", + ); + }); + it("stops infinite pagination after all rows are loaded", () => { const nextPageParam = mediaResources.mediaAssets.queries.list.nextPageParam; const first = { items: new Array(20), total: 25 }; diff --git a/packages/stack/src/client/index.ts b/packages/stack/src/client/index.ts index b402d8557..0f9e3045d 100644 --- a/packages/stack/src/client/index.ts +++ b/packages/stack/src/client/index.ts @@ -189,6 +189,7 @@ export function createClientStack< const router = createRouter(allRoutes); const result: ClientStack = { + context: clientStackContext, router, async generateSitemap() { const sitemapEntries: Sitemap = []; diff --git a/packages/stack/src/context/provider.tsx b/packages/stack/src/context/provider.tsx index 29336ef56..a9ca16011 100644 --- a/packages/stack/src/context/provider.tsx +++ b/packages/stack/src/context/provider.tsx @@ -8,6 +8,7 @@ import { import type { QueryClient } from "@tanstack/react-query"; import type { ClientLocation, + ClientStackContext, ClientProviderPluginRuntime, InferredPluginOverrides, RegisteredClientPlugins, @@ -49,6 +50,8 @@ interface StackContextValue> { plugins?: Record; /** The query client owned by the resolved client stack. */ queryClient?: QueryClient; + /** Resolved plugin definitions used by client-only introspection helpers. */ + clientStackContext?: ClientStackContext; /** Top-level auth provider used by identity-aware components. */ auth?: StackClientAuth; } @@ -246,6 +249,7 @@ export function StackProvider({ site: projection?.site, plugins: projection?.plugins, queryClient: projection?.queryClient, + clientStackContext: stack?.context, auth, }; diff --git a/packages/stack/src/plugins/media/__tests__/authorization.test.ts b/packages/stack/src/plugins/media/__tests__/authorization.test.ts index d9cab1250..d39a6ab1c 100644 --- a/packages/stack/src/plugins/media/__tests__/authorization.test.ts +++ b/packages/stack/src/plugins/media/__tests__/authorization.test.ts @@ -1648,7 +1648,10 @@ describe("Media operation-first authorization", () => { name: "Nested", parentId: folder.id, }); - await seedAsset(backend, { folderId: folder.id }); + await seedAsset(backend, { + folderId: folder.id, + url: "/uploads/photo.jpg", + }); expect("prefetchForRoute" in backend.trusted.media).toBe(false); expect("getAssetById" in backend.trusted.media).toBe(false); expect( @@ -1657,22 +1660,39 @@ describe("Media operation-first authorization", () => { ).toBe(false); expect("updateAsset" in backend.trusted.media).toBe(true); const queryClient = new QueryClient(); - await backend.raw.media.prefetchForRoute("library", queryClient); + const endpoint = { + baseURL: "https://media.example.com", + basePath: "/api/data", + }; + await backend.raw.media.prefetchForRoute("library", queryClient, endpoint); const cached = queryClient.getQueryData( - MEDIA_QUERY_KEYS.assetsList({ limit: 40 }), + MEDIA_QUERY_KEYS.assetsList({ limit: 40 }, undefined, endpoint), ); expect(JSON.stringify(cached)).not.toContain("tenant-a"); - expect(queryClient.getQueryData(MEDIA_QUERY_KEYS.foldersList())).toEqual( + expect(JSON.stringify(cached)).toContain( + "https://media.example.com/uploads/photo.jpg", + ); + expect( + queryClient.getQueryData( + MEDIA_QUERY_KEYS.foldersList(undefined, undefined, endpoint), + ), + ).toEqual( expect.arrayContaining([ expect.objectContaining({ id: folder.id }), expect.objectContaining({ id: child.id, parentId: folder.id }), ]), ); expect( - JSON.stringify(queryClient.getQueryData(MEDIA_QUERY_KEYS.foldersList())), + JSON.stringify( + queryClient.getQueryData( + MEDIA_QUERY_KEYS.foldersList(undefined, undefined, endpoint), + ), + ), ).not.toContain("tenant-a"); expect( - queryClient.getQueryData(MEDIA_QUERY_KEYS.foldersList(null)), + queryClient.getQueryData( + MEDIA_QUERY_KEYS.foldersList(null, undefined, endpoint), + ), ).toBeUndefined(); }); diff --git a/packages/stack/src/plugins/media/__tests__/client-runtime.browser.test.tsx b/packages/stack/src/plugins/media/__tests__/client-runtime.browser.test.tsx new file mode 100644 index 000000000..379d54b75 --- /dev/null +++ b/packages/stack/src/plugins/media/__tests__/client-runtime.browser.test.tsx @@ -0,0 +1,947 @@ +// @vitest-environment jsdom +import { + dehydrate, + hydrate, + QueryClient, + QueryClientProvider, +} from "@tanstack/react-query"; +import { defineRoute } from "@btst/yar"; +import { act, Suspense } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { createMemoryRouter, RouterProvider } from "react-router"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { createClientStack } from "../../../client"; +import { StackProvider } from "@btst/stack/context"; +import { createReactRouterPage } from "../../../react-router"; +import { defineClientPlugin } from "../../client"; +import { + useAssets, + useCreateFolder, + useFolders, + useRegisterAsset, + useUploadAsset, +} from "../client/hooks"; +import { + createMediaUploadConfig, + mediaClientPlugin, + uploadAsset, +} from "../client"; +import { + ROUTE_DOCS_QUERY_KEY, + routeDocsClientPlugin, + useRegisteredRoutes, +} from "../../route-docs/client"; +import { generateRouteDocsSchema } from "../../route-docs/generator"; + +const { putBlob } = vi.hoisted(() => ({ + putBlob: vi.fn(), +})); + +vi.mock("@vercel/blob/client", () => ({ put: putBlob })); + +( + globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean } +).IS_REACT_ACT_ENVIRONMENT = true; + +const asset = { + id: "asset-1", + filename: "runtime.txt", + originalName: "runtime.txt", + mimeType: "text/plain", + size: 7, + url: "https://files.example/runtime.txt", + createdAt: "2026-01-01T00:00:00.000Z", +}; +const relativeAsset = { ...asset, url: "/uploads/runtime.txt" }; +const secondRelativeAsset = { + ...relativeAsset, + id: "asset-2", + filename: "runtime-2.txt", + originalName: "runtime-2.txt", + url: "/uploads/runtime-2.txt", +}; + +function jsonResponse(value: unknown) { + return new Response(JSON.stringify(value), { + status: 200, + headers: { "content-type": "application/json" }, + }); +} + +async function waitFor(check: () => boolean, timeout = 3_000) { + const start = Date.now(); + while (!check()) { + if (Date.now() - start > timeout) throw new Error("waitFor timed out"); + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 10)); + }); + } +} + +describe("Media and Route Docs browser runtime", () => { + let container: HTMLDivElement; + let root: Root; + + beforeEach(() => { + putBlob.mockReset(); + putBlob.mockResolvedValue({ url: "https://blob.example/runtime.txt" }); + container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); + }); + + afterEach(async () => { + await act(async () => root.unmount()); + container.remove(); + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + }); + + it("uses the one resolved Media endpoint for queries, JSON mutations, and uploads", async () => { + const requests: Array<{ + url: string; + method: string; + headers: Headers; + credentials: RequestCredentials; + }> = []; + vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => { + const request = + input instanceof Request ? input : new Request(input, init); + requests.push({ + url: request.url, + method: request.method, + headers: request.headers, + credentials: request.credentials, + }); + if (request.method === "GET") { + const offset = new URL(request.url).searchParams.get("offset"); + return jsonResponse({ + items: [offset === "1" ? secondRelativeAsset : relativeAsset], + total: 2, + }); + } + return jsonResponse(relativeAsset); + }); + const queryClient = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }); + const foreignQueryClient = new QueryClient(); + const stackInvalidate = vi.spyOn(queryClient, "invalidateQueries"); + const foreignInvalidate = vi.spyOn(foreignQueryClient, "invalidateQueries"); + const stack = createClientStack({ + api: { baseURL: "https://app.example.com", basePath: "/api/data" }, + site: { baseURL: "https://app.example.com", basePath: "/pages" }, + queryClient, + plugins: { media: mediaClientPlugin({ uploadMode: "direct" }) }, + endpoints: { + media: { + api: { + baseURL: "https://media.example.net", + basePath: "/btst/media", + browserHeaders: { "x-public-client": "public-value" }, + credentials: "include", + }, + }, + }, + }); + + let assetsQuery: ReturnType | undefined; + let register: + | ReturnType["mutateAsync"] + | undefined; + let registerMutation: ReturnType | undefined; + let upload: ReturnType["mutateAsync"] | undefined; + let registeredAsset: typeof asset | undefined; + let uploadedAsset: typeof asset | undefined; + let probeRenderCount = 0; + function Probe() { + probeRenderCount += 1; + assetsQuery = useAssets({ limit: 1 }); + registerMutation = useRegisterAsset(); + register = registerMutation.mutateAsync; + upload = useUploadAsset().mutateAsync; + return null; + } + + const renderProbe = async () => { + await act(async () => { + root.render( + + + + + , + ); + }); + }; + await renderProbe(); + await waitFor(() => assetsQuery?.isLoading === false); + let refetchedURL: string | undefined; + let nextPageURL: string | undefined; + await act(async () => { + const refetched = await assetsQuery?.refetch(); + refetchedURL = refetched?.data?.pages[0]?.items[0]?.url; + const nextPage = await assetsQuery?.fetchNextPage(); + nextPageURL = nextPage?.data?.pages[1]?.items[0]?.url; + }); + await act(async () => { + registeredAsset = await register?.({ + url: asset.url, + filename: asset.filename, + mimeType: asset.mimeType, + size: asset.size, + }); + uploadedAsset = await upload?.({ + file: new File(["runtime"], "runtime.txt", { type: "text/plain" }), + }); + }); + + const resolvedURL = "https://media.example.net/uploads/runtime.txt"; + expect(refetchedURL).toBe(resolvedURL); + expect(nextPageURL).toBe("https://media.example.net/uploads/runtime-2.txt"); + expect(assetsQuery?.data?.pages[0]?.items[0]).toMatchObject({ + filename: "runtime.txt", + url: resolvedURL, + }); + expect(registeredAsset?.url).toBe(resolvedURL); + expect(uploadedAsset?.url).toBe(resolvedURL); + + let callbackAsset: typeof asset | undefined; + let settledAsset: typeof asset | undefined; + await act(async () => { + registerMutation?.mutate( + { + url: asset.url, + filename: asset.filename, + mimeType: asset.mimeType, + size: asset.size, + }, + { + onSuccess: (created) => { + callbackAsset = created; + }, + onSettled: (created) => { + settledAsset = created; + }, + }, + ); + }); + await waitFor( + () => + registerMutation?.isSuccess === true && + callbackAsset !== undefined && + settledAsset !== undefined, + ); + expect(registerMutation?.data?.url).toBe(resolvedURL); + expect(callbackAsset?.url).toBe(resolvedURL); + expect(settledAsset?.url).toBe(resolvedURL); + const mutationData = registerMutation?.data; + const renderCount = probeRenderCount; + await renderProbe(); + expect(probeRenderCount).toBeGreaterThan(renderCount); + expect(registerMutation?.data).toBe(mutationData); + expect(queryClient.getMutationCache().getAll().length).toBeGreaterThan(0); + expect(foreignQueryClient.getMutationCache().getAll()).toHaveLength(0); + expect(stackInvalidate).toHaveBeenCalled(); + expect(foreignInvalidate).not.toHaveBeenCalled(); + expect(requests.some((request) => request.method === "GET")).toBe(true); + expect( + requests.filter((request) => request.method === "POST").length, + ).toBeGreaterThanOrEqual(2); + for (const request of requests) { + expect(request.url).toMatch( + /^https:\/\/media\.example\.net\/btst\/media\/media\//, + ); + expect(request.headers.get("x-public-client")).toBe("public-value"); + expect(request.headers.get("authorization")).toBeNull(); + expect(request.headers.get("cookie")).toBeNull(); + expect(request.credentials).toBe("include"); + } + }); + + it("isolates Media lists and invalidation by resolved endpoint", async () => { + const requests: string[] = []; + vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => { + const request = + input instanceof Request ? input : new Request(input, init); + requests.push(`${request.method} ${request.url}`); + const service = request.url.includes("media-a.example") ? "a" : "b"; + if (request.method === "POST") { + return jsonResponse({ + id: `folder-${service}-created`, + name: "Created", + }); + } + if (request.url.includes("/media/folders")) { + return jsonResponse([ + { id: `folder-${service}`, name: `Folder ${service}` }, + ]); + } + return jsonResponse({ + items: [ + { + ...relativeAsset, + id: `asset-${service}`, + filename: `${service}.txt`, + }, + ], + total: 1, + }); + }); + const queryClient = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }); + const createStack = (service: "a" | "b") => + createClientStack({ + api: { baseURL: "https://app.example.com", basePath: "/api" }, + site: { baseURL: "https://app.example.com", basePath: "/pages" }, + queryClient, + plugins: { media: mediaClientPlugin() }, + endpoints: { + media: { + api: { + baseURL: `https://media-${service}.example`, + basePath: `/api-${service}`, + }, + }, + }, + }); + const stackA = createStack("a"); + const stackB = createStack("b"); + const filenames: Record = {}; + const folderNames: Record = {}; + let createFolderA: + | ReturnType["mutateAsync"] + | undefined; + function Probe({ service }: { service: "a" | "b" }) { + filenames[service] = useAssets({ + limit: 1, + }).data?.pages[0]?.items[0]?.filename; + folderNames[service] = useFolders().data?.[0]?.name; + const createFolder = useCreateFolder().mutateAsync; + if (service === "a") createFolderA = createFolder; + return null; + } + + await act(async () => { + root.render( + + + + + + + + , + ); + }); + await waitFor( + () => + filenames.a === "a.txt" && + filenames.b === "b.txt" && + folderNames.a === "Folder a" && + folderNames.b === "Folder b", + ); + await act(async () => { + await createFolderA?.({ name: "Created" }); + }); + + expect( + requests.filter((request) => + request.startsWith("GET https://media-a.example/api-a/media/folders"), + ), + ).toHaveLength(2); + expect( + requests.filter((request) => + request.startsWith("GET https://media-b.example/api-b/media/folders"), + ), + ).toHaveLength(1); + expect( + queryClient.getQueriesData({ queryKey: ["mediaAssets", "list"] }), + ).toHaveLength(2); + expect( + queryClient.getQueriesData({ queryKey: ["mediaFolders", "list"] }), + ).toHaveLength(2); + }); + + it("forwards resolved transport to the Vercel Blob token exchange", async () => { + const requests: Array<{ + url: string; + headers: Headers; + credentials: RequestCredentials; + body: unknown; + }> = []; + vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => { + const request = + input instanceof Request ? input : new Request(input, init); + requests.push({ + url: request.url, + headers: request.headers, + credentials: request.credentials, + body: await request.clone().json(), + }); + return request.url.endsWith("/media/upload/vercel-blob") + ? jsonResponse({ clientToken: "vercel_blob_client_runtime" }) + : jsonResponse(relativeAsset); + }); + + const stack = createClientStack({ + api: { baseURL: "https://app.example.com", basePath: "/api/data" }, + site: { baseURL: "https://app.example.com", basePath: "/pages" }, + queryClient: new QueryClient(), + plugins: { + media: mediaClientPlugin({ uploadMode: "vercel-blob" }), + }, + endpoints: { + media: { + api: { + baseURL: "https://media.example.net", + basePath: "/btst/media", + browserHeaders: { "x-public-client": "public-value" }, + credentials: "include", + }, + }, + }, + }); + const result = await uploadAsset( + createMediaUploadConfig(stack.provider.plugins.media, { + imageCompression: false, + }), + { + file: new File(["runtime"], "runtime.txt", { type: "text/plain" }), + folderId: "folder-1", + }, + ); + + expect(result).toEqual({ + ...relativeAsset, + url: "https://media.example.net/uploads/runtime.txt", + }); + expect(requests).toHaveLength(2); + expect(requests[0]).toMatchObject({ + url: "https://media.example.net/btst/media/media/upload/vercel-blob", + credentials: "include", + body: { + type: "blob.generate-client-token", + payload: { + pathname: "runtime.txt", + callbackUrl: + "https://media.example.net/btst/media/media/upload/vercel-blob", + multipart: false, + }, + }, + }); + expect(requests[0]?.headers.get("x-public-client")).toBe("public-value"); + expect(requests[1]).toMatchObject({ + url: "https://media.example.net/btst/media/media/assets", + credentials: "include", + }); + expect(requests[1]?.headers.get("x-public-client")).toBe("public-value"); + expect(putBlob).toHaveBeenCalledWith("runtime.txt", expect.any(File), { + access: "public", + token: "vercel_blob_client_runtime", + }); + }); + + it.each([ + { + mode: "direct" as const, + expectedBtstUrls: ["https://media.example.net/media/upload"], + }, + { + mode: "s3" as const, + expectedBtstUrls: [ + "https://media.example.net/media/upload/token", + "https://media.example.net/media/assets", + ], + }, + { + mode: "vercel-blob" as const, + expectedBtstUrls: [ + "https://media.example.net/media/upload/vercel-blob", + "https://media.example.net/media/assets", + ], + }, + ])("joins Media $mode uploads to a root API mount", async (testCase) => { + const btstUrls: string[] = []; + vi.spyOn(globalThis, "fetch").mockImplementation(async (input) => { + const url = input instanceof Request ? input.url : String(input); + if (url === "https://storage.example.net/presigned") { + return new Response(null, { status: 200 }); + } + btstUrls.push(url); + if (url.endsWith("/media/upload/token")) { + return jsonResponse({ + type: "presigned-url", + payload: { + uploadUrl: "https://storage.example.net/presigned", + publicUrl: "https://files.example/runtime.txt", + key: "runtime.txt", + method: "PUT", + headers: {}, + }, + }); + } + if (url.endsWith("/media/upload/vercel-blob")) { + return jsonResponse({ clientToken: "vercel_blob_client_runtime" }); + } + return jsonResponse(asset); + }); + + await uploadAsset( + { + apiBaseURL: "https://media.example.net", + apiBasePath: "/", + uploadMode: testCase.mode, + imageCompression: false, + }, + { + file: new File(["runtime"], "runtime.txt", { type: "text/plain" }), + }, + ); + + expect(btstUrls).toEqual(testCase.expectedBtstUrls); + expect( + btstUrls.every((url) => !new URL(url).pathname.startsWith("//")), + ).toBe(true); + }); + + it("uses Route Docs' resolved cross-origin site for rendered navigation", async () => { + const queryClient = new QueryClient(); + const foreignQueryClient = new QueryClient(); + const sitemap = vi.fn(() => []); + const stack = createClientStack({ + api: { baseURL: "https://api.example.com", basePath: "/api/data" }, + site: { baseURL: "https://app.example.com", basePath: "/pages" }, + queryClient, + plugins: { + probe: defineClientPlugin({ + id: "probe", + resolve: () => ({ + routes: () => ({ + home: defineRoute("/probe", { page: () => null }), + }), + sitemap, + }), + }), + routeDocs: routeDocsClientPlugin(), + }, + endpoints: { + routeDocs: { + site: { + baseURL: "https://docs.example.net", + basePath: "/", + }, + }, + }, + }); + const route = stack.router.getRoute("/route-docs"); + const routeDefinition = stack.context.plugins.routeDocs!.routes( + stack.context, + ).docs as { + def?: { page?: () => { props: { queryKey: readonly unknown[] } } }; + }; + const queryKey = routeDefinition.def?.page?.().props.queryKey; + if (!queryKey) throw new Error("Route Docs query key was not created"); + queryClient.setQueryData( + queryKey, + generateRouteDocsSchema(stack.context, []), + ); + const PageComponent = route?.PageComponent; + const open = vi.spyOn(window, "open").mockImplementation(() => null); + + await act(async () => { + root.render( + + + loading}> + {PageComponent ? : null} + + + , + ); + }); + await waitFor(() => container.textContent?.includes("Visit") ?? false); + const visitButton = Array.from(container.querySelectorAll("button")).find( + (button) => button.textContent?.includes("Visit"), + ); + await act(async () => visitButton?.click()); + + expect(container.textContent).toContain("https://docs.example.net/probe"); + expect(open).toHaveBeenCalledWith( + "https://docs.example.net/probe", + "_blank", + "noopener,noreferrer", + ); + expect(sitemap).not.toHaveBeenCalled(); + expect( + foreignQueryClient.getQueriesData({ queryKey: ROUTE_DOCS_QUERY_KEY }), + ).toHaveLength(0); + }); + + it("isolates Route Docs pages that share one query client", async () => { + const queryClient = new QueryClient(); + const createStack = (path: string) => + createClientStack({ + api: { baseURL: "https://api.example.com", basePath: "/api" }, + site: { baseURL: "https://app.example.com", basePath: "/" }, + queryClient, + plugins: { + probe: defineClientPlugin({ + id: "probe", + resolve: () => ({ + routes: () => ({ + probe: defineRoute(path, { page: () => null }), + }), + sitemap: () => [], + }), + }), + routeDocs: routeDocsClientPlugin(), + }, + }); + const stackA = createStack("/probe-a"); + const stackB = createStack("/probe-b"); + + const renderStack = async (stack: typeof stackA) => { + const PageComponent = stack.router.getRoute("/route-docs")?.PageComponent; + await act(async () => { + root.render( + + + loading}> + {PageComponent ? : null} + + + , + ); + }); + }; + + await renderStack(stackA); + await waitFor(() => container.textContent?.includes("/probe-a") ?? false); + await renderStack(stackB); + await waitFor(() => container.textContent?.includes("/probe-b") ?? false); + expect(container.textContent).not.toContain("/probe-a"); + }); + + it("isolates client-generated Route Docs schemas by sitemap output", async () => { + const queryClient = new QueryClient(); + const createStack = (sitemapURL: string) => + createClientStack({ + api: { baseURL: "https://api.example.com", basePath: "/api" }, + site: { baseURL: "https://app.example.com", basePath: "/" }, + queryClient, + plugins: { + probe: defineClientPlugin({ + id: "probe", + resolve: () => ({ + routes: () => ({ + probe: defineRoute("/probe", { page: () => null }), + }), + sitemap: async () => [{ url: sitemapURL }], + }), + }), + routeDocs: routeDocsClientPlugin(), + }, + }); + const stackA = createStack("https://app.example.com/probe-a"); + const stackB = createStack("https://app.example.com/probe-b"); + + const renderStack = async (stack: typeof stackA) => { + const PageComponent = stack.router.getRoute("/route-docs")?.PageComponent; + await act(async () => { + root.render( + + + loading}> + {PageComponent ? : null} + + + , + ); + }); + }; + + await renderStack(stackA); + await waitFor( + () => + container.textContent?.includes("https://app.example.com/probe-a") ?? + false, + ); + await renderStack(stackB); + await waitFor( + () => + container.textContent?.includes("https://app.example.com/probe-b") ?? + false, + ); + + expect(container.textContent).not.toContain( + "https://app.example.com/probe-a", + ); + expect( + queryClient.getQueriesData({ queryKey: ROUTE_DOCS_QUERY_KEY }), + ).toHaveLength(2); + }); + + it("isolates hydrated Route Docs alias variants across reconstructed stacks", async () => { + const createStack = (queryClient: QueryClient, sitemapURL: string) => + createClientStack({ + api: { baseURL: "https://api.example.com", basePath: "/api" }, + site: { baseURL: "https://app.example.com", basePath: "/" }, + queryClient, + plugins: { + probe: defineClientPlugin({ + id: "probe", + resolve: () => ({ + routes: () => ({ + probe: defineRoute("/probe", { page: () => null }), + }), + sitemap: async () => [{ url: sitemapURL }], + }), + }), + routeDocs: routeDocsClientPlugin(), + }, + }); + + const serverQueryClient = new QueryClient(); + const serverStackA = createStack( + serverQueryClient, + "https://app.example.com/probe-a", + ); + const serverStackB = createStack( + serverQueryClient, + "https://app.example.com/probe-b", + ); + vi.stubGlobal("window", undefined); + try { + await serverStackA.router.getRoute("/route-docs")?.loader?.(); + await serverStackB.router.getRoute("/route-docs")?.loader?.(); + } finally { + vi.unstubAllGlobals(); + } + + const dehydrated = dehydrate(serverQueryClient); + expect(() => JSON.stringify(dehydrated)).not.toThrow(); + const alias = dehydrated.queries.find( + (query) => + query.queryKey[0] === "route-docs" && + query.queryKey[1] === "schema-key", + )?.state.data; + expect(alias).toEqual( + expect.arrayContaining([expect.any(String), expect.any(String)]), + ); + expect(alias).toHaveLength(2); + + const browserQueryClient = new QueryClient(); + hydrate(browserQueryClient, JSON.parse(JSON.stringify(dehydrated))); + const browserStackA = createStack( + browserQueryClient, + "https://app.example.com/probe-a", + ); + const browserStackB = createStack( + browserQueryClient, + "https://app.example.com/probe-b", + ); + + const pageProps = (stack: typeof browserStackA) => { + const route = stack.context.plugins.routeDocs!.routes(stack.context) + .docs as { + def?: { page?: () => { props: { queryKey: readonly unknown[] } } }; + }; + return route.def?.page?.().props; + }; + const propsA = pageProps(browserStackA); + const propsB = pageProps(browserStackB); + expect(() => JSON.stringify(propsA)).not.toThrow(); + expect(() => JSON.stringify(propsB)).not.toThrow(); + expect(propsA?.queryKey).not.toEqual(propsB?.queryKey); + + const renderStack = async (stack: typeof browserStackA) => { + const PageComponent = stack.router.getRoute("/route-docs")?.PageComponent; + await act(async () => { + root.render( + + + loading}> + {PageComponent ? : null} + + + , + ); + }); + }; + + await renderStack(browserStackA); + await waitFor( + () => + container.textContent?.includes("https://app.example.com/probe-a") ?? + false, + ); + await renderStack(browserStackB); + await waitFor( + () => + container.textContent?.includes("https://app.example.com/probe-b") ?? + false, + ); + expect(container.textContent).not.toContain( + "https://app.example.com/probe-a", + ); + }); + + it("resolves the React Router Route Docs key after its hydration boundary", async () => { + const createStack = ( + queryClient: QueryClient, + sitemap: () => Promise>, + ) => + createClientStack({ + api: { baseURL: "https://api.example.com", basePath: "/api" }, + site: { baseURL: "https://app.example.com", basePath: "/pages" }, + queryClient, + plugins: { + probe: defineClientPlugin({ + id: "probe", + resolve: () => ({ + routes: () => ({ + probe: defineRoute("/probe", { page: () => null }), + }), + sitemap, + }), + }), + routeDocs: routeDocsClientPlugin(), + }, + }); + const serverQueryClient = new QueryClient(); + const serverSitemapURL = "https://app.example.com/server-probe"; + const serverStack = createStack(serverQueryClient, async () => [ + { url: serverSitemapURL }, + ]); + vi.stubGlobal("window", undefined); + try { + await serverStack.router.getRoute("/route-docs")?.loader?.(); + } finally { + vi.unstubAllGlobals(); + } + const dehydratedState = JSON.parse( + JSON.stringify(dehydrate(serverQueryClient)), + ); + + const browserQueryClient = new QueryClient(); + const browserSitemap = vi.fn(async () => [ + { url: "https://app.example.com/browser-probe" }, + ]); + // The layout creates its provider stack before the nested page's + // HydrationBoundary runs, matching generated React Router applications. + const layoutStack = createStack(browserQueryClient, browserSitemap); + const hydratedAliasCounts: number[] = []; + const page = createReactRouterPage({ + getStackClient: (queryClient) => { + hydratedAliasCounts.push( + queryClient.getQueriesData({ + queryKey: ["route-docs", "schema-key"], + }).length, + ); + return createStack(queryClient, browserSitemap); + }, + getQueryClient: () => browserQueryClient, + }); + const router = createMemoryRouter( + [ + { + id: "route-docs-page", + path: "/pages/*", + Component: page.Component, + }, + ], + { + initialEntries: ["/pages/route-docs"], + hydrationData: { + loaderData: { + "route-docs-page": { + path: "/route-docs", + dehydratedState, + meta: undefined, + }, + }, + }, + }, + ); + + await act(async () => { + root.render( + + + + + , + ); + }); + await waitFor( + () => container.textContent?.includes(serverSitemapURL) ?? false, + ); + + expect(container.textContent).not.toContain( + "https://app.example.com/browser-probe", + ); + expect(hydratedAliasCounts).toEqual([1]); + expect(browserSitemap).not.toHaveBeenCalled(); + }); + + it("binds route introspection to the enclosing or explicitly supplied stack", async () => { + const createStack = (path: string) => + createClientStack({ + api: { baseURL: "https://api.example.com", basePath: "/api" }, + site: { baseURL: "https://app.example.com", basePath: "/" }, + queryClient: new QueryClient(), + plugins: { + probe: defineClientPlugin({ + id: "probe", + resolve: () => ({ + routes: () => ({ + probe: defineRoute(path, { page: () => null }), + }), + sitemap: () => [], + }), + }), + routeDocs: routeDocsClientPlugin(), + }, + }); + const stackA = createStack("/probe-a"); + const stackB = createStack("/probe-b"); + const routes: Record> = {}; + function Probe({ + name, + source, + }: { + name: string; + source?: Parameters[0]; + }) { + routes[name] = useRegisteredRoutes(source); + return null; + } + + await act(async () => { + root.render( + <> + + + + + + + + , + ); + }); + + expect(routes.providerA).toEqual([ + { path: "/probe-a", plugin: "probe", key: "probe" }, + ]); + expect(routes.providerB).toEqual([ + { path: "/probe-b", plugin: "probe", key: "probe" }, + ]); + expect(routes.explicitA).toEqual(routes.providerA); + }); +}); diff --git a/packages/stack/src/plugins/media/__tests__/client-runtime.test.ts b/packages/stack/src/plugins/media/__tests__/client-runtime.test.ts new file mode 100644 index 000000000..6471c6ff9 --- /dev/null +++ b/packages/stack/src/plugins/media/__tests__/client-runtime.test.ts @@ -0,0 +1,539 @@ +import { QueryClient } from "@tanstack/react-query"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import * as z from "zod"; +import { createClientStack } from "../../../client"; +import { defineClientPlugin } from "../../client"; +import { defineRoute } from "@btst/yar"; +import { mediaClientPlugin } from "../client"; +import { + ROUTE_DOCS_QUERY_KEY, + routeDocsClientPlugin, +} from "../../route-docs/client"; +import type { RouteDocsSchema } from "../../route-docs/generator"; + +const { mediaPageModuleLoaded } = vi.hoisted(() => ({ + mediaPageModuleLoaded: { value: false }, +})); + +vi.mock("../client/components/pages/library-page", () => { + mediaPageModuleLoaded.value = true; + return { LibraryPageComponent: () => null }; +}); + +function jsonResponse(value: unknown, status = 200) { + return new Response(JSON.stringify(value), { + status, + headers: { "content-type": "application/json" }, + }); +} + +function responseFor(input: RequestInfo | URL) { + const url = new URL(input instanceof Request ? input.url : String(input)); + if (url.pathname.endsWith("/media/assets")) { + return { items: [], total: 0 }; + } + if (url.pathname.endsWith("/media/folders")) return []; + return {}; +} + +function requestDetails(input: RequestInfo | URL, init?: RequestInit) { + const request = input instanceof Request ? input : new Request(input, init); + return { url: request.url, headers: request.headers }; +} + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe("Media and Route Docs resolved client runtime", () => { + it("keeps the Media plugin definition server-import safe", () => { + expect(mediaPageModuleLoaded.value).toBe(false); + createClientStack({ + api: { baseURL: "https://api.example.com", basePath: "/api" }, + site: { baseURL: "https://app.example.com", basePath: "/" }, + queryClient: new QueryClient(), + plugins: { media: mediaClientPlugin() }, + }); + expect(mediaPageModuleLoaded.value).toBe(false); + }); + + it("uses literal IDs and projects only browser-safe Media factory state", () => { + const queryClient = new QueryClient(); + const stack = createClientStack({ + api: { baseURL: "https://app.example.com", basePath: "/api/data" }, + site: { baseURL: "https://app.example.com", basePath: "/pages" }, + queryClient, + plugins: { + media: mediaClientPlugin({ uploadMode: "s3" }), + routeDocs: routeDocsClientPlugin(), + }, + }); + + expect(stack.provider.queryClient).toBe(queryClient); + expect(stack.provider.plugins.media.id).toBe("media"); + expect(stack.provider.plugins.routeDocs.id).toBe("routeDocs"); + expect(stack.provider.plugins.media.config).toEqual({ uploadMode: "s3" }); + expect(stack.provider.plugins.media.config).not.toHaveProperty("headers"); + expect(stack.provider.plugins.media.config).not.toHaveProperty( + "identityPartition", + ); + expect(stack.provider.plugins.routeDocs.config).toBeUndefined(); + }); + + it("drives Media loading, metadata, and hydration from one inherited runtime", async () => { + const queryClient = new QueryClient(); + const requests: Array<{ url: string; headers: Headers }> = []; + vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => { + requests.push(requestDetails(input, init)); + return jsonResponse(responseFor(input)); + }); + const identityPartition = { id: "media-user" }; + const stack = createClientStack({ + api: { + baseURL: "https://app.example.com", + basePath: "/api/data", + headers: { + authorization: "Bearer server-token", + cookie: "session=server", + "x-request": "request-value", + }, + }, + site: { baseURL: "https://www.example.com", basePath: "/pages" }, + queryClient, + plugins: { + media: mediaClientPlugin({ identityPartition }), + }, + }); + + const route = stack.router.getRoute("/media"); + await route?.loader?.(); + const metadata = await route?.meta?.(); + + expect(queryClient.getQueryCache().getAll()).toHaveLength(2); + expect(metadata).toContainEqual({ + property: "og:url", + content: "https://www.example.com/pages/media", + }); + expect(requests).toHaveLength(2); + for (const request of requests) { + expect(request.url).toMatch( + /^https:\/\/app\.example\.com\/api\/data\/media\//, + ); + expect(request.headers.get("authorization")).toBe("Bearer server-token"); + expect(request.headers.get("cookie")).toBe("session=server"); + expect(request.headers.get("x-request")).toBe("request-value"); + } + }); + + it("uses a same-origin Media path override for every loader request", async () => { + const requests: string[] = []; + vi.spyOn(globalThis, "fetch").mockImplementation(async (input) => { + requests.push(input instanceof Request ? input.url : String(input)); + return jsonResponse(responseFor(input)); + }); + const stack = createClientStack({ + api: { baseURL: "https://app.example.com", basePath: "/api/data" }, + site: { baseURL: "https://app.example.com", basePath: "/pages" }, + queryClient: new QueryClient(), + plugins: { media: mediaClientPlugin() }, + endpoints: { media: { api: { basePath: "/api/media" } } }, + }); + + await stack.router.getRoute("/media")?.loader?.(); + + expect(requests).toHaveLength(2); + for (const url of requests) { + expect(url).toMatch(/^https:\/\/app\.example\.com\/api\/media\/media\//); + } + }); + + it("isolates request headers when Media crosses origins", async () => { + const requests: Array<{ url: string; headers: Headers }> = []; + vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => { + requests.push(requestDetails(input, init)); + return jsonResponse(responseFor(input)); + }); + const stack = createClientStack({ + api: { + baseURL: "https://app.example.com", + basePath: "/api/data", + headers: { + authorization: "Bearer server-token", + cookie: "session=server", + "x-request": "request-value", + }, + }, + site: { baseURL: "https://app.example.com", basePath: "/pages" }, + queryClient: new QueryClient(), + plugins: { media: mediaClientPlugin() }, + endpoints: { + media: { + api: { + baseURL: "https://media.example.net", + basePath: "/btst/media", + browserHeaders: { "x-public-client": "public-value" }, + }, + }, + }, + }); + + await stack.router.getRoute("/media")?.loader?.(); + + expect(requests).toHaveLength(2); + for (const request of requests) { + expect(request.url).toMatch( + /^https:\/\/media\.example\.net\/btst\/media\/media\//, + ); + expect(request.headers.get("authorization")).toBeNull(); + expect(request.headers.get("cookie")).toBeNull(); + expect(request.headers.get("x-request")).toBeNull(); + expect(request.headers.get("x-public-client")).toBe("public-value"); + } + }); + + it("cannot revive removed Media transport fields and joins a root site mount", async () => { + const requests: Headers[] = []; + vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => { + requests.push(requestDetails(input, init).headers); + return jsonResponse(responseFor(input)); + }); + const legacyConfig = { + apiBaseURL: "https://legacy.example.com", + headers: { + authorization: "Bearer hidden-plugin-token", + cookie: "session=hidden-plugin", + }, + } as unknown as Parameters[0]; + const stack = createClientStack({ + api: { baseURL: "https://app.example.com", basePath: "/api/data" }, + site: { baseURL: "https://app.example.com", basePath: "/pages" }, + queryClient: new QueryClient(), + plugins: { media: mediaClientPlugin(legacyConfig) }, + endpoints: { + media: { + api: { + baseURL: "https://media.example.net", + basePath: "/btst/media", + }, + site: { + baseURL: "https://media-pages.example.net", + basePath: "/", + }, + }, + }, + }); + + const route = stack.router.getRoute("/media"); + await route?.loader?.(); + const metadata = await route?.meta?.(); + + expect(metadata).toContainEqual({ + property: "og:url", + content: "https://media-pages.example.net/media", + }); + expect(requests.length).toBeGreaterThan(0); + for (const headers of requests) { + expect(headers.get("authorization")).toBeNull(); + expect(headers.get("cookie")).toBeNull(); + } + }); + + it("contains Media error observers and reports a loader failure once", async () => { + vi.spyOn(globalThis, "fetch").mockResolvedValue( + jsonResponse({ message: "unavailable" }, 500), + ); + const onErrorLoad = vi.fn((_error: Error, _context: unknown) => { + throw new Error("reporter failed"); + }); + const stack = createClientStack({ + api: { baseURL: "https://app.example.com", basePath: "/api/data" }, + site: { baseURL: "https://app.example.com", basePath: "/pages" }, + queryClient: new QueryClient(), + plugins: { media: mediaClientPlugin({ hooks: { onErrorLoad } }) }, + }); + + await expect( + stack.router.getRoute("/media")?.loader?.(), + ).resolves.toBeUndefined(); + expect(onErrorLoad).toHaveBeenCalledTimes(1); + expect(onErrorLoad.mock.calls[0]?.[1]).toMatchObject({ + path: "/media", + isSSR: true, + apiBaseURL: "https://app.example.com", + apiBasePath: "/api/data", + }); + }); + + it("keeps Route Docs client-only and resolves site overrides independently", async () => { + const queryClient = new QueryClient(); + const probe = defineClientPlugin({ + id: "probe", + resolve: (runtime) => ({ + routes: () => ({ + probe: defineRoute("/probe", { + page: () => null, + meta: () => [{ title: "Probe" }], + }), + }), + sitemap: () => [ + { url: `${runtime.site.baseURL}${runtime.site.basePath}/probe` }, + ], + }), + }); + const stack = createClientStack({ + api: { baseURL: "https://api.example.com", basePath: "/api/data" }, + site: { baseURL: "https://app.example.com", basePath: "/pages" }, + queryClient, + plugins: { + probe, + routeDocs: routeDocsClientPlugin({ + title: "Routes", + description: "Resolved routes", + }), + }, + endpoints: { + routeDocs: { + site: { + baseURL: "https://docs.example.net", + basePath: "/", + }, + }, + }, + }); + + const route = stack.router.getRoute("/route-docs"); + await route?.loader?.(); + const metadata = await route?.meta?.(); + const schema = queryClient.getQueriesData({ + queryKey: ROUTE_DOCS_QUERY_KEY, + })[0]?.[1]; + + expect(schema?.plugins.map((plugin) => plugin.key)).toEqual(["probe"]); + expect(metadata).toContainEqual({ + property: "og:url", + content: "https://docs.example.net/route-docs", + }); + expect(stack.provider.plugins.routeDocs.site).toEqual({ + baseURL: "https://docs.example.net", + basePath: "/", + }); + }); + + it("keeps Route Docs page props serializable across the Next RSC boundary", () => { + const stack = createClientStack({ + api: { baseURL: "https://api.example.com", basePath: "/api" }, + site: { baseURL: "https://site.example.com", basePath: "/" }, + queryClient: new QueryClient(), + plugins: { routeDocs: routeDocsClientPlugin() }, + }); + const route = stack.context.plugins.routeDocs!.routes(stack.context) + .docs as { + def?: { page?: () => { props: Record } }; + }; + const props = route.def?.page?.().props; + + expect(props).toBeDefined(); + expect(props).not.toHaveProperty("loadSchema"); + expect(Object.values(props ?? {})).not.toContainEqual(expect.any(Function)); + expect(() => JSON.stringify(props)).not.toThrow(); + }); + + it("isolates Route Docs loader caches for structurally identical stacks", async () => { + const createProbe = (label: string) => + defineClientPlugin({ + id: "probe", + resolve: () => ({ + routes: () => ({ + probe: defineRoute("/probe", { page: () => null }, undefined, { + title: label, + }), + }), + sitemap: () => [ + { + url: `https://stack-${label.endsWith("A") ? "a" : "b"}.example.com/probe`, + }, + ], + }), + }); + const queryClient = new QueryClient(); + const stackA = createClientStack({ + api: { baseURL: "https://api.example.com", basePath: "/api" }, + site: { baseURL: "https://site.example.com", basePath: "/" }, + queryClient, + plugins: { + probe: createProbe("Stack A"), + routeDocs: routeDocsClientPlugin(), + }, + }); + const stackB = createClientStack({ + api: { baseURL: "https://api.example.com", basePath: "/api" }, + site: { baseURL: "https://site.example.com", basePath: "/" }, + queryClient, + plugins: { + probe: createProbe("Stack B"), + routeDocs: routeDocsClientPlugin(), + }, + }); + + await stackA.router.getRoute("/route-docs")?.loader?.(); + expect( + queryClient + .getQueriesData({ queryKey: ROUTE_DOCS_QUERY_KEY }) + .map(([, schema]) => ({ + title: schema?.plugins[0]?.routes[0]?.meta?.title, + sitemap: schema?.allSitemapEntries[0]?.url, + })), + ).toEqual([ + { + title: "Stack A", + sitemap: "https://stack-a.example.com/probe", + }, + ]); + expect(queryClient.getQueryData(ROUTE_DOCS_QUERY_KEY)).toBeUndefined(); + + await stackB.router.getRoute("/route-docs")?.loader?.(); + expect( + queryClient + .getQueriesData({ queryKey: ROUTE_DOCS_QUERY_KEY }) + .map(([, schema]) => ({ + title: schema?.plugins[0]?.routes[0]?.meta?.title, + sitemap: schema?.allSitemapEntries[0]?.url, + })) + .sort((left, right) => + String(left.title).localeCompare(String(right.title)), + ), + ).toEqual([ + { + title: "Stack A", + sitemap: "https://stack-a.example.com/probe", + }, + { + title: "Stack B", + sitemap: "https://stack-b.example.com/probe", + }, + ]); + }); + + it("reuses Route Docs loader data across equivalent stack reconstruction", async () => { + const queryClient = new QueryClient(); + const createEquivalentStack = (apiBaseURL: string, apiBasePath: string) => + createClientStack({ + api: { baseURL: apiBaseURL, basePath: apiBasePath }, + site: { baseURL: "https://site.example.com", basePath: "/" }, + queryClient, + plugins: { + probe: defineClientPlugin({ + id: "probe", + resolve: () => ({ + routes: () => ({ + probe: defineRoute( + "/probe/:id", + { page: () => null }, + { query: z.object({ view: z.string().optional() }) }, + { title: "Equivalent probe" }, + ), + }), + sitemap: () => [ + { url: "https://site.example.com/probe/example" }, + ], + }), + }), + routeDocs: routeDocsClientPlugin(), + }, + }); + const loaderStack = createEquivalentStack( + "http://internal-api:3000", + "/internal-api", + ); + const pageStack = createEquivalentStack( + "https://api.example.com", + "/public-api", + ); + const getPageQueryKey = (stack: typeof loaderStack) => { + const route = stack.context.plugins.routeDocs!.routes(stack.context) + .docs as { + def?: { page?: () => { props: { queryKey: readonly unknown[] } } }; + }; + return route.def?.page?.().props.queryKey; + }; + + await loaderStack.router.getRoute("/route-docs")?.loader?.(); + const loaderKey = getPageQueryKey(loaderStack); + const pageKey = getPageQueryKey(pageStack); + if (!loaderKey || !pageKey) + throw new Error("Route Docs key was not created"); + + expect(pageKey).toEqual(loaderKey); + expect(queryClient.getQueryData(pageKey)).toBe( + queryClient.getQueryData(loaderKey), + ); + expect( + queryClient.getQueriesData({ queryKey: ROUTE_DOCS_QUERY_KEY }), + ).toHaveLength(1); + }); + + it("isolates otherwise identical Route Docs stacks by sitemap output", async () => { + const queryClient = new QueryClient(); + const createStack = (sitemapURL: string) => + createClientStack({ + api: { baseURL: "https://api.example.com", basePath: "/api" }, + site: { baseURL: "https://site.example.com", basePath: "/" }, + queryClient, + plugins: { + probe: defineClientPlugin({ + id: "probe", + resolve: () => ({ + routes: () => ({ + probe: defineRoute("/probe", { page: () => null }, undefined, { + title: "Same probe", + }), + }), + sitemap: async () => [{ url: sitemapURL }], + }), + }), + routeDocs: routeDocsClientPlugin(), + }, + }); + const stackA = createStack("https://site.example.com/probe-a"); + const stackB = createStack("https://site.example.com/probe-b"); + const getPageQueryKey = (stack: typeof stackA) => { + const route = stack.context.plugins.routeDocs!.routes(stack.context) + .docs as { + def?: { page?: () => { props: { queryKey: readonly unknown[] } } }; + }; + return route.def?.page?.().props.queryKey; + }; + + await stackA.router.getRoute("/route-docs")?.loader?.(); + const keyA = getPageQueryKey(stackA); + await stackB.router.getRoute("/route-docs")?.loader?.(); + const keyB = getPageQueryKey(stackB); + if (!keyA || !keyB) throw new Error("Route Docs key was not created"); + + expect(keyB).not.toEqual(keyA); + expect( + queryClient.getQueryData(keyA)?.allSitemapEntries[0] + ?.url, + ).toBe("https://site.example.com/probe-a"); + expect( + queryClient.getQueryData(keyB)?.allSitemapEntries[0] + ?.url, + ).toBe("https://site.example.com/probe-b"); + expect( + queryClient.getQueriesData({ queryKey: ROUTE_DOCS_QUERY_KEY }), + ).toHaveLength(2); + + const reconstructedAKey = getPageQueryKey( + createStack("https://site.example.com/probe-a"), + ); + const reconstructedBKey = getPageQueryKey( + createStack("https://site.example.com/probe-b"), + ); + if (!reconstructedAKey || !reconstructedBKey) { + throw new Error("Reconstructed Route Docs key was not created"); + } + expect(reconstructedAKey).not.toEqual(keyB); + expect(reconstructedBKey).not.toEqual(keyB); + expect(reconstructedAKey).not.toEqual(reconstructedBKey); + }); +}); diff --git a/packages/stack/src/plugins/media/__tests__/client-runtime.typecheck.tsx b/packages/stack/src/plugins/media/__tests__/client-runtime.typecheck.tsx new file mode 100644 index 000000000..a5d0b6c81 --- /dev/null +++ b/packages/stack/src/plugins/media/__tests__/client-runtime.typecheck.tsx @@ -0,0 +1,135 @@ +import { QueryClient } from "@tanstack/react-query"; +import { createClientStack } from "../../../client"; +import { StackProvider } from "../../../context"; +import { + mediaClientPlugin, + type MediaClientConfig, + type MediaPluginOverrides, +} from "../client"; +import { + routeDocsClientPlugin, + type RouteDocsClientConfig, + useRegisteredRoutes, +} from "../../route-docs/client"; + +const queryClient = new QueryClient(); +const mediaDefinition = mediaClientPlugin({ + uploadMode: "s3", + hooks: { onErrorLoad: () => undefined }, +}); +const routeDocsDefinition = routeDocsClientPlugin({ title: "Routes" }); + +mediaDefinition.id satisfies "media"; +routeDocsDefinition.id satisfies "routeDocs"; + +const stack = createClientStack({ + api: { baseURL: "https://app.example.com", basePath: "/api/data" }, + site: { baseURL: "https://app.example.com", basePath: "/pages" }, + queryClient, + plugins: { media: mediaDefinition, routeDocs: routeDocsDefinition }, +}); + +; +stack.context satisfies import("../../../types").ClientStackContext; + +function RouteIntrospectionProbe() { + useRegisteredRoutes(); + useRegisteredRoutes(stack); + useRegisteredRoutes(stack.context); + return null; +} +void RouteIntrospectionProbe; +; + +// @ts-expect-error Route Docs has no provider override activation block. +StackProvider({ stack, overrides: { routeDocs: {} } }); +// @ts-expect-error Kebab-case is a package and URL slug, not a programmatic ID. +StackProvider({ stack, overrides: { "route-docs": {} } }); + +createClientStack({ + api: { baseURL: "https://app.example.com", basePath: "/api/data" }, + site: { baseURL: "https://app.example.com", basePath: "/pages" }, + queryClient, + plugins: { + // @ts-expect-error The registration key must match Media's literal ID. + assets: mediaClientPlugin(), + }, +}); + +createClientStack({ + api: { baseURL: "https://app.example.com", basePath: "/api/data" }, + site: { baseURL: "https://app.example.com", basePath: "/pages" }, + queryClient, + plugins: { + // @ts-expect-error The registration key must match Route Docs' literal ID. + "route-docs": routeDocsClientPlugin(), + }, +}); + +mediaClientPlugin({ + // @ts-expect-error Shared API origins belong to createClientStack(). + apiBaseURL: "https://app.example.com", +}); +mediaClientPlugin({ + // @ts-expect-error Shared API paths belong to createClientStack(). + apiBasePath: "/api/data", +}); +mediaClientPlugin({ + // @ts-expect-error Shared site origins belong to createClientStack(). + siteBaseURL: "https://app.example.com", +}); +mediaClientPlugin({ + // @ts-expect-error Shared site paths belong to createClientStack(). + siteBasePath: "/pages", +}); +mediaClientPlugin({ + // @ts-expect-error The query client belongs to createClientStack(). + queryClient, +}); +mediaClientPlugin({ + // @ts-expect-error Request headers belong to createClientStack().api. + headers: new Headers(), +}); +mediaClientPlugin({ + // @ts-expect-error Public browser headers belong to endpoints.media.api. + browserHeaders: { "x-public": "value" }, +}); +mediaClientPlugin({ + // @ts-expect-error Browser credentials belong to endpoints.media.api. + credentials: "include", +}); +mediaClientPlugin({ + hooks: { + // @ts-expect-error The canonical loader error callback is onErrorLoad. + onLoadError: () => undefined, + }, +}); + +routeDocsClientPlugin({ + // @ts-expect-error Route Docs inherits its query client from the stack. + queryClient, +}); +routeDocsClientPlugin({ + // @ts-expect-error Route Docs inherits its site path from the stack. + siteBasePath: "/pages", +}); +routeDocsClientPlugin({ + // @ts-expect-error Route Docs has no API transport configuration. + apiBaseURL: "https://app.example.com", +}); + +const mediaConfig: MediaClientConfig = { uploadMode: "vercel-blob" }; +const routeDocsConfig: RouteDocsClientConfig = { description: "Routes" }; +const overrides: MediaPluginOverrides = { imageCompression: false }; +void mediaConfig; +void routeDocsConfig; +void overrides; + +const removedOverrides: MediaPluginOverrides = { + // @ts-expect-error Query clients are resolved by the registered stack. + queryClient, +}; +void removedOverrides; diff --git a/packages/stack/src/plugins/media/__tests__/identity-partition.test.tsx b/packages/stack/src/plugins/media/__tests__/identity-partition.test.tsx index 4781c0da3..c0f0ec1b3 100644 --- a/packages/stack/src/plugins/media/__tests__/identity-partition.test.tsx +++ b/packages/stack/src/plugins/media/__tests__/identity-partition.test.tsx @@ -14,6 +14,11 @@ import { } from "../client/hooks/use-media"; import { mediaResources } from "../query-keys"; +const MEDIA_ENDPOINT = { + baseURL: "http://test.local", + basePath: "/api", +}; + ( globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean } ).IS_REACT_ACT_ENVIRONMENT = true; @@ -108,12 +113,20 @@ describe("Media protected query identity partition", () => { await waitFor(() => filename === "user-b.jpg"); expect( queryClient.getQueryData( - MEDIA_QUERY_KEYS.assetsList({ limit: 40 }, { id: "user-a" }), + MEDIA_QUERY_KEYS.assetsList( + { limit: 40 }, + { id: "user-a" }, + MEDIA_ENDPOINT, + ), ), ).toBeDefined(); expect( queryClient.getQueryData( - MEDIA_QUERY_KEYS.assetsList({ limit: 40 }, { id: "user-b" }), + MEDIA_QUERY_KEYS.assetsList( + { limit: 40 }, + { id: "user-b" }, + MEDIA_ENDPOINT, + ), ), ).toBeDefined(); }); @@ -229,7 +242,13 @@ describe("Media protected query identity partition", () => { expect(fetchMock).toHaveBeenCalledTimes(4); const userA = queryClient.getQueryData<{ pages: Array<{ items: Array<{ filename: string }> }>; - }>(MEDIA_QUERY_KEYS.assetsList({ limit: 40 }, { id: "user-a" })); + }>( + MEDIA_QUERY_KEYS.assetsList( + { limit: 40 }, + { id: "user-a" }, + MEDIA_ENDPOINT, + ), + ); expect(userA?.pages[0]?.items[0]?.filename).toBe("user-a.jpg"); }); @@ -290,10 +309,22 @@ describe("Media protected query identity partition", () => { expect(fetchMock).toHaveBeenCalledTimes(4); const userA = queryClient.getQueryData<{ pages: Array<{ items: Array<{ filename: string }> }>; - }>(MEDIA_QUERY_KEYS.assetsList({ limit: 40 }, { id: "user-a" })); + }>( + MEDIA_QUERY_KEYS.assetsList( + { limit: 40 }, + { id: "user-a" }, + MEDIA_ENDPOINT, + ), + ); const userB = queryClient.getQueryData<{ pages: Array<{ items: Array<{ filename: string }> }>; - }>(MEDIA_QUERY_KEYS.assetsList({ limit: 40 }, { id: "user-b" })); + }>( + MEDIA_QUERY_KEYS.assetsList( + { limit: 40 }, + { id: "user-b" }, + MEDIA_ENDPOINT, + ), + ); expect(userA?.pages[0]?.items[0]?.filename).toBe("user-a.jpg"); expect(userB?.pages[0]?.items[0]?.filename).toBe("user-b-updated.jpg"); }); @@ -358,15 +389,103 @@ describe("Media protected query identity partition", () => { expect(fetchMock).toHaveBeenCalledTimes(3); expect( queryClient.getQueryData( - MEDIA_QUERY_KEYS.assetsList({ limit: 40 }, { id: "user-a" }), + MEDIA_QUERY_KEYS.assetsList( + { limit: 40 }, + { id: "user-a" }, + MEDIA_ENDPOINT, + ), ), ).toBeUndefined(); const userB = queryClient.getQueryData<{ pages: Array<{ items: Array<{ filename: string }> }>; - }>(MEDIA_QUERY_KEYS.assetsList({ limit: 40 }, { id: "user-b" })); + }>( + MEDIA_QUERY_KEYS.assetsList( + { limit: 40 }, + { id: "user-b" }, + MEDIA_ENDPOINT, + ), + ); expect(userB?.pages[0]?.items[0]?.filename).toBe("user-b.jpg"); }); + it("never refetches a mutation-start endpoint after an in-flight endpoint switch", async () => { + let resolveDelete: ((response: Response) => void) | undefined; + const deleteResponse = new Promise((resolve) => { + resolveDelete = resolve; + }); + fetchMock + .mockResolvedValueOnce(responseFor("endpoint-a")) + .mockReturnValueOnce(deleteResponse) + .mockResolvedValueOnce(responseFor("endpoint-b")); + const auth = createIdentityTestAuth(vi.fn(() => null)); + const identity = { id: "user-a" }; + const endpointA = { + baseURL: "http://media-a.local", + basePath: "/api-a", + }; + const endpointB = { + baseURL: "http://media-b.local", + basePath: "/api-b", + }; + let filename: string | undefined; + let deleteAsset: + | ReturnType["mutateAsync"] + | undefined; + + function Probe() { + filename = useAssets({ limit: 40 }).data?.pages[0]?.items[0]?.filename; + deleteAsset = useDeleteAsset().mutateAsync; + return null; + } + + async function render(endpoint: typeof endpointA) { + await act(async () => { + root.render( + + + + + , + ); + }); + } + + await render(endpointA); + await waitFor(() => filename === "endpoint-a.jpg"); + let deletion: Promise<{ success: boolean }> | undefined; + await act(async () => { + deletion = deleteAsset?.("asset-endpoint-a"); + await Promise.resolve(); + }); + await waitFor(() => fetchMock.mock.calls.length === 2); + await render(endpointB); + await waitFor(() => filename === "endpoint-b.jpg"); + resolveDelete?.( + new Response(JSON.stringify({ success: true }), { + status: 200, + headers: { "content-type": "application/json" }, + }), + ); + await act(async () => deletion); + + expect(fetchMock).toHaveBeenCalledTimes(3); + expect( + queryClient.getQueryData( + MEDIA_QUERY_KEYS.assetsList({ limit: 40 }, identity, endpointA), + ), + ).toBeUndefined(); + const endpointBData = queryClient.getQueryData<{ + pages: Array<{ items: Array<{ filename: string }> }>; + }>(MEDIA_QUERY_KEYS.assetsList({ limit: 40 }, identity, endpointB)); + expect(endpointBData?.pages[0]?.items[0]?.filename).toBe("endpoint-b.jpg"); + }); + it("ignores an identity from an abandoned concurrent render", async () => { fetchMock .mockResolvedValueOnce(responseFor("user-a")) @@ -420,12 +539,20 @@ describe("Media protected query identity partition", () => { expect( queryClient.getQueryData( - MEDIA_QUERY_KEYS.assetsList({ limit: 40 }, { id: "user-a" }), + MEDIA_QUERY_KEYS.assetsList( + { limit: 40 }, + { id: "user-a" }, + MEDIA_ENDPOINT, + ), ), ).toBeUndefined(); expect( queryClient.getQueryData( - MEDIA_QUERY_KEYS.assetsList({ limit: 40 }, { id: "user-b" }), + MEDIA_QUERY_KEYS.assetsList( + { limit: 40 }, + { id: "user-b" }, + MEDIA_ENDPOINT, + ), ), ).toBeUndefined(); expect(fetchMock).toHaveBeenCalledTimes(2); @@ -492,12 +619,22 @@ describe("Media protected query identity partition", () => { expect(fetchMock).toHaveBeenCalledTimes(3); expect( queryClient.getQueryData( - MEDIA_QUERY_KEYS.assetsList({ limit: 40 }, { id: "user-a" }), + MEDIA_QUERY_KEYS.assetsList( + { limit: 40 }, + { id: "user-a" }, + MEDIA_ENDPOINT, + ), ), ).toBeUndefined(); const userB = queryClient.getQueryData<{ pages: Array<{ items: Array<{ filename: string }> }>; - }>(MEDIA_QUERY_KEYS.assetsList({ limit: 40 }, { id: "user-b" })); + }>( + MEDIA_QUERY_KEYS.assetsList( + { limit: 40 }, + { id: "user-b" }, + MEDIA_ENDPOINT, + ), + ); expect(userB?.pages[0]?.items[0]?.filename).toBe("user-b.jpg"); }); @@ -574,7 +711,13 @@ describe("Media protected query identity partition", () => { const current = queryClient.getQueryData<{ pages: Array<{ items: Array<{ filename: string }> }>; - }>(MEDIA_QUERY_KEYS.assetsList({ limit: 40 }, { id: "user-a" })); + }>( + MEDIA_QUERY_KEYS.assetsList( + { limit: 40 }, + { id: "user-a" }, + MEDIA_ENDPOINT, + ), + ); expect(current?.pages[0]?.items[0]?.filename).toBe("user-a-updated.jpg"); expect(fetchMock).toHaveBeenCalledTimes(4); }); diff --git a/packages/stack/src/plugins/media/__tests__/query-key-defs.test.ts b/packages/stack/src/plugins/media/__tests__/query-key-defs.test.ts index 6176ceac4..27e8825e5 100644 --- a/packages/stack/src/plugins/media/__tests__/query-key-defs.test.ts +++ b/packages/stack/src/plugins/media/__tests__/query-key-defs.test.ts @@ -9,6 +9,11 @@ import { assetListDiscriminator, } from "../api/query-key-defs"; +const ENDPOINT = { + baseURL: "https://media.example.com", + basePath: "/api/data", +}; + const createTestAdapter = (): Adapter => { const db = defineDb({}).use(mediaSchema); return createMemoryAdapter(db)({}); @@ -47,24 +52,33 @@ describe("media asset list query keys", () => { expect(assetListDiscriminator()).not.toEqual( assetListDiscriminator({ limit: 20, offset: 0 }), ); - expect(MEDIA_QUERY_KEYS.assetsList()).not.toEqual( - MEDIA_QUERY_KEYS.assetsList({ limit: 20, offset: 0 }), + expect( + MEDIA_QUERY_KEYS.assetsList(undefined, undefined, ENDPOINT), + ).not.toEqual( + MEDIA_QUERY_KEYS.assetsList( + { limit: 20, offset: 0 }, + undefined, + ENDPOINT, + ), ); }); it("partitions protected asset and folder queries by identity", () => { const first = { id: "user-a", role: "member" }; const second = { id: "user-b", role: "member" }; - expect(MEDIA_QUERY_KEYS.assetsList({ limit: 40 }, first)).not.toEqual( - MEDIA_QUERY_KEYS.assetsList({ limit: 40 }, second), - ); - expect(MEDIA_QUERY_KEYS.foldersList(null, first)).not.toEqual( - MEDIA_QUERY_KEYS.foldersList(null, "pending:2"), + expect( + MEDIA_QUERY_KEYS.assetsList({ limit: 40 }, first, ENDPOINT), + ).not.toEqual(MEDIA_QUERY_KEYS.assetsList({ limit: 40 }, second, ENDPOINT)); + expect(MEDIA_QUERY_KEYS.foldersList(null, first, ENDPOINT)).not.toEqual( + MEDIA_QUERY_KEYS.foldersList(null, "pending:2", ENDPOINT), ); - expect(MEDIA_QUERY_KEYS.assetsList({ limit: 40 })).toEqual([ + expect( + MEDIA_QUERY_KEYS.assetsList({ limit: 40 }, undefined, ENDPOINT), + ).toEqual([ "mediaAssets", "list", assetListDiscriminator({ limit: 40 }), + { endpoint: ENDPOINT }, ]); }); }); diff --git a/packages/stack/src/plugins/media/api/adapters/vercel-blob.ts b/packages/stack/src/plugins/media/api/adapters/vercel-blob.ts index a5a5bba2c..455a7ea24 100644 --- a/packages/stack/src/plugins/media/api/adapters/vercel-blob.ts +++ b/packages/stack/src/plugins/media/api/adapters/vercel-blob.ts @@ -102,8 +102,9 @@ type DelFn = (url: string, options?: { token?: string }) => Promise; * with `handleUpload` exported from `@vercel/blob/client`). * * Upload flow: - * 1. Client calls `POST /media/upload/vercel-blob` to obtain a client token. - * 2. Client uses `@vercel/blob/client`'s `upload()` to upload directly to Vercel. + * 1. The client authenticates with the Media endpoint to obtain a scoped token. + * 2. The client uses that token with `@vercel/blob/client`'s `put()` to upload + * directly to Vercel Blob. * 3. After upload, client calls `POST /media/assets` to save metadata to the DB. * * @example diff --git a/packages/stack/src/plugins/media/api/index.ts b/packages/stack/src/plugins/media/api/index.ts index f491d193c..94ae3ade4 100644 --- a/packages/stack/src/plugins/media/api/index.ts +++ b/packages/stack/src/plugins/media/api/index.ts @@ -29,6 +29,7 @@ export { MEDIA_QUERY_KEYS, assetListDiscriminator, folderListDiscriminator, + type MediaEndpointPartition, type MediaIdentityPartition, } from "./query-key-defs"; diff --git a/packages/stack/src/plugins/media/api/plugin.ts b/packages/stack/src/plugins/media/api/plugin.ts index 164bc4ea5..b89a902a8 100644 --- a/packages/stack/src/plugins/media/api/plugin.ts +++ b/packages/stack/src/plugins/media/api/plugin.ts @@ -25,6 +25,8 @@ import { import { MEDIA_QUERY_KEYS } from "./query-key-defs"; import { serializeAsset, serializeFolder } from "./serializers"; import type { StorageAdapter } from "./storage-adapter"; +import { resolveMediaAsset } from "../asset-url"; +import type { MediaEndpointPartition } from "./query-key-defs"; export { AssetIdOperationInputSchema, @@ -68,7 +70,11 @@ export interface MediaBackendConfig { export type MediaRouteKey = "library"; interface MediaPrefetchForRoute { - (key: "library", queryClient: QueryClient): Promise; + ( + key: "library", + queryClient: QueryClient, + endpoint: MediaEndpointPartition, + ): Promise; } /** @@ -77,25 +83,28 @@ interface MediaPrefetchForRoute { * deployment boundary when the Media library is not public. */ function createMediaPrefetchForRoute(adapter: Adapter): MediaPrefetchForRoute { - return async (_key, queryClient) => { + return async (_key, queryClient, endpoint) => { const [assets, folders] = await Promise.all([ listAssets(adapter, { limit: 40 }), listFolders(adapter), ]); - queryClient.setQueryData(MEDIA_QUERY_KEYS.assetsList({ limit: 40 }), { - pages: [ - { - ...assets, - items: assets.items.map((asset) => { - const { tenantId: _tenantId, ...safe } = serializeAsset(asset); - return safe; - }), - }, - ], - pageParams: [0], - }); queryClient.setQueryData( - MEDIA_QUERY_KEYS.foldersList(), + MEDIA_QUERY_KEYS.assetsList({ limit: 40 }, undefined, endpoint), + { + pages: [ + { + ...assets, + items: assets.items.map((asset) => { + const { tenantId: _tenantId, ...safe } = serializeAsset(asset); + return resolveMediaAsset(safe, endpoint.baseURL); + }), + }, + ], + pageParams: [0], + }, + ); + queryClient.setQueryData( + MEDIA_QUERY_KEYS.foldersList(undefined, undefined, endpoint), folders.map((folder) => { const { tenantId: _tenantId, ...safe } = serializeFolder(folder); return safe; diff --git a/packages/stack/src/plugins/media/api/query-key-defs.ts b/packages/stack/src/plugins/media/api/query-key-defs.ts index 597cd043e..874fc3b43 100644 --- a/packages/stack/src/plugins/media/api/query-key-defs.ts +++ b/packages/stack/src/plugins/media/api/query-key-defs.ts @@ -13,6 +13,43 @@ export type MediaIdentityPartition = | `pending:${number}` | `error:${number}`; +/** Resolved Media service location that partitions shared React Query caches. */ +export interface MediaEndpointPartition { + /** Absolute origin of the resolved Media API. */ + baseURL: string; + /** Path where the resolved Media API is mounted. */ + basePath: string; +} + +/** Stable structured endpoint discriminator used in Media query keys. */ +export function mediaEndpointDiscriminator( + endpoint: MediaEndpointPartition, +): MediaEndpointPartition { + return { + baseURL: endpoint.baseURL, + basePath: endpoint.basePath, + }; +} + +/** Identity and endpoint scope shared by Media browser, SSR, and SSG keys. */ +export interface MediaQueryScope { + /** Optional identity partition for protected Media data. */ + identity?: MediaIdentityPartition; + /** Browser-safe resolved Media service location. */ + endpoint: MediaEndpointPartition; +} + +/** Creates the browser-safe scope cell appended to Media list query keys. */ +export function mediaQueryScope( + identityPartition: MediaIdentityPartition | undefined, + endpoint: MediaEndpointPartition, +): MediaQueryScope { + return { + ...(identityPartition === undefined ? {} : { identity: identityPartition }), + endpoint: mediaEndpointDiscriminator(endpoint), + }; +} + /** * Discriminator for the asset list cache key. */ @@ -48,30 +85,28 @@ export function folderListDiscriminator( /** Full query key builders — use these with `queryClient.setQueryData()`. */ export const MEDIA_QUERY_KEYS = { assetsList: ( - params?: AssetListParams, - identityPartition?: MediaIdentityPartition, + params: AssetListParams | undefined, + identityPartition: MediaIdentityPartition | undefined, + endpoint: MediaEndpointPartition, ) => - identityPartition === undefined - ? (["mediaAssets", "list", assetListDiscriminator(params)] as const) - : ([ - "mediaAssets", - "list", - assetListDiscriminator(params), - { identity: identityPartition }, - ] as const), + [ + "mediaAssets", + "list", + assetListDiscriminator(params), + mediaQueryScope(identityPartition, endpoint), + ] as const, assetDetail: (id: string) => ["mediaAssets", "detail", id] as const, foldersList: ( - parentId?: string | null, - identityPartition?: MediaIdentityPartition, + parentId: string | null | undefined, + identityPartition: MediaIdentityPartition | undefined, + endpoint: MediaEndpointPartition, ) => - identityPartition === undefined - ? (["mediaFolders", "list", folderListDiscriminator(parentId)] as const) - : ([ - "mediaFolders", - "list", - folderListDiscriminator(parentId), - { identity: identityPartition }, - ] as const), + [ + "mediaFolders", + "list", + folderListDiscriminator(parentId), + mediaQueryScope(identityPartition, endpoint), + ] as const, }; diff --git a/packages/stack/src/plugins/media/api/storage-adapter.ts b/packages/stack/src/plugins/media/api/storage-adapter.ts index dfea70a3a..14cdcba96 100644 --- a/packages/stack/src/plugins/media/api/storage-adapter.ts +++ b/packages/stack/src/plugins/media/api/storage-adapter.ts @@ -151,9 +151,8 @@ export interface VercelBlobStorageAdapter { body: VercelBlobUploadCompletedBody, ): Promise; /** - * Process a raw request from `@vercel/blob/client`'s `upload()` or from - * Vercel Blob's upload-completion webhook. Returns a JSON-serialisable object - * that should be sent back as the response body. + * Process a client-token request or Vercel Blob's upload-completion webhook. + * Returns a JSON-serialisable object that should be sent as the response body. */ handleRequest( request: Request, diff --git a/packages/stack/src/plugins/media/asset-url.ts b/packages/stack/src/plugins/media/asset-url.ts new file mode 100644 index 000000000..86041867c --- /dev/null +++ b/packages/stack/src/plugins/media/asset-url.ts @@ -0,0 +1,14 @@ +import type { SerializedAsset } from "./types"; + +export function resolveMediaAsset( + asset: SerializedAsset, + apiBaseURL: string | undefined, +): SerializedAsset { + if (!apiBaseURL) return asset; + try { + const url = new URL(asset.url, apiBaseURL).href; + return url === asset.url ? asset : { ...asset, url }; + } catch { + return asset; + } +} diff --git a/packages/stack/src/plugins/media/client/components/media-picker/index.tsx b/packages/stack/src/plugins/media/client/components/media-picker/index.tsx index 3ef84a237..097e3a355 100644 --- a/packages/stack/src/plugins/media/client/components/media-picker/index.tsx +++ b/packages/stack/src/plugins/media/client/components/media-picker/index.tsx @@ -18,14 +18,10 @@ import { FolderTree } from "./folder-tree"; import { BrowseTab } from "./browse-tab"; import { UploadTab } from "./upload-tab"; import { UrlTab } from "./url-tab"; -import { - PermissionAccess, - usePluginOverrides, - useStack, - useTranslate, -} from "@btst/stack/context"; +import { PermissionAccess, useStack, useTranslate } from "@btst/stack/context"; import { mediaPermissions } from "../../../permissions"; -import type { MediaPluginOverrides } from "../../overrides"; +import type { MediaProviderConfig } from "../../overrides"; +import { MEDIA_PLUGIN_ID } from "../../constants"; import { MediaFinalizePermissionCheck, MediaUploadPermissionCheck, @@ -94,8 +90,11 @@ export function MediaPicker({ accept, }: MediaPickerProps) { const t = useTranslate(); - const { uploadMode = "direct" } = - usePluginOverrides("media"); + const { plugins } = useStack(); + const providerConfig = plugins?.[MEDIA_PLUGIN_ID]?.config as + | MediaProviderConfig + | undefined; + const uploadMode = providerConfig?.uploadMode ?? "direct"; const [open, setOpen] = useState(false); const [selectedFolder, setSelectedFolder] = useState(null); const [selectedAssets, setSelectedAssets] = useState([]); diff --git a/packages/stack/src/plugins/media/client/components/pages/library-page.internal.tsx b/packages/stack/src/plugins/media/client/components/pages/library-page.internal.tsx index 4d9c2ff10..47ed471fb 100644 --- a/packages/stack/src/plugins/media/client/components/pages/library-page.internal.tsx +++ b/packages/stack/src/plugins/media/client/components/pages/library-page.internal.tsx @@ -7,10 +7,15 @@ import { cn } from "@workspace/ui/lib/utils"; import { useNotify, usePluginOverrides, + useStack, useTranslate, } from "@btst/stack/context"; import { useListState, type ListStateSchema } from "@btst/stack/client/hooks"; -import type { MediaPluginOverrides } from "../../overrides"; +import type { + MediaPluginOverrides, + MediaProviderConfig, +} from "../../overrides"; +import { MEDIA_PLUGIN_ID } from "../../constants"; import { useRouteLifecycle } from "@workspace/ui/hooks/use-route-lifecycle"; import { BrowseTab } from "../media-picker/browse-tab"; import { FolderTree } from "../media-picker/folder-tree"; @@ -22,7 +27,12 @@ export function LibraryPage() { const overrides = usePluginOverrides< MediaPluginOverrides, Partial - >("media", {}); + >(MEDIA_PLUGIN_ID, {}); + const { plugins } = useStack(); + const providerConfig = plugins?.[MEDIA_PLUGIN_ID]?.config as + | MediaProviderConfig + | undefined; + const uploadMode = providerConfig?.uploadMode ?? "direct"; useRouteLifecycle({ routeName: "library", context: { @@ -103,7 +113,7 @@ export function LibraryPage() { return ( {({ can: canUpload, isPending, error }) => { diff --git a/packages/stack/src/plugins/media/client/components/pages/library-page.tsx b/packages/stack/src/plugins/media/client/components/pages/library-page.tsx index e942e94f8..3ba871ed2 100644 --- a/packages/stack/src/plugins/media/client/components/pages/library-page.tsx +++ b/packages/stack/src/plugins/media/client/components/pages/library-page.tsx @@ -4,6 +4,7 @@ import type { FallbackProps } from "react-error-boundary"; import { usePluginOverrides } from "@btst/stack/context"; import { ComposedRoute } from "@btst/stack/client/components"; import type { MediaPluginOverrides } from "../../overrides"; +import { MEDIA_PLUGIN_ID } from "../../constants"; import { Loader2 } from "lucide-react"; import { mediaPermissions } from "../../../permissions"; @@ -29,7 +30,7 @@ function LibraryError({ error }: FallbackProps) { } export function LibraryPageComponent() { - usePluginOverrides("media"); + usePluginOverrides(MEDIA_PLUGIN_ID); return ( ({ baseURL, basePath }), [baseURL, basePath]); +} + +function useMediaApiBaseURL() { + return useMediaEndpointPartition().baseURL; +} + function useIdentityPartition() { const { identity, isPending, error } = useIdentity(); const sourceGeneration = useIdentitySourceGeneration(); @@ -40,11 +58,18 @@ function sameIdentityPartition( queryKey: readonly unknown[], partition: ReturnType, ) { - const marker = queryKey[3] as { identity?: unknown } | undefined; - if (partition === undefined) return marker === undefined; - return ( - marker !== undefined && hashKey([marker.identity]) === hashKey([partition]) - ); + const scope = queryKey[3] as MediaQueryScope | undefined; + const hasIdentity = scope !== undefined && Object.hasOwn(scope, "identity"); + if (partition === undefined) return !hasIdentity; + return hasIdentity && hashKey([scope.identity]) === hashKey([partition]); +} + +function sameEndpointPartition( + queryKey: readonly unknown[], + partition: MediaEndpointPartition, +) { + const scope = queryKey[3] as MediaQueryScope | undefined; + return hashKey([scope?.endpoint]) === hashKey([partition]); } function samePartition( @@ -54,14 +79,35 @@ function samePartition( return hashKey([left]) === hashKey([right]); } +interface CurrentMediaListScope { + identity: ReturnType; + endpoint: MediaEndpointPartition; +} + +function sameListScope( + left: CurrentMediaListScope, + right: CurrentMediaListScope, +) { + return ( + samePartition(left.identity, right.identity) && + hashKey([left.endpoint]) === hashKey([right.endpoint]) + ); +} + function useCurrentMediaListRefresh(resource: "mediaAssets" | "mediaFolders") { - const queryClient = useQueryClient(); + const { queryClient: stackQueryClient } = useStack(); + const queryClient = useQueryClient(stackQueryClient); + const endpointPartition = useMediaEndpointPartition(); const identityPartition = useIdentityPartition(); - const latestPartition = useRef(identityPartition); + const currentScope = useMemo( + () => ({ identity: identityPartition, endpoint: endpointPartition }), + [identityPartition, endpointPartition], + ); + const latestScope = useRef(currentScope); const mounted = useRef(true); useLayoutEffect(() => { - latestPartition.current = identityPartition; - }, [identityPartition]); + latestScope.current = currentScope; + }, [currentScope]); useLayoutEffect(() => { mounted.current = true; return () => { @@ -69,22 +115,26 @@ function useCurrentMediaListRefresh(resource: "mediaAssets" | "mediaFolders") { }; }, []); - const removePartition = (partition: typeof identityPartition) => + const removeScope = (scope: CurrentMediaListScope) => queryClient.removeQueries({ queryKey: [resource, "list"], - predicate: ({ queryKey }) => sameIdentityPartition(queryKey, partition), + predicate: ({ queryKey }) => + sameIdentityPartition(queryKey, scope.identity) && + sameEndpointPartition(queryKey, scope.endpoint), }); - const refreshAfterSuccess = async (startedAs: typeof identityPartition) => { - const current = latestPartition.current; - if (!mounted.current || !samePartition(startedAs, current)) { + const refreshAfterSuccess = async (startedAs: CurrentMediaListScope) => { + const current = latestScope.current; + if (!mounted.current || !sameListScope(startedAs, current)) { // Never refetch an initiating account with a newer account's session. - // Dropping it also prevents stale mutation-era data from resurfacing. - removePartition(startedAs); + // The endpoint is part of that ownership boundary for shared caches. + removeScope(startedAs); return; } await queryClient.invalidateQueries({ queryKey: [resource, "list"], - predicate: ({ queryKey }) => sameIdentityPartition(queryKey, current), + predicate: ({ queryKey }) => + sameIdentityPartition(queryKey, current.identity) && + sameEndpointPartition(queryKey, current.endpoint), // The current tab can temporarily unmount its list. Refresh only this // identity's inactive variants; never refetch a previous account's key // with the current request headers. @@ -95,8 +145,8 @@ function useCurrentMediaListRefresh(resource: "mediaAssets" | "mediaFolders") { return { // Event handlers retain the hook result from the committed render. Reading // that closure prevents an abandoned concurrent render from changing which - // identity owns a newly-started mutation. - currentPartition: () => identityPartition, + // identity and endpoint own a newly-started mutation. + currentScope: () => currentScope, refreshAfterSuccess, }; } @@ -104,38 +154,66 @@ function useCurrentMediaListRefresh(resource: "mediaAssets" | "mediaFolders") { function withCurrentListRefresh( mutation: UseMutationResult, listRefresh: ReturnType, + mapResult: (data: TData) => TData = (data) => data, + data: TData | undefined = mutation.data, ): UseMutationResult { const mutateAsync: typeof mutation.mutateAsync = async ( variables, options, ) => { - const startedAs = listRefresh.currentPartition(); - const result = await mutation.mutateAsync(variables, options); + const startedAs = listRefresh.currentScope(); + const result = await mutation.mutateAsync(variables, { + ...options, + onSuccess: options?.onSuccess + ? (data, ...args) => options.onSuccess?.(mapResult(data), ...args) + : undefined, + onSettled: options?.onSettled + ? (data, ...args) => + options.onSettled?.( + data === undefined ? undefined : mapResult(data), + ...args, + ) + : undefined, + }); await listRefresh.refreshAfterSuccess(startedAs); - return result; + return mapResult(result); }; const mutate: typeof mutation.mutate = (variables, options) => { // Each invocation owns an awaited promise, so a later mutation cannot // detach the successful call's required cache refresh. void mutateAsync(variables, options).catch(() => {}); }; - return { ...mutation, mutate, mutateAsync }; + return { + ...mutation, + data, + mutate, + mutateAsync, + } as UseMutationResult; } /** Infinite-scroll list of assets, optionally filtered by folder, MIME type, or search. */ export function useAssets(params: AssetListParams = {}) { const identityPartition = useIdentityPartition(); - return media.mediaAssets.list.useInfinite([params, identityPartition], { - enabled: !isUnresolvedIdentityPartition(identityPartition), - }); + const endpointPartition = useMediaEndpointPartition(); + const result = media.mediaAssets.list.useInfinite( + [params, identityPartition, endpointPartition], + { + enabled: !isUnresolvedIdentityPartition(identityPartition), + }, + ); + return result; } /** Pass `null` for root-level folders and `undefined` for all folders. */ export function useFolders(parentId?: string | null) { const identityPartition = useIdentityPartition(); - return media.mediaFolders.list.use([parentId, identityPartition], { - enabled: !isUnresolvedIdentityPartition(identityPartition), - }); + const endpointPartition = useMediaEndpointPartition(); + return media.mediaFolders.list.use( + [parentId, identityPartition, endpointPartition], + { + enabled: !isUnresolvedIdentityPartition(identityPartition), + }, + ); } /** @@ -143,46 +221,70 @@ export function useFolders(parentId?: string | null) { * This remains custom because the resource factory models JSON requests only. */ export function useUploadAsset() { - const { - headers, - uploadMode = "direct", - imageCompression, - } = usePluginOverrides("media"); - const { api } = useStack(); - // Resource-generated asset queries use the nearest QueryClientProvider. + const { imageCompression } = + usePluginOverrides(MEDIA_PLUGIN_ID); + const { api, plugins, queryClient: stackQueryClient } = useStack(); + const queryClient = useQueryClient(stackQueryClient); + const pluginRuntime = plugins?.[MEDIA_PLUGIN_ID]; + const pluginApi = pluginRuntime?.api ?? api; + const providerConfig = pluginRuntime?.config as + | MediaProviderConfig + | undefined; + // Resource-generated asset queries use the stack-owned QueryClient. // Keep the custom upload transport on that same cache. const listRefresh = useCurrentMediaListRefresh("mediaAssets"); - return useMutation({ - onMutate: () => listRefresh.currentPartition(), - mutationFn: async ({ - file, - folderId, - }: { - file: File; - folderId?: string; - }): Promise => - uploadAsset( - { - apiBaseURL: api?.baseURL ?? "", - apiBasePath: api?.basePath ?? "", - headers, - uploadMode, - imageCompression, - }, - { file, folderId }, - ), - onSuccess: async (_asset, _variables, startedAs) => { - await listRefresh.refreshAfterSuccess(startedAs); + return useMutation( + { + onMutate: () => listRefresh.currentScope(), + mutationFn: async ({ + file, + folderId, + }: { + file: File; + folderId?: string; + }): Promise => + uploadAsset( + createMediaUploadConfig( + { + api: { + baseURL: pluginApi?.baseURL ?? "", + basePath: pluginApi?.basePath ?? "", + browserHeaders: pluginRuntime?.api.browserHeaders, + credentials: pluginRuntime?.api.credentials, + }, + config: providerConfig, + }, + { imageCompression }, + ), + { file, folderId }, + ), + onSuccess: async (_asset, _variables, startedAs) => { + await listRefresh.refreshAfterSuccess(startedAs); + }, }, - }); + queryClient, + ); } /** Register an already-hosted asset URL. */ export function useRegisterAsset() { const mutation = media.mediaAssets.create.use(); const listRefresh = useCurrentMediaListRefresh("mediaAssets"); - return withCurrentListRefresh(mutation, listRefresh); + const apiBaseURL = useMediaApiBaseURL(); + const data = useMemo( + () => + mutation.data === undefined + ? undefined + : resolveMediaAsset(mutation.data, apiBaseURL), + [mutation.data, apiBaseURL], + ); + return withCurrentListRefresh( + mutation, + listRefresh, + (asset) => resolveMediaAsset(asset, apiBaseURL), + data, + ); } /** Delete an asset by ID. */ @@ -229,6 +331,7 @@ export function useRegisterAssetForm( options: UseRegisterAssetFormOptions = {}, ): ResourceFormResult { const t = useTranslate(); + const apiBaseURL = useMediaApiBaseURL(); const listRefresh = useCurrentMediaListRefresh("mediaAssets"); const form = media.mediaAssets.useForm< RegisterAssetFormValues, @@ -249,9 +352,10 @@ export function useRegisterAssetForm( return { ...form, submit: async (values) => { - const startedAs = listRefresh.currentPartition(); - const asset = await form.submit(values); - if (asset === undefined) return undefined; + const startedAs = listRefresh.currentScope(); + const submittedAsset = await form.submit(values); + if (submittedAsset === undefined) return undefined; + const asset = resolveMediaAsset(submittedAsset, apiBaseURL); await listRefresh.refreshAfterSuccess(startedAs); await options.onSuccess?.(asset); return asset; @@ -293,7 +397,7 @@ export function useCreateFolderForm( return { ...form, submit: async (values) => { - const startedAs = listRefresh.currentPartition(); + const startedAs = listRefresh.currentScope(); const folder = await form.submit(values); if (folder === undefined) return undefined; await listRefresh.refreshAfterSuccess(startedAs); diff --git a/packages/stack/src/plugins/media/client/index.ts b/packages/stack/src/plugins/media/client/index.ts index 438cabcc4..d6ba8e5ff 100644 --- a/packages/stack/src/plugins/media/client/index.ts +++ b/packages/stack/src/plugins/media/client/index.ts @@ -1,4 +1,17 @@ export { mediaClientPlugin } from "./plugin"; -export type { MediaPluginOverrides, MediaUploadMode } from "./overrides"; -export { uploadAsset } from "./upload"; -export type { MediaUploadClientConfig, UploadAssetInput } from "./upload"; +export type { + MediaClientConfig, + MediaClientHooks, + MediaLoaderContext, +} from "./plugin"; +export type { + MediaPluginOverrides, + MediaProviderConfig, + MediaUploadMode, +} from "./overrides"; +export { createMediaUploadConfig, uploadAsset } from "./upload"; +export type { + MediaUploadClientConfig, + MediaUploadProviderRuntime, + UploadAssetInput, +} from "./upload"; diff --git a/packages/stack/src/plugins/media/client/overrides.ts b/packages/stack/src/plugins/media/client/overrides.ts index 2bfe58a44..989647825 100644 --- a/packages/stack/src/plugins/media/client/overrides.ts +++ b/packages/stack/src/plugins/media/client/overrides.ts @@ -1,4 +1,3 @@ -import type { QueryClient } from "@tanstack/react-query"; import type { ImageCompressionOptions } from "./utils/image-compression"; /** @@ -9,6 +8,12 @@ import type { ImageCompressionOptions } from "./utils/image-compression"; */ export type MediaUploadMode = "direct" | "s3" | "vercel-blob"; +/** Browser-safe Media factory values carried by the resolved client stack. */ +export interface MediaProviderConfig { + /** Upload transport matching the server-side storage adapter. */ + readonly uploadMode?: MediaUploadMode; +} + /** * Overridable components and functions for the Media plugin. * @@ -16,22 +21,6 @@ export type MediaUploadMode = "direct" | "s3" | "vercel-blob"; * via the StackProvider overrides. */ export interface MediaPluginOverrides { - /** - * React Query client — used by the MediaPicker to cache and fetch assets. - */ - queryClient: QueryClient; - - /** - * Upload mode — must match the storageAdapter configured in mediaBackendPlugin. - * @default "direct" - */ - uploadMode?: MediaUploadMode; - - /** - * Optional headers to pass with API requests (e.g., for SSR auth). - */ - headers?: HeadersInit; - /** * Client-side image compression applied before upload via the Canvas API. * diff --git a/packages/stack/src/plugins/media/client/plugin.tsx b/packages/stack/src/plugins/media/client/plugin.tsx index 61ba6e61a..21b1456d5 100644 --- a/packages/stack/src/plugins/media/client/plugin.tsx +++ b/packages/stack/src/plugins/media/client/plugin.tsx @@ -1,22 +1,42 @@ import { - defineClientPlugin, createApiClient, + createSanitizedSSRLoaderError, + defineClientPlugin, isConnectionError, + type ResolvedClientPluginRuntime, } from "@btst/stack/plugins/client"; +import { normalizePath } from "@btst/stack/client"; import { defineRoute, defineRoutes } from "@btst/yar"; -import type { ComponentType } from "react"; import type { QueryClient } from "@tanstack/react-query"; -import { LibraryPageComponent } from "./components/pages/library-page"; -import { createMediaQueryKeys } from "../query-keys"; +import { lazy, type ComponentType } from "react"; import type { MediaApiRouter } from "../api/plugin"; import type { MediaIdentityPartition } from "../api/query-key-defs"; - +import { createMediaQueryKeys } from "../query-keys"; +import { MEDIA_PLUGIN_ID } from "./constants"; +import type { + MediaPluginOverrides, + MediaProviderConfig, + MediaUploadMode, +} from "./overrides"; + +const LibraryPageComponent = lazy(() => + import("./components/pages/library-page").then((module) => ({ + default: module.LibraryPageComponent, + })), +); + +/** Resolved request context supplied to Media SSR loader hooks. */ export interface MediaLoaderContext { + /** Normalized Media route path being loaded. */ path: string; + /** Whether the hook is running during server-side rendering. */ isSSR: boolean; + /** Resolved absolute origin for the Media backend. */ apiBaseURL: string; + /** Resolved path where the Media backend is mounted. */ apiBasePath: string; - headers?: HeadersInit; + /** Request-scoped server headers used by the Media SSR loader. */ + headers?: Headers; } export interface MediaClientHooks { @@ -26,159 +46,165 @@ export interface MediaClientHooks { /** Called after the media library data is fetched during SSR. */ afterLoadLibrary?: (context: MediaLoaderContext) => Promise | void; - /** Called when an error occurs during the SSR loader. */ - onLoadError?: ( + /** + * Reports an SSR loader failure once. Callback failures are contained and + * cannot make the loader reject. + */ + onErrorLoad?: ( error: Error, context: MediaLoaderContext, ) => Promise | void; } +/** + * Media-specific client configuration. Shared API, site, query-client, and + * request-header values are inherited from `createClientStack()`. + */ export interface MediaClientConfig { - /** Base URL for API calls (e.g., "http://localhost:3000") */ - apiBaseURL: string; - /** Path where the API is mounted (e.g., "/api/data") */ - apiBasePath: string; - /** Base URL of your site for SEO meta tags */ - siteBaseURL: string; - /** Path where pages are mounted (e.g., "/pages") */ - siteBasePath: string; - /** React Query client — used by the SSR loader to prefetch data */ - queryClient: QueryClient; - /** Optional headers forwarded with SSR API requests (e.g. auth cookies) */ - headers?: HeadersInit; + /** Upload transport matching the storage adapter configured on the backend. */ + uploadMode?: MediaUploadMode; /** Identity snapshot used to align protected SSR prefetch and browser keys. */ identityPartition?: MediaIdentityPartition; - /** Optional lifecycle hooks for the media client plugin */ + /** Optional lifecycle hooks for the media client plugin. */ hooks?: MediaClientHooks; - /** - * Optional page component overrides. - * Replace any plugin page with a custom React component. - * The built-in component is used as the fallback when not provided. - */ + /** Optional replacement for the media library page. */ pageComponents?: { - /** Replaces the media library page */ library?: ComponentType; }; } -/** - * Media client plugin. - * Registers the /media library route. - * - * Configure overrides in StackProvider: - * ```tsx - * - * ``` - * - * @example - * ```ts - * import { mediaClientPlugin } from "@btst/stack/plugins/media/client" - * - * const clientPlugins = [ - * mediaClientPlugin({ apiBaseURL, apiBasePath, siteBaseURL, siteBasePath, queryClient }), - * // ...other plugins - * ] - * ``` - */ -export const mediaClientPlugin = (config: MediaClientConfig) => - defineClientPlugin({ - name: "media", +interface ResolvedMediaClientConfig extends MediaClientConfig { + apiBaseURL: string; + apiBasePath: string; + siteBaseURL: string; + siteBasePath: string; + queryClient: QueryClient; + headers?: Headers; + credentials?: RequestCredentials; +} - routes: () => - defineRoutes( - { - library: defineRoute("/media", { - page: LibraryPageComponent, - loader: createMediaLibraryLoader(config), - meta: createMediaLibraryMeta(config), - }), - }, - { pages: config.pageComponents }, - ), +function resolveMediaClientConfig( + config: MediaClientConfig, + runtime: ResolvedClientPluginRuntime, +): ResolvedMediaClientConfig { + return { + uploadMode: config.uploadMode, + identityPartition: config.identityPartition, + hooks: config.hooks, + pageComponents: config.pageComponents, + apiBaseURL: runtime.api.baseURL, + apiBasePath: runtime.api.basePath, + siteBaseURL: runtime.site.baseURL, + siteBasePath: runtime.site.basePath, + queryClient: runtime.queryClient, + ...(runtime.api.headers ? { headers: runtime.api.headers } : {}), + ...(runtime.api.credentials + ? { credentials: runtime.api.credentials } + : {}), + }; +} + +function createMediaApiClient(config: ResolvedMediaClientConfig) { + return createApiClient({ + baseURL: config.apiBaseURL, + basePath: config.apiBasePath, + headers: config.headers, + credentials: config.credentials, }); +} -function createMediaLibraryLoader(config: MediaClientConfig) { - return async () => { - if (typeof window === "undefined") { - const { - queryClient, - apiBasePath, - apiBaseURL, - hooks, - headers, - identityPartition, - } = config; - - const context: MediaLoaderContext = { - path: "/media", - isSSR: true, - apiBaseURL, - apiBasePath, - headers, - }; - - try { - if (hooks?.beforeLoadLibrary) { - await hooks.beforeLoadLibrary(context); - } - - const client = createApiClient({ - baseURL: apiBaseURL, - basePath: apiBasePath, - }); - const queries = createMediaQueryKeys(client, headers); +function createLoadErrorReporter( + hooks: MediaClientHooks | undefined, + context: MediaLoaderContext, +) { + let reported = false; + return async (error: unknown) => { + if (reported || !hooks?.onErrorLoad) return; + reported = true; + try { + await hooks.onErrorLoad( + error instanceof Error ? error : new Error(String(error)), + context, + ); + } catch { + // Reporting hooks cannot make an SSR loader reject or report twice. + } + }; +} - // Prefetch initial asset grid (infinite query — root folder, default limit) - const assetQuery = queries.mediaAssets.list( - { limit: 40 }, - identityPartition, - ); - const folderQuery = queries.mediaFolders.list( - undefined, - identityPartition, +function createMediaLibraryLoader(config: ResolvedMediaClientConfig) { + return async () => { + if (typeof window !== "undefined") return; + + const { + queryClient, + apiBasePath, + apiBaseURL, + hooks, + headers, + identityPartition, + } = config; + const context: MediaLoaderContext = { + path: "/media", + isSSR: true, + apiBaseURL, + apiBasePath, + headers, + }; + const reportError = createLoadErrorReporter(hooks, context); + const queries = createMediaQueryKeys(createMediaApiClient(config)); + const endpointPartition = { baseURL: apiBaseURL, basePath: apiBasePath }; + const assetQuery = queries.mediaAssets.list( + { limit: 40 }, + identityPartition, + endpointPartition, + ); + const folderQuery = queries.mediaFolders.list( + undefined, + identityPartition, + endpointPartition, + ); + + try { + await hooks?.beforeLoadLibrary?.(context); + await queryClient.prefetchInfiniteQuery({ + ...assetQuery, + initialPageParam: 0, + }); + await queryClient.prefetchQuery(folderQuery); + await hooks?.afterLoadLibrary?.(context); + + const queryError = + queryClient.getQueryState(assetQuery.queryKey)?.error ?? + queryClient.getQueryState(folderQuery.queryKey)?.error; + if (queryError) await reportError(queryError); + } catch (error) { + if (isConnectionError(error)) { + console.warn( + "[btst/media] route.loader() failed — no server running at build time. " + + "For an explicitly public static library, use the explicit " + + "stack.raw.media.prefetchForRoute() server helper instead.", ); + } else { + const sanitizedError = createSanitizedSSRLoaderError(); await queryClient.prefetchInfiniteQuery({ - ...assetQuery, + queryKey: assetQuery.queryKey, + queryFn: () => { + throw sanitizedError; + }, initialPageParam: 0, + retry: false, }); - - // Prefetch the complete scoped folder tree in the exact browser key. - await queryClient.prefetchQuery(folderQuery); - - if (hooks?.afterLoadLibrary) { - await hooks.afterLoadLibrary(context); - } - - const queryError = - queryClient.getQueryState(assetQuery.queryKey)?.error ?? - queryClient.getQueryState(folderQuery.queryKey)?.error; - if (queryError && hooks?.onLoadError) { - const error = - queryError instanceof Error - ? queryError - : new Error(String(queryError)); - await hooks.onLoadError(error, context); - } - } catch (error) { - if (isConnectionError(error)) { - console.warn( - "[btst/media] route.loader() failed — no server running at build time. " + - "For an explicitly public static library, use the explicit " + - "stack.raw.media.prefetchForRoute() server helper instead.", - ); - } - if (hooks?.onLoadError) { - await hooks.onLoadError(error as Error, context); - } } + await reportError(error); } }; } -function createMediaLibraryMeta(config: MediaClientConfig) { +function createMediaLibraryMeta(config: ResolvedMediaClientConfig) { return () => { - const { siteBaseURL, siteBasePath } = config; - const fullUrl = `${siteBaseURL}${siteBasePath}/media`; + const sitePath = normalizePath([config.siteBasePath, "/media"].join("/")); + const fullUrl = `${config.siteBaseURL}${sitePath}`; const title = "Media Library"; return [ @@ -186,19 +212,39 @@ function createMediaLibraryMeta(config: MediaClientConfig) { { name: "title", content: title }, { name: "description", content: "Manage your media assets" }, { name: "robots", content: "noindex, nofollow" }, - - // Open Graph { property: "og:type", content: "website" }, { property: "og:title", content: title }, - { - property: "og:description", - content: "Manage your media assets", - }, + { property: "og:description", content: "Manage your media assets" }, { property: "og:url", content: fullUrl }, - - // Twitter { name: "twitter:card", content: "summary" }, { name: "twitter:title", content: title }, ]; }; } + +function createResolvedMediaPlugin(config: ResolvedMediaClientConfig) { + return { + routes: () => + defineRoutes( + { + library: defineRoute("/media", { + page: LibraryPageComponent, + loader: createMediaLibraryLoader(config), + meta: createMediaLibraryMeta(config), + }), + }, + { pages: config.pageComponents }, + ), + }; +} + +/** Registers the Media library against the enclosing resolved client runtime. */ +export const mediaClientPlugin = (config: MediaClientConfig = {}) => + defineClientPlugin()({ + id: MEDIA_PLUGIN_ID, + providerConfig: { + ...(config.uploadMode ? { uploadMode: config.uploadMode } : {}), + } satisfies MediaProviderConfig, + resolve: (runtime) => + createResolvedMediaPlugin(resolveMediaClientConfig(config, runtime)), + }); diff --git a/packages/stack/src/plugins/media/client/upload.ts b/packages/stack/src/plugins/media/client/upload.ts index 070491a8b..c2bede784 100644 --- a/packages/stack/src/plugins/media/client/upload.ts +++ b/packages/stack/src/plugins/media/client/upload.ts @@ -1,18 +1,50 @@ "use client"; +import { normalizePath } from "@btst/stack/client"; import type { SerializedAsset } from "../types"; -import type { MediaUploadMode } from "./overrides"; +import type { MediaProviderConfig, MediaUploadMode } from "./overrides"; +import { resolveMediaAsset } from "../asset-url"; import { compressImage } from "./utils/image-compression"; import type { ImageCompressionOptions } from "./utils/image-compression"; +/** Transport and preprocessing options for an imperative Media upload. */ export interface MediaUploadClientConfig { + /** Resolved Media API base URL. */ apiBaseURL: string; + /** Mount path of the resolved Media API endpoint. */ apiBasePath: string; + /** Browser-safe headers sent with Media API requests. Never include secrets. */ headers?: HeadersInit; + /** + * Fetch credentials mode applied only to Media API requests. + * Configure this explicitly when a cross-origin Media endpoint accepts + * browser credentials. It is not forwarded to storage upload URLs and does + * not make server-only headers safe to expose. + */ + credentials?: RequestCredentials; + /** Upload transport matching the backend Media storage adapter. Defaults to `"direct"`. */ uploadMode?: MediaUploadMode; + /** Client-side image compression options, or `false` to skip compression. */ imageCompression?: ImageCompressionOptions | false; } +/** Browser-safe Media runtime exposed as `stack.provider.plugins.media`. */ +export interface MediaUploadProviderRuntime { + /** Resolved browser transport for the Media API. */ + readonly api: { + /** Resolved Media API base URL. */ + readonly baseURL: string; + /** Media API mount path. */ + readonly basePath: string; + /** Explicitly public headers safe to expose to browser code. */ + readonly browserHeaders?: HeadersInit; + /** Explicit browser Fetch credentials behavior. */ + readonly credentials?: RequestCredentials; + }; + /** Browser-safe Media factory configuration. */ + readonly config?: MediaProviderConfig; +} + export interface UploadAssetInput { file: File; folderId?: string; @@ -24,6 +56,31 @@ const DEFAULT_IMAGE_COMPRESSION = { quality: 0.85, } as const; +/** + * Bind imperative uploads to the Media endpoint resolved by `createClientStack`. + */ +export function createMediaUploadConfig( + runtime: MediaUploadProviderRuntime, + overrides: Pick = {}, +): MediaUploadClientConfig { + return { + apiBaseURL: runtime.api.baseURL, + apiBasePath: runtime.api.basePath, + headers: runtime.api.browserHeaders, + credentials: runtime.api.credentials, + uploadMode: runtime.config?.uploadMode ?? "direct", + ...overrides, + }; +} + +function createMediaApiURL( + apiBaseURL: string, + apiBasePath: string, + path: string, +): string { + return `${apiBaseURL}${normalizePath([apiBasePath, path].join("/"))}`; +} + /** * Upload an asset using the media plugin's configured storage mode. * @@ -39,6 +96,7 @@ export async function uploadAsset( apiBaseURL, apiBasePath, headers, + credentials, uploadMode = "direct", imageCompression, } = config; @@ -52,7 +110,6 @@ export async function uploadAsset( imageCompression ?? DEFAULT_IMAGE_COMPRESSION, ); - const base = `${apiBaseURL}${apiBasePath}`; const headersObj = new Headers(headers as HeadersInit | undefined); if (uploadMode === "direct") { @@ -60,32 +117,40 @@ export async function uploadAsset( formData.append("file", processedFile); if (folderId) formData.append("folderId", folderId); - const res = await fetch(`${base}/media/upload`, { - method: "POST", - headers: headersObj, - body: formData, - }); + const res = await fetch( + createMediaApiURL(apiBaseURL, apiBasePath, "/media/upload"), + { + method: "POST", + headers: headersObj, + credentials, + body: formData, + }, + ); if (!res.ok) { const err = await res.json().catch(() => ({ message: res.statusText })); throw new Error(err.message ?? "Upload failed"); } - return res.json(); + return resolveMediaAsset((await res.json()) as SerializedAsset, apiBaseURL); } if (uploadMode === "s3") { - const tokenRes = await fetch(`${base}/media/upload/token`, { - method: "POST", - headers: { - ...Object.fromEntries(headersObj.entries()), - "Content-Type": "application/json", + const tokenRes = await fetch( + createMediaApiURL(apiBaseURL, apiBasePath, "/media/upload/token"), + { + method: "POST", + headers: { + ...Object.fromEntries(headersObj.entries()), + "Content-Type": "application/json", + }, + credentials, + body: JSON.stringify({ + filename: processedFile.name, + mimeType: processedFile.type, + size: processedFile.size, + folderId, + }), }, - body: JSON.stringify({ - filename: processedFile.name, - mimeType: processedFile.type, - size: processedFile.size, - folderId, - }), - }); + ); if (!tokenRes.ok) { const err = await tokenRes .json() @@ -111,65 +176,116 @@ export async function uploadAsset( }); if (!putRes.ok) throw new Error("Failed to upload to S3"); - const assetRes = await fetch(`${base}/media/assets`, { - method: "POST", - headers: { - ...Object.fromEntries(headersObj.entries()), - "Content-Type": "application/json", + const assetRes = await fetch( + createMediaApiURL(apiBaseURL, apiBasePath, "/media/assets"), + { + method: "POST", + headers: { + ...Object.fromEntries(headersObj.entries()), + "Content-Type": "application/json", + }, + credentials, + body: JSON.stringify({ + filename: processedFile.name, + originalName: file.name, + mimeType: processedFile.type, + size: processedFile.size, + url: token.payload.publicUrl, + folderId, + }), }, - body: JSON.stringify({ - filename: processedFile.name, - originalName: file.name, - mimeType: processedFile.type, - size: processedFile.size, - url: token.payload.publicUrl, - folderId, - }), - }); + ); if (!assetRes.ok) { const err = await assetRes .json() .catch(() => ({ message: assetRes.statusText })); throw new Error(err.message ?? "Failed to register asset"); } - return assetRes.json(); + return resolveMediaAsset( + (await assetRes.json()) as SerializedAsset, + apiBaseURL, + ); } if (uploadMode === "vercel-blob") { - // Dynamic import keeps @vercel/blob/client optional. - const { upload } = await import("@vercel/blob/client"); - const blob = await upload(processedFile.name, processedFile, { - access: "public", - handleUploadUrl: `${base}/media/upload/vercel-blob`, - clientPayload: JSON.stringify({ - mimeType: processedFile.type, - size: processedFile.size, - ...(folderId ? { folderId } : {}), - }), + const handleUploadUrl = createMediaApiURL( + apiBaseURL, + apiBasePath, + "/media/upload/vercel-blob", + ); + const clientPayload = JSON.stringify({ + mimeType: processedFile.type, + size: processedFile.size, + ...(folderId ? { folderId } : {}), }); - - const assetRes = await fetch(`${base}/media/assets`, { + const tokenRes = await fetch(handleUploadUrl, { method: "POST", headers: { ...Object.fromEntries(headersObj.entries()), "Content-Type": "application/json", }, + credentials, body: JSON.stringify({ - filename: processedFile.name, - originalName: file.name, - mimeType: processedFile.type, - size: processedFile.size, - url: blob.url, - folderId, + type: "blob.generate-client-token", + payload: { + pathname: processedFile.name, + callbackUrl: handleUploadUrl, + clientPayload, + multipart: false, + }, }), }); + if (!tokenRes.ok) { + const err = await tokenRes + .json() + .catch(() => ({ message: tokenRes.statusText })); + throw new Error(err.message ?? "Failed to get Vercel Blob upload token"); + } + const { clientToken } = (await tokenRes.json()) as { + clientToken?: string; + }; + if (!clientToken) { + throw new Error("Failed to get Vercel Blob upload token"); + } + + // Dynamic import keeps @vercel/blob/client optional. The app-authenticated + // token exchange stays under our fetch control; the scoped token alone is + // then sent to Vercel's storage origin. + const { put } = await import("@vercel/blob/client"); + const blob = await put(processedFile.name, processedFile, { + access: "public", + token: clientToken, + }); + + const assetRes = await fetch( + createMediaApiURL(apiBaseURL, apiBasePath, "/media/assets"), + { + method: "POST", + headers: { + ...Object.fromEntries(headersObj.entries()), + "Content-Type": "application/json", + }, + credentials, + body: JSON.stringify({ + filename: processedFile.name, + originalName: file.name, + mimeType: processedFile.type, + size: processedFile.size, + url: blob.url, + folderId, + }), + }, + ); if (!assetRes.ok) { const err = await assetRes .json() .catch(() => ({ message: assetRes.statusText })); throw new Error(err.message ?? "Failed to register asset"); } - return assetRes.json(); + return resolveMediaAsset( + (await assetRes.json()) as SerializedAsset, + apiBaseURL, + ); } throw new Error(`Unknown uploadMode: ${uploadMode}`); diff --git a/packages/stack/src/plugins/media/query-keys.ts b/packages/stack/src/plugins/media/query-keys.ts index 5efdd307b..5629db3ee 100644 --- a/packages/stack/src/plugins/media/query-keys.ts +++ b/packages/stack/src/plugins/media/query-keys.ts @@ -8,8 +8,11 @@ import type { AssetListParams } from "./api/getters"; import { assetListDiscriminator, folderListDiscriminator, + mediaQueryScope, + type MediaEndpointPartition, type MediaIdentityPartition, } from "./api/query-key-defs"; +import { resolveMediaAsset } from "./asset-url"; import { ROOT_FOLDER_QUERY_VALUE } from "./schemas"; import type { SerializedAsset, SerializedFolder } from "./types"; @@ -56,37 +59,48 @@ export const mediaResources = { list: { path: "/media/assets", query: ( - params: AssetListParams = {}, - _identityPartition?: MediaIdentityPartition, + params: AssetListParams | undefined, + _identityPartition: MediaIdentityPartition | undefined, + _endpoint: MediaEndpointPartition, ) => ({ - folderId: params.folderId, - mimeType: params.mimeType, - query: normalizeSearch(params.query), - limit: params.limit ?? 20, + folderId: params?.folderId, + mimeType: params?.mimeType, + query: normalizeSearch(params?.query), + limit: params?.limit ?? 20, }), key: ( - params: AssetListParams = {}, - identityPartition?: MediaIdentityPartition, - ) => - identityPartition === undefined - ? [assetListDiscriminator(params)] - : [assetListDiscriminator(params), { identity: identityPartition }], + params: AssetListParams | undefined, + identityPartition: MediaIdentityPartition | undefined, + endpoint: MediaEndpointPartition, + ) => [ + assetListDiscriminator(params), + mediaQueryScope(identityPartition, endpoint), + ], select: ( data: any, - _params?: AssetListParams, - _identityPartition?: MediaIdentityPartition, - ) => - data as { + _params: AssetListParams | undefined, + _identityPartition: MediaIdentityPartition | undefined, + endpoint: MediaEndpointPartition, + ) => { + const result = data as { items: SerializedAsset[]; total: number; limit?: number; offset?: number; - }, + }; + return { + ...result, + items: result.items.map((asset) => + resolveMediaAsset(asset, endpoint.baseURL), + ), + }; + }, infinite: true, pageSize: ( - params: AssetListParams = {}, - _identityPartition?: MediaIdentityPartition, - ) => params.limit ?? 20, + params: AssetListParams | undefined, + _identityPartition: MediaIdentityPartition | undefined, + _endpoint: MediaEndpointPartition, + ) => params?.limit ?? 20, nextPageParam: paginatedNextPageParam, }, }, @@ -125,26 +139,26 @@ export const mediaResources = { list: { path: "/media/folders", query: ( - parentId?: string | null, - _identityPartition?: MediaIdentityPartition, + parentId: string | null | undefined, + _identityPartition: MediaIdentityPartition | undefined, + _endpoint: MediaEndpointPartition, ) => parentId === undefined ? {} : { parentId: parentId ?? ROOT_FOLDER_QUERY_VALUE }, key: ( - parentId?: string | null, - identityPartition?: MediaIdentityPartition, - ) => - identityPartition === undefined - ? [folderListDiscriminator(parentId)] - : [ - folderListDiscriminator(parentId), - { identity: identityPartition }, - ], + parentId: string | null | undefined, + identityPartition: MediaIdentityPartition | undefined, + endpoint: MediaEndpointPartition, + ) => [ + folderListDiscriminator(parentId), + mediaQueryScope(identityPartition, endpoint), + ], select: ( data: any, - _parentId?: string | null, - _identityPartition?: MediaIdentityPartition, + _parentId: string | null | undefined, + _identityPartition: MediaIdentityPartition | undefined, + _endpoint: MediaEndpointPartition, ) => data as SerializedFolder[], }, }, diff --git a/packages/stack/src/plugins/route-docs/client/components/pages/docs-page.tsx b/packages/stack/src/plugins/route-docs/client/components/pages/docs-page.tsx index ca515a795..64c4a4c9d 100644 --- a/packages/stack/src/plugins/route-docs/client/components/pages/docs-page.tsx +++ b/packages/stack/src/plugins/route-docs/client/components/pages/docs-page.tsx @@ -39,7 +39,8 @@ import { Menu, Navigation, } from "lucide-react"; -import { useSuspenseQuery } from "@tanstack/react-query"; +import { useSuspenseQuery, type QueryKey } from "@tanstack/react-query"; +import { joinBasePath, useStackOrNull } from "@btst/stack/context"; import type { RouteDocsSchema, DocumentedPlugin, @@ -47,7 +48,19 @@ import type { RouteParameter, PluginSitemapEntry, } from "../../../generator"; -import { ROUTE_DOCS_QUERY_KEY, generateSchema } from "../../plugin"; +import { generateSchema } from "../../schema"; + +function createSiteUrl( + siteBaseURL: string, + siteBasePath: string, + path: string, +): string { + return `${siteBaseURL}${joinBasePath(siteBasePath, path)}`; +} + +function openInNewTab(url: string): void { + window.open(url, "_blank", "noopener,noreferrer"); +} /** * Escapes regex special characters in a string, except for placeholders @@ -211,9 +224,11 @@ function ParametersSection({ */ function NavigationForm({ route, + siteBaseURL, siteBasePath, }: { route: DocumentedRoute; + siteBaseURL: string; siteBasePath: string; }) { const [paramValues, setParamValues] = useState>({}); @@ -238,7 +253,7 @@ function NavigationForm({ url = url.replace(`:${param.name}`, value); } } - return `${siteBasePath}${url}`; + return createSiteUrl(siteBaseURL, siteBasePath, url); }; const handleVisit = () => { @@ -249,7 +264,7 @@ function NavigationForm({ if (hasUnfilledParams) { return; } - window.open(url, "_blank"); + openInNewTab(url); }; const allParamsFilled = route.pathParams.every((p) => paramValues[p.name]); @@ -300,12 +315,13 @@ function NavigationForm({ ) : (
- {siteBasePath} - {route.path} + {createSiteUrl(siteBaseURL, siteBasePath, route.path)} @@ -447,7 +463,7 @@ function RouteSitemapSection({ variant="ghost" size="sm" className="h-7 w-7 p-0 shrink-0" - onClick={() => window.open(entry.url, "_blank")} + onClick={() => openInNewTab(entry.url)} > @@ -475,11 +491,13 @@ function RouteDetail({ route, pluginName, sitemapEntries, + siteBaseURL, siteBasePath, }: { route: DocumentedRoute; pluginName: string; sitemapEntries: PluginSitemapEntry[]; + siteBaseURL: string; siteBasePath: string; }) { return ( @@ -525,7 +543,11 @@ function RouteDetail({
{/* Navigation form */} - + {/* Path parameters */} @@ -685,7 +707,7 @@ function RouteCard({ variant="ghost" size="sm" className="h-8 w-8 p-0 shrink-0" - onClick={() => window.open(staticUrl, "_blank")} + onClick={() => openInNewTab(staticUrl)} > @@ -812,7 +834,7 @@ function SitemapSection({ variant="ghost" size="sm" className="h-7 px-2" - onClick={() => window.open(entry.url, "_blank")} + onClick={() => openInNewTab(entry.url)} > @@ -840,7 +862,7 @@ function SitemapSection({ variant="ghost" size="sm" className="h-7 w-7 p-0 shrink-0" - onClick={() => window.open(entry.url, "_blank")} + onClick={() => openInNewTab(entry.url)} > @@ -879,9 +901,11 @@ function SitemapSection({ */ function AllRoutesSection({ schema, + siteBaseURL, siteBasePath, }: { schema: RouteDocsSchema; + siteBaseURL: string; siteBasePath: string; }) { const scrollToRoute = (pluginKey: string, routeKey: string) => { @@ -937,14 +961,16 @@ function AllRoutesSection({ pluginName: plugin.name, route, hasParams, - staticUrl: hasParams ? null : `${siteBasePath}${route.path}`, + staticUrl: hasParams + ? null + : createSiteUrl(siteBaseURL, siteBasePath, route.path), sitemapCount, }); } } return routes; - }, [schema, siteBasePath]); + }, [schema, siteBaseURL, siteBasePath]); if (allRoutes.length === 0) return null; @@ -1022,7 +1048,7 @@ function AllRoutesSection({ variant="ghost" size="sm" className="h-7 px-2" - onClick={() => window.open(staticUrl, "_blank")} + onClick={() => openInNewTab(staticUrl)} > @@ -1078,20 +1104,29 @@ function AllRoutesSection({ export interface DocsPageProps { title?: string; description?: string; + siteBaseURL?: string; siteBasePath?: string; + queryKey: QueryKey; } export function DocsPageComponent({ title = "Route Documentation", description = "Documentation for all client routes in your application", + siteBaseURL = "", siteBasePath = "/pages", + queryKey, }: DocsPageProps) { + const stack = useStackOrNull(); + const context = stack?.clientStackContext ?? null; // Read schema from React Query (prefetched by loader on server, or generated on client) - const { data: schema } = useSuspenseQuery({ - queryKey: ROUTE_DOCS_QUERY_KEY, - queryFn: generateSchema, - staleTime: Infinity, // Don't refetch - schema is static for this session - }); + const { data: schema } = useSuspenseQuery( + { + queryKey, + queryFn: () => generateSchema(context), + staleTime: Infinity, // Don't refetch - schema is static for this session + }, + stack?.queryClient, + ); const [mobileMenuOpen, setMobileMenuOpen] = useState(false); const totalRoutes = schema.plugins.reduce( @@ -1180,7 +1215,11 @@ export function DocsPageComponent({ {/* All routes overview table */} - + {/* All route details - one after another */} {schema.plugins.map((plugin) => ( @@ -1205,6 +1244,7 @@ export function DocsPageComponent({ route={route} pluginName={plugin.name} sitemapEntries={plugin.sitemapEntries} + siteBaseURL={siteBaseURL} siteBasePath={siteBasePath} /> diff --git a/packages/stack/src/plugins/route-docs/client/constants.ts b/packages/stack/src/plugins/route-docs/client/constants.ts new file mode 100644 index 000000000..a46f6fb09 --- /dev/null +++ b/packages/stack/src/plugins/route-docs/client/constants.ts @@ -0,0 +1,2 @@ +/** Stable programmatic ID for the client-only Route Docs plugin. */ +export const ROUTE_DOCS_PLUGIN_ID = "routeDocs" as const; diff --git a/packages/stack/src/plugins/route-docs/client/hooks.ts b/packages/stack/src/plugins/route-docs/client/hooks.ts index dbf974263..66c0b35c8 100644 --- a/packages/stack/src/plugins/route-docs/client/hooks.ts +++ b/packages/stack/src/plugins/route-docs/client/hooks.ts @@ -1,20 +1,30 @@ "use client"; -import { useEffect, useState } from "react"; +import { useMemo } from "react"; +import { useStackOrNull } from "@btst/stack/context"; +import type { ClientStack, ClientStackContext } from "../../../types"; import { getRegisteredRoutes, type RegisteredRoute } from "./plugin"; -/** - * React hook that returns all registered client route paths. - * Updates whenever the component mounts (after client hydration). - */ -export function useRegisteredRoutes(): RegisteredRoute[] { - const [routes, setRoutes] = useState(() => - getRegisteredRoutes(), - ); +type RegisteredRoutesSource = ClientStackContext | Pick; - useEffect(() => { - setRoutes(getRegisteredRoutes()); - }, []); +function resolveContext( + source: RegisteredRoutesSource | undefined, + providerContext: ClientStackContext | undefined, +): ClientStackContext | null { + if (!source) return providerContext ?? null; + return Object.hasOwn(source, "context") + ? (source as Pick).context + : (source as ClientStackContext); +} - return routes; +/** + * Returns registered client route paths for the enclosing provider or an + * explicitly supplied resolved stack/context. + */ +export function useRegisteredRoutes( + source?: RegisteredRoutesSource, +): RegisteredRoute[] { + const provider = useStackOrNull(); + const context = resolveContext(source, provider?.clientStackContext); + return useMemo(() => getRegisteredRoutes(context), [context]); } diff --git a/packages/stack/src/plugins/route-docs/client/index.ts b/packages/stack/src/plugins/route-docs/client/index.ts index fbfa7e2b1..aa87b503b 100644 --- a/packages/stack/src/plugins/route-docs/client/index.ts +++ b/packages/stack/src/plugins/route-docs/client/index.ts @@ -3,7 +3,6 @@ export { type RouteDocsClientConfig, ROUTE_DOCS_QUERY_KEY, generateSchema, - getStoredContext, getRegisteredRoutes, type RegisteredRoute, } from "./plugin"; diff --git a/packages/stack/src/plugins/route-docs/client/plugin.tsx b/packages/stack/src/plugins/route-docs/client/plugin.tsx index 00982d21d..87a218ef4 100644 --- a/packages/stack/src/plugins/route-docs/client/plugin.tsx +++ b/packages/stack/src/plugins/route-docs/client/plugin.tsx @@ -1,7 +1,11 @@ -import { lazy } from "react"; -import { defineClientPlugin } from "@btst/stack/plugins/client"; +import { lazy, type ComponentType } from "react"; +import { + defineClientPlugin, + type ResolvedClientPluginRuntime, +} from "@btst/stack/plugins/client"; +import { normalizePath } from "@btst/stack/client"; import { defineRoute } from "@btst/yar"; -import type { QueryClient } from "@tanstack/react-query"; +import { hashKey, type QueryClient } from "@tanstack/react-query"; import type { ClientStackContext } from "../../../types"; import { resolvePluginProgrammaticId } from "../../../plugin-registration"; import { @@ -10,137 +14,201 @@ import { type RouteDocsSchema, } from "../generator"; import type { DocsPageProps } from "./components/pages/docs-page"; +import { ROUTE_DOCS_PLUGIN_ID } from "./constants"; +import { createEmptySchema } from "./schema"; + +export { generateSchema } from "./schema"; -// Lazy load page components for code splitting const DocsPageComponent = lazy(() => - import("./components/pages/docs-page").then((m) => ({ - default: m.DocsPageComponent as React.ComponentType, + import("./components/pages/docs-page").then((module) => ({ + default: module.DocsPageComponent as ComponentType, })), ); const DocsPageSkeleton = lazy(() => - import("./components/loading/docs-skeleton").then((m) => ({ - default: m.DocsPageSkeleton, + import("./components/loading/docs-skeleton").then((module) => ({ + default: module.DocsPageSkeleton, })), ); -/** - * Query key for route docs schema - */ +/** Query-key prefix for Route Docs schema caches. */ export const ROUTE_DOCS_QUERY_KEY = ["route-docs", "schema"] as const; +const ROUTE_DOCS_KEY_RESOLUTION = ["route-docs", "schema-key"] as const; -/** - * Module-level storage for the client stack context - * This allows the schema to be generated on both server and client - */ -let moduleStoredContext: ClientStackContext | null = null; - -/** - * Get the stored client stack context - * Used by the docs page component to generate schema on client-side navigation - */ -export function getStoredContext(): ClientStackContext | null { - return moduleStoredContext; -} - -/** - * A registered route entry - */ export interface RegisteredRoute { - /** The route path pattern (e.g., "/blog/:slug") */ + /** The route path pattern (for example, `/blog/:slug`). */ path: string; - /** The plugin this route belongs to (e.g., "blog") */ + /** Canonical programmatic ID of the plugin that owns the route. */ plugin: string; - /** The route key within the plugin (e.g., "detail") */ + /** Route key within the plugin. */ key: string; } -/** - * Returns all registered client route paths from the stored ClientStackContext. - * The context is populated when `createStackClient` is called (i.e. on first render). - * Returns an empty array if called before the stack client has been initialised. - */ -export function getRegisteredRoutes(): RegisteredRoute[] { - if (!moduleStoredContext) return []; +/** Returns all registered routes except Route Docs' own introspection page. */ +export function getRegisteredRoutes( + context: ClientStackContext | null, +): RegisteredRoute[] { + if (!context) return []; const result: RegisteredRoute[] = []; - for (const [pluginKey, plugin] of Object.entries( - moduleStoredContext.plugins, - )) { + for (const [pluginKey, plugin] of Object.entries(context.plugins)) { const pluginId = resolvePluginProgrammaticId(plugin, pluginKey); - if (pluginId === "routeDocs" || pluginId === "route-docs") continue; + if (pluginId === ROUTE_DOCS_PLUGIN_ID) continue; try { - const routes = plugin.routes(moduleStoredContext); + const routes = plugin.routes(context); for (const [routeKey, route] of Object.entries(routes)) { - const path = (route as any)?.path; - if (path) { - result.push({ - path, - plugin: pluginId, - key: routeKey, - }); + const path = (route as { path?: unknown }).path; + if (typeof path === "string" && path.length > 0) { + result.push({ path, plugin: pluginId, key: routeKey }); } } } catch { - // silently skip plugins whose routes() throws during introspection + // Introspection deliberately skips definitions that cannot expose routes. } } return result; } -/** - * Generate the route docs schema from the stored context - * This can be called from both server and client - */ -export async function generateSchema(): Promise { - if (!moduleStoredContext) { - return { - plugins: [], - generatedAt: new Date().toISOString(), - allSitemapEntries: [], - }; +/** Route Docs-specific presentation configuration. */ +export interface RouteDocsClientConfig { + /** Title for the documentation page. */ + title?: string; + /** Description for the documentation page. */ + description?: string; +} + +interface ResolvedRouteDocsClientConfig extends RouteDocsClientConfig { + queryClient: QueryClient; + siteBaseURL: string; + siteBasePath: string; +} + +const resolvedSchemaKeysByContext = new WeakMap(); +const contextFallbackKeysByQueryClient = new WeakMap< + QueryClient, + { + nextKey: number; + keys: WeakMap; } +>(); + +function createRouteDocsBaseFingerprint( + config: ResolvedRouteDocsClientConfig, + context: ClientStackContext | null, +) { + // Framework entry factories may reconstruct the same stack between the loader + // and render. Hash schema inputs, never process-local object identities. + const schemaInputs = context + ? generateRouteDocsSchema(context, []).plugins.map( + ({ sitemapEntries: _sitemapEntries, ...plugin }) => plugin, + ) + : []; + const registrations = context + ? Object.entries(context.plugins) + .map(([key, plugin]) => ({ + key, + id: resolvePluginProgrammaticId(plugin, key), + })) + .sort((left, right) => left.key.localeCompare(right.key)) + : []; + return hashKey([ + { + basePath: context?.basePath ?? null, + siteBaseURL: config.siteBaseURL, + siteBasePath: config.siteBasePath, + registrations, + schemaInputs, + }, + ]); +} + +function createSchemaQueryKey(fingerprint: string) { + return [...ROUTE_DOCS_QUERY_KEY, fingerprint] as const; +} + +function createSchemaKeyResolutionQueryKey(baseFingerprint: string) { + return [...ROUTE_DOCS_KEY_RESOLUTION, baseFingerprint] as const; +} - try { - const sitemapEntries = await fetchAllSitemapEntries(moduleStoredContext); - return generateRouteDocsSchema(moduleStoredContext, sitemapEntries); - } catch (error) { - console.warn("Failed to generate route docs schema:", error); - // Return schema without sitemap entries on error - return generateRouteDocsSchema(moduleStoredContext, []); +function getContextFallbackKey( + queryClient: QueryClient, + context: ClientStackContext, +) { + let state = contextFallbackKeysByQueryClient.get(queryClient); + if (!state) { + state = { nextKey: 0, keys: new WeakMap() }; + contextFallbackKeysByQueryClient.set(queryClient, state); } + let key = state.keys.get(context); + if (key === undefined) { + key = state.nextKey++; + state.keys.set(context, key); + } + return key; } -/** - * Configuration for Route Docs client plugin - */ -export interface RouteDocsClientConfig { - /** React Query client for SSR prefetching */ - queryClient: QueryClient; - /** Title for the documentation page */ - title?: string; - /** Description for the documentation page */ - description?: string; - /** Site base path for constructing URLs (e.g., "/pages") */ - siteBasePath: string; +function resolveRouteDocsQueryKey( + config: ResolvedRouteDocsClientConfig, + context: ClientStackContext | null, +) { + const baseFingerprint = createRouteDocsBaseFingerprint(config, context); + // Loaders record every sitemap-complete key under this deterministic alias. + // A single dehydrated variant lets an equivalent reconstructed page find it; + // ambiguous variants fall back to isolated context keys below. + const aliases = config.queryClient.getQueryData( + createSchemaKeyResolutionQueryKey(baseFingerprint), + ); + const resolvedFingerprint = context + ? (resolvedSchemaKeysByContext.get(context) ?? + (aliases?.length === 1 ? aliases[0] : undefined)) + : undefined; + if (resolvedFingerprint) return createSchemaQueryKey(resolvedFingerprint); + if (context) { + return createSchemaQueryKey( + hashKey([ + { + baseFingerprint, + contextFallback: getContextFallbackKey(config.queryClient, context), + }, + ]), + ); + } + return createSchemaQueryKey(baseFingerprint); } -/** - * Create meta generator for the docs page - */ -function createDocsMeta(config: RouteDocsClientConfig) { +function resolveRouteDocsClientConfig( + config: RouteDocsClientConfig, + runtime: ResolvedClientPluginRuntime, +): ResolvedRouteDocsClientConfig { + return { + title: config.title, + description: config.description, + queryClient: runtime.queryClient, + siteBaseURL: runtime.site.baseURL, + siteBasePath: runtime.site.basePath, + }; +} + +function createDocsMeta(config: ResolvedRouteDocsClientConfig) { return () => { - const title = config.title || "Route Documentation"; + const title = config.title ?? "Route Documentation"; + const description = + config.description ?? + "Documentation for all client routes in your application"; + const sitePath = normalizePath( + [config.siteBasePath, "/route-docs"].join("/"), + ); return [ { title }, { name: "title", content: title }, + { name: "description", content: description }, { name: "robots", content: "noindex" }, + { property: "og:title", content: title }, + { property: "og:description", content: description }, + { property: "og:url", content: `${config.siteBaseURL}${sitePath}` }, ]; }; } -/** - * Default error component - no required props, matches other plugins - */ function DocsErrorComponent() { return (
@@ -156,75 +224,73 @@ function DocsErrorComponent() { ); } -/** - * Create loader for SSR prefetching of route docs schema - * This properly awaits all sitemap data before storing in React Query - */ -function createRouteDocsLoader(config: RouteDocsClientConfig) { +function createRouteDocsLoader( + config: ResolvedRouteDocsClientConfig, + context: ClientStackContext | null, +) { return async () => { - // Only run on server for SSR prefetching - // Client-side navigation uses the queryFn in the component - if (typeof window === "undefined" && moduleStoredContext) { - const { queryClient } = config; - - try { - // Await all sitemap entries from all plugins - const sitemapEntries = - await fetchAllSitemapEntries(moduleStoredContext); - - // Generate the complete schema with sitemap data - const schema = generateRouteDocsSchema( - moduleStoredContext, - sitemapEntries, - ); - - // Store in React Query for the component to read - queryClient.setQueryData(ROUTE_DOCS_QUERY_KEY, schema); - } catch (error) { - console.warn("Failed to load route docs schema:", error); - // Store empty schema on error - queryClient.setQueryData(ROUTE_DOCS_QUERY_KEY, { - plugins: [], - generatedAt: new Date().toISOString(), - allSitemapEntries: [], - }); - } + if (typeof window !== "undefined" || !context) return; + + try { + const sitemapEntries = await fetchAllSitemapEntries(context); + const schema = generateRouteDocsSchema(context, sitemapEntries); + const baseFingerprint = createRouteDocsBaseFingerprint(config, context); + const resolvedFingerprint = hashKey([ + { baseFingerprint, sitemapEntries }, + ]); + const queryKey = createSchemaQueryKey(resolvedFingerprint); + resolvedSchemaKeysByContext.set(context, resolvedFingerprint); + config.queryClient.setQueryData( + createSchemaKeyResolutionQueryKey(baseFingerprint), + (previous = []) => + previous.includes(resolvedFingerprint) + ? previous + : [...previous, resolvedFingerprint], + ); + config.queryClient.setQueryData(queryKey, schema); + } catch (error) { + console.warn("Failed to load route docs schema:", error); + const queryKey = resolveRouteDocsQueryKey(config, context); + config.queryClient.setQueryData( + queryKey, + createEmptySchema(), + ); } }; } -/** - * Route Docs client plugin - * Provides a route that displays documentation for all client routes - */ -export const routeDocsClientPlugin = (config: RouteDocsClientConfig) => { - return defineClientPlugin({ - name: "route-docs", - +function createResolvedRouteDocsPlugin(config: ResolvedRouteDocsClientConfig) { + return { routes: (context?: ClientStackContext) => { - // Store context at module level for client-side schema generation - moduleStoredContext = context || null; - + const resolvedContext = context ?? null; return { docs: defineRoute("/route-docs", { page: () => ( ), loading: DocsPageSkeleton, error: DocsErrorComponent, - loader: createRouteDocsLoader(config), + loader: createRouteDocsLoader(config, resolvedContext), meta: createDocsMeta(config), }), }; }, + sitemap: () => [], + }; +} - sitemap: async () => { - // Route docs page should NOT be in sitemap - return []; - }, +/** Registers the intentionally client-only Route Docs introspection plugin. */ +export const routeDocsClientPlugin = (config: RouteDocsClientConfig = {}) => + defineClientPlugin({ + id: ROUTE_DOCS_PLUGIN_ID, + resolve: (runtime) => + createResolvedRouteDocsPlugin( + resolveRouteDocsClientConfig(config, runtime), + ), }); -}; diff --git a/packages/stack/src/plugins/route-docs/client/schema.ts b/packages/stack/src/plugins/route-docs/client/schema.ts new file mode 100644 index 000000000..7dab2879b --- /dev/null +++ b/packages/stack/src/plugins/route-docs/client/schema.ts @@ -0,0 +1,31 @@ +import type { ClientStackContext } from "../../../types"; +import { + fetchAllSitemapEntries, + generateRouteDocsSchema, + type RouteDocsSchema, +} from "../generator"; + +export function createEmptySchema(): RouteDocsSchema { + return { + plugins: [], + generatedAt: new Date().toISOString(), + allSitemapEntries: [], + }; +} + +/** Generates the route schema from explicit resolved client definitions. */ +export async function generateSchema( + context: ClientStackContext | null, +): Promise { + if (!context) { + return createEmptySchema(); + } + + try { + const sitemapEntries = await fetchAllSitemapEntries(context); + return generateRouteDocsSchema(context, sitemapEntries); + } catch (error) { + console.warn("Failed to generate route docs schema:", error); + return generateRouteDocsSchema(context, []); + } +} diff --git a/packages/stack/src/plugins/route-docs/generator.ts b/packages/stack/src/plugins/route-docs/generator.ts index 94810af40..e1e31c176 100644 --- a/packages/stack/src/plugins/route-docs/generator.ts +++ b/packages/stack/src/plugins/route-docs/generator.ts @@ -1,5 +1,6 @@ import type { ClientStackContext, SitemapEntry } from "../../types"; import { resolvePluginProgrammaticId } from "../../plugin-registration"; +import { ROUTE_DOCS_PLUGIN_ID } from "./client/constants"; import type { Route } from "@btst/yar"; import * as z from "zod"; @@ -289,7 +290,7 @@ export async function fetchAllSitemapEntries( for (const [pluginKey, plugin] of Object.entries(context.plugins)) { const pluginId = resolvePluginProgrammaticId(plugin, pluginKey); // Skip route-docs plugin - if (pluginId === "routeDocs" || pluginId === "route-docs") { + if (pluginId === ROUTE_DOCS_PLUGIN_ID) { continue; } @@ -334,7 +335,7 @@ export function generateRouteDocsSchema( for (const [pluginKey, plugin] of Object.entries(context.plugins)) { const pluginId = resolvePluginProgrammaticId(plugin, pluginKey); // Skip the route-docs plugin itself - if (pluginId === "routeDocs" || pluginId === "route-docs") { + if (pluginId === ROUTE_DOCS_PLUGIN_ID) { continue; } diff --git a/packages/stack/src/react-router/page.tsx b/packages/stack/src/react-router/page.tsx index 215773901..8fec6842a 100644 --- a/packages/stack/src/react-router/page.tsx +++ b/packages/stack/src/react-router/page.tsx @@ -119,8 +119,7 @@ export function createReactRouterPage(options: CreateReactRouterPageOptions) { return (args.loaderData ?? args.data)?.meta; } - function Component() { - const data = useLoaderData(); + function PageContent({ path }: { path: string }) { const queryClient = useQueryClient(); // Memoized so PageComponent keeps a stable identity across re-renders: // getRoute() invokes the route handler, which produces new component @@ -128,8 +127,8 @@ export function createReactRouterPage(options: CreateReactRouterPageOptions) { // re-renders this component (e.g. a search-param update) would remount // the whole page subtree, losing component state such as open dialogs. const route = useMemo( - () => getStackClient(queryClient).router.getRoute(data.path), - [queryClient, data.path], + () => getStackClient(queryClient).router.getRoute(path), + [queryClient, path], ); const page = route?.PageComponent ? ( @@ -138,10 +137,15 @@ export function createReactRouterPage(options: CreateReactRouterPageOptions) { ) : (
Route not found
); + return wrapPage ? wrapPage(page) : page; + } + + function Component() { + const data = useLoaderData(); return ( - {wrapPage ? wrapPage(page) : page} + ); } diff --git a/packages/stack/src/types.ts b/packages/stack/src/types.ts index f8c99cb43..ecc55a5d2 100644 --- a/packages/stack/src/types.ts +++ b/packages/stack/src/types.ts @@ -801,6 +801,8 @@ type UnionToIntersection = ( export interface ClientStack< TRoutes extends Record = Record, > { + /** Resolved plugin definitions for intentional client-side introspection. */ + context: ClientStackContext; router: ReturnType>; generateSitemap: () => Promise; } diff --git a/scripts/codegen/files/nextjs/app/pages/client-layout.tsx b/scripts/codegen/files/nextjs/app/pages/client-layout.tsx index b61ec5420..ecc756d7f 100644 --- a/scripts/codegen/files/nextjs/app/pages/client-layout.tsx +++ b/scripts/codegen/files/nextjs/app/pages/client-layout.tsx @@ -15,8 +15,8 @@ import type { KanbanPluginOverrides } from "@btst/stack/plugins/kanban/client"; import type { CommentsPluginOverrides } from "@btst/stack/plugins/comments/client"; import { CommentThread } from "@btst/stack/plugins/comments/client/components"; import { + createMediaUploadConfig, uploadAsset, - type MediaPluginOverrides, } from "@btst/stack/plugins/media/client"; import { MediaPicker, @@ -26,14 +26,6 @@ import { resolveUser, searchUsers } from "@/lib/mock-users"; import { Button } from "@/components/ui/button"; import { clientAuth } from "@/lib/authorization.client"; -// Get base URL - works on both server and client -// On server: uses process.env.BASE_URL -// On client: uses NEXT_PUBLIC_BASE_URL or falls back to window.location.origin (which will be correct) -const getBaseURL = () => - typeof window !== "undefined" - ? process.env.NEXT_PUBLIC_BASE_URL || window.location.origin - : process.env.BASE_URL || "http://localhost:3000"; - type PluginOverrides = { blog: BlogPluginOverrides; aiChat: AiChatPluginOverrides; @@ -41,7 +33,6 @@ type PluginOverrides = { formBuilder: FormBuilderPluginOverrides; kanban: KanbanPluginOverrides; comments: CommentsPluginOverrides; - media: MediaPluginOverrides; }; export function BtstPagesClientLayout({ @@ -53,15 +44,10 @@ export function BtstPagesClientLayout({ }) { // fresh instance to avoid stale client cache overriding hydrated data const [queryClient] = useState(() => getOrCreateQueryClient()); - const baseURL = getBaseURL(); const stack = React.useMemo(() => getStackClient(queryClient), [queryClient]); const mediaClientConfig = React.useMemo( - () => ({ - apiBaseURL: baseURL, - apiBasePath: "/api/data", - uploadMode: "direct" as const, - }), - [baseURL], + () => createMediaUploadConfig(stack.provider.plugins.media), + [stack], ); const uploadImage = React.useCallback( @@ -146,10 +132,6 @@ export function BtstPagesClientLayout({ "blog-post": (slug) => `/pages/blog/${slug}`, }, }, - media: { - uploadMode: "direct", - queryClient, - }, } satisfies Partial as never } > diff --git a/scripts/codegen/files/nextjs/lib/stack-client.tsx b/scripts/codegen/files/nextjs/lib/stack-client.tsx index 420b7ef9f..f63a7b2b2 100644 --- a/scripts/codegen/files/nextjs/lib/stack-client.tsx +++ b/scripts/codegen/files/nextjs/lib/stack-client.tsx @@ -125,10 +125,8 @@ export const getStackClient = ( }, }), routeDocs: routeDocsClientPlugin({ - queryClient: queryClient, title: "Client Route Documentation", description: "Documentation for all client routes in this application", - siteBasePath: "/pages", }), kanban: kanbanClientPlugin({ identityPartition: options?.identity, @@ -158,12 +156,7 @@ export const getStackClient = ( : undefined, }), media: mediaClientPlugin({ - apiBaseURL: baseURL, - apiBasePath: "/api/data", - siteBaseURL: baseURL, - siteBasePath: "/pages", - queryClient: queryClient, - headers: options?.headers, + uploadMode: "direct", identityPartition: options?.identity, }), }, diff --git a/scripts/codegen/files/react-router/app/lib/stack-client.tsx b/scripts/codegen/files/react-router/app/lib/stack-client.tsx index 2b735a56d..2a460d9d8 100644 --- a/scripts/codegen/files/react-router/app/lib/stack-client.tsx +++ b/scripts/codegen/files/react-router/app/lib/stack-client.tsx @@ -97,10 +97,8 @@ export const getStackClient = ( formBuilder: formBuilderClientPlugin(), uiBuilder: uiBuilderClientPlugin(), routeDocs: routeDocsClientPlugin({ - queryClient: queryClient, title: "Client Route Documentation", description: "Documentation for all client routes in this application", - siteBasePath: "/pages", }), kanban: kanbanClientPlugin({ identityPartition: options?.identity, @@ -119,12 +117,7 @@ export const getStackClient = ( : undefined, }), media: mediaClientPlugin({ - apiBaseURL: baseURL, - apiBasePath: "/api/data", - siteBaseURL: baseURL, - siteBasePath: "/pages", - queryClient: queryClient, - headers: options?.headers, + uploadMode: "direct", identityPartition: options?.identity, }), }, diff --git a/scripts/codegen/files/react-router/app/routes/pages/_layout.tsx b/scripts/codegen/files/react-router/app/routes/pages/_layout.tsx index 74ab107e1..22340b27a 100644 --- a/scripts/codegen/files/react-router/app/routes/pages/_layout.tsx +++ b/scripts/codegen/files/react-router/app/routes/pages/_layout.tsx @@ -12,8 +12,8 @@ import type { KanbanPluginOverrides } from "@btst/stack/plugins/kanban/client"; import type { CommentsPluginOverrides } from "@btst/stack/plugins/comments/client"; import { CommentThread } from "@btst/stack/plugins/comments/client/components"; import { + createMediaUploadConfig, uploadAsset, - type MediaPluginOverrides, } from "@btst/stack/plugins/media/client"; import { MediaPicker, @@ -28,14 +28,6 @@ import { hydrationAuth } from "../../lib/authorization.server"; const layout = createReactRouterLayout({ auth: hydrationAuth }); export const loader = layout.loader; -// Get base URL function - works on both server and client -// On server: uses process.env.BASE_URL -// On client: uses import.meta.env.VITE_BASE_URL or falls back to window.location.origin -const getBaseURL = () => - typeof window !== "undefined" - ? import.meta.env.VITE_BASE_URL || window.location.origin - : process.env.BASE_URL || "http://localhost:3008"; - type PluginOverrides = { blog: BlogPluginOverrides; aiChat: AiChatPluginOverrides; @@ -43,21 +35,15 @@ type PluginOverrides = { formBuilder: FormBuilderPluginOverrides; kanban: KanbanPluginOverrides; comments: CommentsPluginOverrides; - media: MediaPluginOverrides; }; export default function Layout() { const { initialIdentity } = useLoaderData(); - const baseURL = getBaseURL(); const queryClient = useQueryClient(); const stack = useMemo(() => getStackClient(queryClient), [queryClient]); const mediaClientConfig = useMemo( - () => ({ - apiBaseURL: baseURL, - apiBasePath: "/api/data", - uploadMode: "direct" as const, - }), - [baseURL], + () => createMediaUploadConfig(stack.provider.plugins.media), + [stack], ); const uploadImage = useCallback( @@ -129,10 +115,6 @@ export default function Layout() { "blog-post": (slug) => `/pages/blog/${slug}`, }, }, - media: { - uploadMode: "direct", - queryClient, - }, } satisfies Partial as never } > diff --git a/scripts/codegen/files/tanstack/src/lib/stack-client.tsx b/scripts/codegen/files/tanstack/src/lib/stack-client.tsx index 330ec26a3..7fd0af281 100644 --- a/scripts/codegen/files/tanstack/src/lib/stack-client.tsx +++ b/scripts/codegen/files/tanstack/src/lib/stack-client.tsx @@ -97,10 +97,8 @@ export const getStackClient = ( formBuilder: formBuilderClientPlugin(), uiBuilder: uiBuilderClientPlugin(), routeDocs: routeDocsClientPlugin({ - queryClient: queryClient, title: "Client Route Documentation", description: "Documentation for all client routes in this application", - siteBasePath: "/pages", }), kanban: kanbanClientPlugin({ identityPartition: options?.identity, @@ -119,12 +117,7 @@ export const getStackClient = ( : undefined, }), media: mediaClientPlugin({ - apiBaseURL: baseURL, - apiBasePath: "/api/data", - siteBaseURL: baseURL, - siteBasePath: "/pages", - queryClient: queryClient, - headers: options?.headers, + uploadMode: "direct", identityPartition: options?.identity, }), }, diff --git a/scripts/codegen/files/tanstack/src/routes/pages/route.tsx b/scripts/codegen/files/tanstack/src/routes/pages/route.tsx index b2a6c7c3e..fa1b57a32 100644 --- a/scripts/codegen/files/tanstack/src/routes/pages/route.tsx +++ b/scripts/codegen/files/tanstack/src/routes/pages/route.tsx @@ -12,8 +12,8 @@ import type { KanbanPluginOverrides } from "@btst/stack/plugins/kanban/client"; import type { CommentsPluginOverrides } from "@btst/stack/plugins/comments/client"; import { CommentThread } from "@btst/stack/plugins/comments/client/components"; import { + createMediaUploadConfig, uploadAsset, - type MediaPluginOverrides, } from "@btst/stack/plugins/media/client"; import { MediaPicker, @@ -26,14 +26,6 @@ import { clientAuth } from "../../lib/authorization.ui"; import { getInitialIdentity } from "../../lib/authorization.identity"; import { getStackClient } from "../../lib/stack-client"; -// Get base URL function - works on both server and client -// On server: uses process.env.BASE_URL -// On client: uses import.meta.env.VITE_BASE_URL or falls back to window.location.origin -const getBaseURL = () => - typeof window !== "undefined" - ? import.meta.env.VITE_BASE_URL || window.location.origin - : process.env.BASE_URL || "http://localhost:3007"; - type PluginOverrides = { blog: BlogPluginOverrides; aiChat: AiChatPluginOverrides; @@ -41,7 +33,6 @@ type PluginOverrides = { formBuilder: FormBuilderPluginOverrides; kanban: KanbanPluginOverrides; comments: CommentsPluginOverrides; - media: MediaPluginOverrides; }; const layout = createTanStackLayout({ getInitialIdentity }); @@ -57,18 +48,13 @@ export const Route = createFileRoute("/pages")({ function Layout() { const routeContext = Route.useRouteContext(); const { initialIdentity } = Route.useLoaderData(); - const baseURL = getBaseURL(); const stack = useMemo( () => getStackClient(routeContext.queryClient), [routeContext.queryClient], ); const mediaClientConfig = useMemo( - () => ({ - apiBaseURL: baseURL, - apiBasePath: "/api/data", - uploadMode: "direct" as const, - }), - [baseURL], + () => createMediaUploadConfig(stack.provider.plugins.media), + [stack], ); const uploadImage = useCallback( @@ -145,10 +131,6 @@ function Layout() { "blog-post": (slug) => `/pages/blog/${slug}`, }, }, - media: { - uploadMode: "direct", - queryClient: routeContext.queryClient, - }, } satisfies Partial as never } >