everything-dev
Version:
A consolidated product package for building Module Federation apps with oRPC APIs.
140 lines (138 loc) • 6.81 kB
JavaScript
import { MISSING_CONFIG_MESSAGE, readAuthoredConfigInput } from "../resolution/load.mjs";
import { openResolution } from "../resolution/session.mjs";
import { timePhase } from "../../utils/timing.mjs";
import { formatUnknownError } from "../../utils/errors.mjs";
import { readNodeModulesVersion } from "../framework-version.mjs";
import { syncResolvedSharedDeps } from "../workspace/shared-deps.mjs";
import { saveBosConfig } from "../../utils/save-config.mjs";
import { runTypesGen } from "./init.mjs";
import { syncTemplate } from "./sync.mjs";
import { FRAMEWORK_PACKAGES, installDriftError, migrateChildRootPackageJson } from "./upgrade-packages.mjs";
import { detectOwnedDivergentKeys, realignOwnedRemotes } from "./upgrade-realign.mjs";
import { buildChangelogUrl } from "./upgrade-source.mjs";
import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
//#region src/services/scaffold/upgrade-migration.ts
/**
* Surgical authored-release edit on the authored config's source: rewrites
* only the `release:` line (or a legacy `platform:` line — the codemod form),
* or inserts one after `extends`, leaving every other byte — formatting,
* comments, attachments — untouched. Throws with the version to set by hand
* when no safe anchor exists; the authored file is never re-serialized.
*/
function stampRelease(source, version) {
const releaseLineRe = /^([ \t]*)(release|platform|"release"|"platform")[ \t]*:[ \t]*"([^"]*)"(,?)[ \t]*$/;
const extendsLineRe = /^([ \t]*)(extends|"extends")[ \t]*:[ \t]*("[^"]*")(,?)[ \t]*$/;
const lines = source.split("\n");
for (let i = 0; i < lines.length; i++) {
const match = lines[i].match(releaseLineRe);
if (match) {
lines[i] = `${match[1]}release: "${version}"${match[4]}`;
return lines.join("\n");
}
}
for (let i = 0; i < lines.length; i++) {
const match = lines[i].match(extendsLineRe);
if (match) {
lines[i] = `${match[1]}${match[2]}: ${match[3]},`;
lines.splice(i + 1, 0, `${match[1]}release: "${version}",`);
return lines.join("\n");
}
}
throw new Error(`could not stamp the authored release surgically — no release or extends property found in the authored config; set release: "${version}" in bos.app.ts manually and re-run`);
}
/**
* Stamp the resolved framework version into the authored config's `release`
* field (ADR 0034). Runs at the top of the migration phase on both the inline
* and re-exec'd paths, so everyday resolution (sync, init, runtime) always
* freezes to the release this upgrade just landed from — whether or not the
* package versions actually moved. A legacy `platform:` line is the codemod
* form: the same stamp rewrites it to `release:`. The authored `bos.app.ts`
* is edited surgically (the field line only) — never re-serialized.
*/
async function applyRelease(projectDir, parentSource) {
const version = parentSource.platform.manifest.frameworkVersion;
const config = await readAuthoredConfigInput(projectDir);
if (!config) return void 0;
if (config.release === version && config.platform === void 0) return void 0;
const appConfigPath = join(projectDir, "bos.app.ts");
if (existsSync(appConfigPath)) {
const source = readFileSync(appConfigPath, "utf-8");
writeFileSync(appConfigPath, stampRelease(source, version));
return "bos.app.ts";
}
delete config.platform;
config.release = version;
await saveBosConfig(projectDir, config);
return "bos.config.json";
}
/**
* The re-exec'd migration child runs `--json`, so its stdout is the structured
* result — a failed run carries the real failure in its `error` field, which
* raw stderr/stdout concatenation hides behind `[CLI] [object Object]`.
*/
function describeMigrationFailure(stdout, stderr) {
if (stdout) try {
const parsed = JSON.parse(stdout);
if (parsed && typeof parsed === "object" && parsed.error != null) return formatUnknownError(parsed.error);
} catch {}
const raw = (stderr || stdout || "").trim();
return raw.length > 0 ? raw : "Unknown error";
}
async function runMigrationPhase(projectDir, options, parentSource, scope) {
const timings = [];
const legacyCache = join(projectDir, ".bos", "platform-manifest.json");
if (existsSync(legacyCache)) rmSync(legacyCache, { force: true });
const drift = installDriftError(Object.fromEntries(FRAMEWORK_PACKAGES.map((name) => [name, readNodeModulesVersion(projectDir, name)])), Object.fromEntries(FRAMEWORK_PACKAGES.map((name) => [name, parentSource.catalog[name]])));
if (drift) throw new Error(drift);
const releaseStamped = await timePhase(timings, "stamp release", () => applyRelease(projectDir, parentSource));
const migratedRootPackageJson = await timePhase(timings, "migrate root package", () => migrateChildRootPackageJson(projectDir));
let syncResult;
if (scope.versionDelta && !options.noSync) {
syncResult = await timePhase(timings, "sync template", () => syncTemplate(projectDir, {
dryRun: false,
noInstall: true,
force: options.force,
resolvedRelease: parentSource.platform
}));
if (syncResult?.status === "conflicted") throw new Error(syncResult.error ?? "Template sync hit unresolvable local conflicts");
}
await timePhase(timings, "sync shared deps", async () => {
const configSession = await openResolution({ cwd: projectDir });
if (!configSession?.config) throw new Error(`${MISSING_CONFIG_MESSAGE} in current directory`);
return syncResolvedSharedDeps({
configDir: projectDir,
hostMode: "local",
bosConfig: configSession.config
});
});
if (!options.noInstall) await timePhase(timings, "generate types", () => runTypesGen(projectDir));
let realignment;
if (scope.versionDelta && !options.noRealign) realignment = await timePhase(timings, "realign owned slots", async () => {
const session = await openResolution({ cwd: projectDir });
if (!session?.config) return void 0;
const { keys, lines } = await detectOwnedDivergentKeys(session);
if (keys.length === 0) return {
keys: [],
realigned: [],
failures: []
};
for (const line of lines) if (line.kind === "owned") console.error(` [realign] ${line.message}`);
return await realignOwnedRemotes(projectDir, keys, console.error);
});
const migratedFiles = [...releaseStamped ? [releaseStamped] : [], ...migratedRootPackageJson ? ["package.json"] : []];
const mainPkg = parentSource.catalog["everything-dev"];
const changelogUrl = mainPkg ? buildChangelogUrl(void 0, mainPkg, parentSource.repository) : void 0;
return {
status: "upgraded",
packages: [],
sync: syncResult,
migrated: migratedFiles.length > 0 ? migratedFiles : void 0,
...realignment ? { realignment } : {},
timings,
changelogUrl
};
}
//#endregion
export { applyRelease, describeMigrationFailure, runMigrationPhase, stampRelease };
//# sourceMappingURL=upgrade-migration.mjs.map