everything-dev
Version:
A consolidated product package for building Module Federation apps with oRPC APIs.
444 lines (442 loc) • 14.7 kB
JavaScript
import { MISSING_CONFIG_MESSAGE, findConfigPath, readAuthoredConfigInput } from "../services/resolution/load.mjs";
import { colors } from "../utils/theme.mjs";
import { readWorkspaceCatalog } from "../services/workspace/catalog.mjs";
import { ManifestService } from "../services/platform/manifest.mjs";
import { openResolution } from "../services/resolution/session.mjs";
import { checkFederationCompat, checkUiCompositionCompat } from "../services/federation/service.mjs";
import { generateCodeArtifacts } from "../services/codegen/artifacts.mjs";
import { findWorkspaceRoot } from "../services/workspace/workspace.mjs";
import { readInstalledFrameworkVersion } from "../services/framework-version.mjs";
import { selectWorkspaceTargets } from "../services/workspace/build-train.mjs";
import { resolvePublishedConfig } from "../services/registry/published.mjs";
import { upgradeTemplate } from "../services/scaffold/upgrade.mjs";
import { planUpgradeInteraction } from "../cli/upgrade-plan.mjs";
import { GateBlocked } from "../services/scaffold/upgrade-audit/domain.mjs";
import { applyV1Tree, auditV1Tree, isV2Tree, maintainV1Tree, toPlainFinding } from "../services/scaffold/upgrade-audit/index.mjs";
import { existsSync, readFileSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { Effect } from "effect";
import process from "node:process";
import { spawnSync } from "node:child_process";
import { generateUiManifest } from "every-plugin/ui/manifest-generator";
//#region src/handlers/upgrade.ts
const nodeEnvProduction = () => process.env.NODE_ENV === "production";
const envOf = (name) => process.env[name];
const stageLog = (message) => {
console.log(message);
};
function registerUpgrade(builder) {
return {
upgrade: builder.upgrade.effect(function* (_opts, input) {
return yield* Effect.tryPromise({
try: async () => {
const configPath = findConfigPath();
if (!configPath) return {
status: "error",
packages: [],
error: `${MISSING_CONFIG_MESSAGE} in current directory`
};
const projectDir = resolve(dirname(configPath));
if (input.from === "v1") {
if (input.maintain && input.maintain.length > 0) {
const migrated = [];
const notes = [];
for (const step of input.maintain) try {
const result = await maintainV1Tree(projectDir, step, input.dryRun);
for (const path of result.writes) migrated.push(`${step}: wrote ${path}`);
for (const path of result.deletes) migrated.push(`${step}: deleted ${path}`);
for (const note of result.notes) notes.push(`${step}: ${note}`);
} catch (error) {
if (!(error instanceof GateBlocked)) throw error;
return {
status: "gate-blocked",
packages: [],
blockers: error.findings.map(toPlainFinding)
};
}
return {
status: input.dryRun ? "dry-run" : "upgraded",
packages: [],
migrated,
notes
};
}
if (isV2Tree(projectDir)) return {
status: "already-upgraded",
packages: [],
notes: ["bos.app.ts present — this tree is already on the v2 train; nothing to audit or apply"]
};
if (input.audit) {
const outcome = await auditV1Tree(projectDir);
const auditResult = {
tier: outcome.tier,
findings: outcome.findings,
manifest: outcome.manifest
};
return outcome.gateBlocked ? {
status: "gate-blocked",
packages: [],
audit: auditResult,
blockers: outcome.findings.filter((f) => f.severity === "blocker")
} : {
status: "audit",
packages: [],
audit: auditResult
};
}
const outcome = await applyV1Tree(projectDir, input.dryRun);
if (!outcome.ok) return {
status: "gate-blocked",
packages: [],
blockers: outcome.blockers
};
return {
status: input.dryRun ? "dry-run" : "upgraded",
packages: [],
migrated: outcome.outcome.migrated,
notes: outcome.outcome.notes
};
}
const decision = await planUpgradeInteraction(projectDir, input);
if (decision === null) return {
status: "cancelled",
packages: []
};
return await upgradeTemplate(projectDir, {
...input,
...decision
});
},
catch: (error) => ({
status: "error",
packages: [],
error: error instanceof Error ? error.message : "Unknown error"
})
});
}),
typecheck: builder.typecheck.effect(function* (_opts, input) {
return yield* Effect.tryPromise({
try: async () => {
const configPath = findConfigPath();
if (!configPath) return {
status: "error",
checked: [],
skipped: [],
results: [],
error: `${MISSING_CONFIG_MESSAGE} in current directory`
};
const projectDir = resolve(dirname(configPath));
const refreshed = await openResolution({ cwd: projectDir });
if (!refreshed?.config || !refreshed.runtime) return {
status: "error",
checked: [],
skipped: [],
results: [],
error: "Failed to load the authored config"
};
const runtime = refreshed.runtime;
const resolvedConfig = refreshed.config;
await generateCodeArtifacts(projectDir, resolvedConfig, {
env: nodeEnvProduction() ? "production" : "development",
extendsChain: [...refreshed.chain],
runtimeConfig: runtime
});
const workspaceEntries = [];
const skipped = [];
const appTargets = [
{
key: "host",
label: "host",
target: runtime.host
},
{
key: "ui",
label: "ui",
target: runtime.ui
},
{
key: "api",
label: "api",
target: runtime.api
}
];
if (runtime.auth) appTargets.push({
key: "auth",
label: "auth",
target: runtime.auth
});
for (const entry of appTargets) if (entry.target?.source === "local" && entry.target.localPath && existsSync(join(entry.target.localPath, "tsconfig.json"))) workspaceEntries.push({
key: entry.key,
label: entry.label,
dir: entry.target.localPath
});
else skipped.push({
key: entry.key,
label: entry.label
});
for (const [key, plugin] of Object.entries(runtime.plugins ?? {})) {
const label = `plugins/${key}`;
const localPath = plugin.source === "local" ? plugin.localPath : void 0;
if (localPath && existsSync(join(localPath, "tsconfig.json"))) workspaceEntries.push({
key,
label,
dir: localPath
});
else skipped.push({
key,
label
});
if (localPath && existsSync(join(localPath, "ui", "tsconfig.json"))) workspaceEntries.push({
key,
label: `${label}/ui`,
dir: localPath,
ui: true
});
}
const selected = selectWorkspaceTargets(input.packages, resolvedConfig);
const targets = input.packages === "all" ? workspaceEntries : workspaceEntries.filter((entry) => selected.includes(entry.key));
const skippedEntries = input.packages === "all" ? skipped : skipped.filter((entry) => selected.includes(entry.key));
const checked = [];
const results = [];
for (const entry of targets) {
if (entry.ui && !existsSync(join(entry.dir, "ui", "src", "routeTree.gen.ts"))) try {
await generateUiManifest({
workspaceRoot: join(entry.dir, "ui"),
pluginName: entry.key,
emitRouteTree: true
});
} catch (error) {
checked.push(entry.label);
results.push({
workspace: entry.label,
passed: false,
error: `routeTree materialization failed: ${error instanceof Error ? error.message : String(error)}`
});
continue;
}
const packageJsonPath = join(entry.dir, "package.json");
let args = entry.ui ? [
"exec",
"tsc",
"--noEmit",
"-p",
"ui/tsconfig.json"
] : [
"exec",
"tsc",
"--noEmit"
];
if (existsSync(packageJsonPath)) try {
const pkg = JSON.parse(readFileSync(packageJsonPath, "utf-8"));
const scriptName = entry.ui ? "typecheck:ui" : "typecheck";
if (pkg.scripts?.[scriptName]) args = ["run", scriptName];
} catch {}
stageLog(`\n ${colors.dim("Checking")} ${colors.cyan(entry.label)}`);
const child = spawnSync("pnpm", args, {
cwd: entry.dir,
stdio: "inherit"
});
const passed = child.status === 0;
checked.push(entry.label);
results.push({
workspace: entry.label,
passed,
error: passed ? void 0 : `typecheck failed (exit code ${child.status ?? "n/a"})`
});
}
return {
status: "success",
checked,
skipped: skippedEntries.map((entry) => entry.label),
results
};
},
catch: (error) => ({
status: "error",
checked: [],
skipped: [],
results: [],
error: error instanceof Error ? error.message : "Unknown error"
})
});
}),
mfCheck: builder.mfCheck.effect(function* (_opts, input) {
const manifestService = yield* ManifestService;
return yield* Effect.promise(async () => {
let authored = null;
try {
authored = await readAuthoredConfigInput();
} catch (e) {
return {
status: "fail",
hostVersion: null,
hostReachable: false,
hostReason: e instanceof Error ? e.message : String(e),
remotes: []
};
}
if (!authored) {
const account = envOf("BOS_ACCOUNT");
const gateway = envOf("BOS_GATEWAY");
if (!account || !gateway) return {
status: "fail",
hostVersion: null,
hostReachable: false,
hostReason: MISSING_CONFIG_MESSAGE,
remotes: []
};
try {
authored = await resolvePublishedConfig(account, gateway);
} catch (e) {
return {
status: "fail",
hostVersion: null,
hostReachable: false,
hostReason: e instanceof Error ? e.message : String(e),
remotes: []
};
}
if (!authored) return {
status: "fail",
hostVersion: null,
hostReachable: false,
hostReason: `No config found at bos://${account}/${gateway} — verify BOS_ACCOUNT/BOS_GATEWAY and that the config has been published.`,
remotes: []
};
}
const report = await checkFederationCompat(authored, { timeoutMs: input.timeoutMs });
const ui = await checkUiCompositionCompat(authored, { timeoutMs: input.timeoutMs });
let manifest;
try {
const configPath = findConfigPath();
if (configPath) {
const projectDir = resolve(dirname(configPath));
const resolved = await manifestService.resolvePlatformManifest({
configDir: projectDir,
localConfig: authored
});
if (resolved) {
const root = findWorkspaceRoot(projectDir)?.dir ?? projectDir;
const violations = manifestService.checkPlatformCompat(resolved.manifest, {
platformVersion: readInstalledFrameworkVersion(projectDir, "everything-dev"),
catalog: readWorkspaceCatalog(root)
});
manifest = {
ok: violations.length === 0,
violations
};
}
}
} catch (e) {
manifest = {
ok: false,
violations: [{
kind: "minChild",
message: `release manifest resolution failed: ${e instanceof Error ? e.message : String(e)}`
}]
};
}
return {
status: report.ok && (manifest?.ok ?? true) ? "ok" : "fail",
hostVersion: report.hostVersion,
hostReachable: report.hostReachable,
hostReason: report.hostReason,
remotes: report.remotes,
...ui.remotes.length > 0 ? { ui: {
ok: ui.ok,
remotes: ui.remotes
} } : {},
...manifest ? { manifest } : {}
};
});
}),
manifest: builder.manifest.effect(function* (_opts, input) {
const manifestService = yield* ManifestService;
return yield* Effect.promise(async () => {
const inImage = manifestService.readInImagePlatformManifest();
if (inImage) return {
status: "ok",
version: inImage.frameworkVersion,
source: "in-image",
...input.check ? { compat: {
ok: true,
violations: []
} } : {}
};
const configPath = findConfigPath();
if (!configPath) return {
status: "absent",
version: null,
error: `${MISSING_CONFIG_MESSAGE} — and the in-image platform manifest is absent (non-framework image)`
};
const projectDir = resolve(dirname(configPath));
try {
const authoredConfig = await readAuthoredConfigInput() ?? {};
let resolved;
let drift;
try {
resolved = await manifestService.resolvePlatformManifest({
configDir: projectDir,
localConfig: authoredConfig
});
} catch (pinError) {
const latest = await manifestService.resolvePlatformManifest({
configDir: projectDir,
localConfig: {
...authoredConfig,
release: void 0
}
});
if (!latest) throw pinError;
resolved = latest;
const authored = typeof authoredConfig.release === "string" ? authoredConfig.release : void 0;
drift = authored ? {
pinned: authored,
published: latest.manifest.frameworkVersion
} : void 0;
}
if (!resolved) return {
status: "absent",
version: null
};
if (drift) return {
status: "fail",
version: drift.published,
source: `bos://${resolved.source.account}/${resolved.source.gateway}`,
drift,
error: `parent release is ${drift.published} (published at bos://${resolved.source.account}/${resolved.source.gateway}), you target ${drift.pinned} — run \`bos upgrade\` to realign`
};
const base = {
status: "ok",
version: resolved.manifest.frameworkVersion,
source: `bos://${resolved.source.account}/${resolved.source.gateway}`,
fromCache: resolved.fromCache,
provenance: resolved.provenance
};
if (!input.check) return base;
const root = findWorkspaceRoot(projectDir)?.dir ?? projectDir;
const violations = manifestService.checkPlatformCompat(resolved.manifest, {
platformVersion: readInstalledFrameworkVersion(projectDir, "everything-dev"),
catalog: readWorkspaceCatalog(root)
});
return {
...base,
compat: {
ok: violations.length === 0,
violations
}
};
} catch (e) {
return {
status: "fail",
version: null,
error: e instanceof Error ? e.message : String(e)
};
}
});
})
};
}
//#endregion
export { registerUpgrade };
//# sourceMappingURL=upgrade.mjs.map