Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,7 @@ fabric.properties
**/*.gen.tsx
**/*.gen.json
**/ui-types.gen/
**/ui-remote.gen/
.bos/generated/

# Module Federation DTS artifacts
Expand Down
64 changes: 40 additions & 24 deletions host/src/services/ui-compose.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,7 @@ export interface UiSource {

/**
* SSR availability: a production pin, or a local ui whose supervisor-computed
* session intent (BOS_DEV_SSR_INTENT, plan 078 phase 2) materializes the dev
* container — ambient shell exports never count. Loud when requested.
* session intent (BOS_DEV_SSR_INTENT, plan 078) materializes the container.
*/
export function isSsrAvailable(config: RuntimeConfig): boolean {
return ssrEntryResolvable(config);
Expand Down Expand Up @@ -450,7 +449,7 @@ const digestOfSources = Effect.fn("digestOfSources")(function* (composable: Comp
const clientPayloadOf = (
composable: ComposableSource[],
digest: string,
facadePreload?: string[],
facadePreload?: Record<string, string[]>,
): ComposePayload => ({
digest,
remotes: composable.flatMap(({ source, manifest }) => {
Expand All @@ -463,16 +462,20 @@ const clientPayloadOf = (
name: source.mfName,
entry: source.uiEntry,
...(source.browserManifestUrl ? { manifestUrl: source.browserManifestUrl } : {}),
...(source.key === CORE_UI_KEY && facadePreload?.length ? { preload: facadePreload } : {}),
...(facadePreload?.[source.key]?.length ? { preload: facadePreload[source.key] } : {}),
},
];
}),
manifests: composable.map(({ manifest }) => manifest),
});

/** The core's components-expose static chunks (assets.js.sync) from its
* mf-manifest — SSR preload hints. The async list is the app's whole graph. */
export function facadeChunkUrlsOf(doc: unknown, base: string): string[] {
/** The components-expose `sync` chunks from the mf-manifest — preload
* hints. */
export function facadeChunkUrlsOf(
doc: unknown,
base: string,
exposeNames: Set<string> = new Set(["components"]),
): string[] {
if (!doc || typeof doc !== "object") return [];
const exposes = (doc as { exposes?: unknown }).exposes;
if (!Array.isArray(exposes)) return [];
Expand All @@ -487,7 +490,7 @@ export function facadeChunkUrlsOf(doc: unknown, base: string): string[] {
for (const entry of exposes) {
if (!entry || typeof entry !== "object") continue;
const { name, assets } = entry as { name?: unknown; assets?: unknown };
if (typeof name !== "string" || name.replace(/^\.\//, "") !== "components") continue;
if (typeof name !== "string" || !exposeNames.has(name.replace(/^\.\//, ""))) continue;
collect((assets as { js?: { sync?: unknown } } | undefined)?.js?.sync);
}
return [
Expand All @@ -507,22 +510,35 @@ function browserManifestUrlOf(source: UiSource): string | undefined {
return base ? `${base}/${MF_MANIFEST_FILENAME}` : undefined;
}

const coreFacadePreloadOf = Effect.fn("coreFacadePreloadOf")(function* (
source: UiSource,
/** Preload chunk URLs per composed source declaring the components
* capability (`./components`, or a plugin's `./ui` — issue #1265). */
const facadePreloadsOf = Effect.fn("facadePreloadsOf")(function* (
composable: ComposableSource[],
cache: UiComposeCacheState,
) {
const url = browserManifestUrlOf(source);
if (!url) return [];
const cached = cache.facadePreload.get(url);
const now = yield* Clock.currentTimeMillis;
if (cached && now - cached.fetchedAt < MANIFEST_TTL_MS) return cached.chunks;
const chunks = yield* Effect.tryPromise(async () => {
const response = await runFetch(url);
if (!response.ok) throw new Error(`mf-manifest fetch ${response.status} for ${url}`);
return facadeChunkUrlsOf(JSON.parse(await response.text()), manifestBaseOf(url));
}).pipe(Effect.catch(() => Effect.succeed([] as string[])));
cache.facadePreload.set(url, { chunks, fetchedAt: now });
return chunks;
const out: Record<string, string[]> = {};
for (const { source, manifest } of composable) {
if (!manifest.components?.length) continue;
const url = browserManifestUrlOf(source);
if (!url) continue;
const cached = cache.facadePreload.get(url);
const now = yield* Clock.currentTimeMillis;
if (cached && now - cached.fetchedAt < MANIFEST_TTL_MS) {
if (cached.chunks.length > 0) out[source.key] = cached.chunks;
continue;
}
const chunks = yield* Effect.tryPromise(async () => {
const response = await runFetch(url);
if (!response.ok) throw new Error(`mf-manifest fetch ${response.status} for ${url}`);
const doc = JSON.parse(await response.text());
const exposes = manifest.components ?? [];
const names = new Set(exposes.map((surface) => surface.expose.replace(/^\.\//, "")));
return facadeChunkUrlsOf(doc, manifestBaseOf(url), names);
}).pipe(Effect.catch(() => Effect.succeed([] as string[])));
cache.facadePreload.set(url, { chunks, fetchedAt: now });
if (chunks.length > 0) out[source.key] = chunks;
}
return out;
});

function rememberVariant(
Expand Down Expand Up @@ -741,7 +757,7 @@ export const composeUi = Effect.fn("composeUi")(function* (

const digest = yield* digestOfSources(healthy);

const facadePreload = yield* coreFacadePreloadOf(core, cache);
const facadePreloads = yield* facadePreloadsOf(healthy, cache);
const variantKey = `${digest}::${variantCacheKey(healthySources)}`;
const isDev = healthySources.some((source) => source.localRoot);
const now = yield* Clock.currentTimeMillis;
Expand Down Expand Up @@ -797,7 +813,7 @@ export const composeUi = Effect.fn("composeUi")(function* (
routeTree: constructed.rootRoute,
digest,
nav: constructed.nav,
clientPayload: clientPayloadOf(healthy, digest, facadePreload),
clientPayload: clientPayloadOf(healthy, digest, facadePreloads),
};
rememberVariant(
cache,
Expand Down
59 changes: 35 additions & 24 deletions packages/every-plugin/src/build/ui/generated-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@
const UI_DIR = "ui";
const GENERATED_CONFIG_DIR = ".every-plugin";
const GENERATED_UI_CONFIG = "ui.rsbuild.config.generated.mjs";
/** ADR 0010 §3: present — exposes `./ui` + the manifest capability. */
const UI_EXPORTS_ENTRY = "src/ui-exports.ts";

/**
* Folder-form UI source: a `ui/` directory with route files but no own
* package.json — the plugin workspace owns the build (single-workspace
* plugin, one dev process, one deploy train). Workspace-form ui sources
* (own package.json + scripts) are NOT managed here.
* package.json — the plugin workspace owns the build (one dev process, one
* deploy train). Workspace-form ui sources are NOT managed here.
*/
export function hasFolderFormUi(cwd: string): boolean {
const uiDir = path.join(cwd, UI_DIR);
Expand All @@ -24,26 +25,33 @@
return path.join(cwd, UI_DIR, "dist");
}

function generatedUiConfig(pluginId: string): string {
return `import path from "node:path";
import { createUiRsbuildConfig } from "every-plugin/build/ui";
import pkg from "../package.json";

const workspaceRoot = path.resolve(import.meta.dirname, "..", "ui");

export default createUiRsbuildConfig({
workspaceRoot,
pkg,
role: "consumer",
manifestName: ${JSON.stringify(pluginId)},
devPort: Number(process.env.BOS_UI_PORT) || 0,
webEntry: "./ui/src/routeConfig.gen.ts",
webExposes: { "./routeConfig": "./ui/src/routeConfig.gen.ts" },
nodeEntry: "./ui/src/routeConfig.gen.ts",
nodeExposes: { "./routeConfig": "./ui/src/routeConfig.gen.ts" },
routesDirectory: "./ui/src/routes",
});
`;
function generatedUiConfig(pluginId: string, componentExpose: string | null): string {
const uiExposeEntry = componentExpose ? `, "./ui": "./ui/${componentExpose}"` : "";
const capabilityEntry = componentExpose
? '\n componentExposeFiles: [{ expose: "./ui", file: "' + componentExpose + '" }],'

Check notice on line 31 in packages/every-plugin/src/build/ui/generated-config.ts

View workflow job for this annotation

GitHub Actions / Lint and Type Check

lint/style/useTemplate

Template literals are preferred over string concatenation.
: "";
return (
[
'import path from "node:path";',
'import { createUiRsbuildConfig } from "every-plugin/build/ui";',
'import pkg from "../package.json";',
"",
'const workspaceRoot = path.resolve(import.meta.dirname, "..", "ui");',
"",
"export default createUiRsbuildConfig({",
" workspaceRoot,",
" pkg,",
' role: "consumer",',
" manifestName: " + JSON.stringify(pluginId) + ",",

Check notice on line 45 in packages/every-plugin/src/build/ui/generated-config.ts

View workflow job for this annotation

GitHub Actions / Lint and Type Check

lint/style/useTemplate

Template literals are preferred over string concatenation.
" devPort: Number(process.env.BOS_UI_PORT) || 0,",
' webEntry: "./ui/src/routeConfig.gen.ts",',
' webExposes: { "./routeConfig": "./ui/src/routeConfig.gen.ts"' + uiExposeEntry + " },",

Check notice on line 48 in packages/every-plugin/src/build/ui/generated-config.ts

View workflow job for this annotation

GitHub Actions / Lint and Type Check

lint/style/useTemplate

Template literals are preferred over string concatenation.
' nodeEntry: "./ui/src/routeConfig.gen.ts",',
' nodeExposes: { "./routeConfig": "./ui/src/routeConfig.gen.ts"' + uiExposeEntry + " },",

Check notice on line 50 in packages/every-plugin/src/build/ui/generated-config.ts

View workflow job for this annotation

GitHub Actions / Lint and Type Check

lint/style/useTemplate

Template literals are preferred over string concatenation.
].join("\n") +
capabilityEntry +
'\n routesDirectory: "./ui/src/routes",\n});\n'
);
}

/**
Expand Down Expand Up @@ -81,7 +89,10 @@
const outDir = path.join(cwd, GENERATED_CONFIG_DIR);
fs.mkdirSync(outDir, { recursive: true });
const outPath = path.join(outDir, GENERATED_UI_CONFIG);
const next = generatedUiConfig(pluginId);
const componentExpose = fs.existsSync(path.join(cwd, UI_DIR, UI_EXPORTS_ENTRY))
? UI_EXPORTS_ENTRY
: null;
const next = generatedUiConfig(pluginId, componentExpose);
if (!fs.existsSync(outPath) || fs.readFileSync(outPath, "utf8") !== next) {
fs.writeFileSync(outPath, next);
}
Expand Down
36 changes: 34 additions & 2 deletions packages/everything-dev/src/services/codegen/artifacts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,26 @@ interface UiManifestTarget {
workspaceRoot: string;
pluginName: string;
emitRouteTree: boolean;
/** the source's component-expose convention file, when present */
componentExposeFile?: { expose: string; file: string };
}

const UI_EXPORTS_ENTRY = "src/ui-exports.ts";
const CORE_EXPOSE_ENTRY = "src/components/expose.ts";

/** The source's component-expose convention file — the core publishes
* `./components` from its primitives expose, a plugin publishes `./ui` from
* the ui-exports convention file (ADR 0010 §3, issue #1265). */
const componentExposeFileOf = (
workspaceRoot: string,
isCore: boolean,
): { expose: string; file: string } | undefined => {
const entry = isCore ? CORE_EXPOSE_ENTRY : UI_EXPORTS_ENTRY;
return existsSync(join(workspaceRoot, entry))
? { expose: isCore ? "./components" : "./ui", file: entry }
: undefined;
};

export function uiManifestTargets(
runtimeConfig: RuntimeConfig,
forceRouteTree?: boolean,
Expand All @@ -62,6 +80,7 @@ export function uiManifestTargets(
emitRouteTree: forceRouteTree
? true
: !existsSync(join(ui.localPath, "src/routeTree.gen.ts")),
componentExposeFile: componentExposeFileOf(ui.localPath, true),
});
}
const authUi = runtimeConfig.auth?.ui;
Expand All @@ -81,7 +100,12 @@ export function uiManifestTargets(
for (const [key, plugin] of Object.entries(runtimeConfig.plugins ?? {})) {
const uiPath = plugin.ui?.localPath;
if (plugin.ui?.source === "local" && uiPath && existsSync(join(uiPath, "src/routes"))) {
targets.push({ workspaceRoot: uiPath, pluginName: key, emitRouteTree: false });
targets.push({
workspaceRoot: uiPath,
pluginName: key,
emitRouteTree: false,
componentExposeFile: componentExposeFileOf(uiPath, false),
});
}
}
return targets;
Expand Down Expand Up @@ -142,7 +166,15 @@ export const generateCodeArtifactsEffect = Effect.fn("generateCodeArtifacts")(fu
});
}
yield* Effect.tryPromise({
try: () => generateUiManifest(target),
try: () =>
generateUiManifest({
workspaceRoot: target.workspaceRoot,
pluginName: target.pluginName,
emitRouteTree: target.emitRouteTree,
...(target.componentExposeFile
? { componentExposeFiles: [target.componentExposeFile] }
: {}),
}),
catch: (cause) =>
new ArtifactGenError({ phase: `generate ui manifest (${target.pluginName})`, cause }),
});
Expand Down
Loading
Loading