UNPKG

everything-dev

Version:

A consolidated product package for building Module Federation apps with oRPC APIs.

222 lines (220 loc) • 10.2 kB
import { fetchResponse } from "../../utils/http-client.mjs"; import { buildRegistryConfigUrlForNetwork, fetchPublishedConfigFromFastKv, getRegistryNamespaceForNetwork } from "../registry/fastkv.mjs"; import { getNetworkIdForAccount } from "../../utils/network.mjs"; import { colors } from "../../utils/theme.mjs"; import { selectWorkspaceTargets } from "../workspace/build-train.mjs"; import { readSessionHandle } from "../auth/session.mjs"; import { describeSigningStrategy, resolveSigningStrategy } from "../auth/near-signer.mjs"; import { probeStorageOrigin, resolveCdnDeployInputs } from "./cdn.mjs"; import { existsSync, readFileSync } from "node:fs"; import { join } from "node:path"; import process from "node:process"; //#region src/services/deploy/preflight.ts const FRAMEWORK_PACKAGE_NAMES = [ "better-near-auth", "every-plugin", "everything-dev" ]; /** * Whether npm serves `name@version` (true), definitively does not (404 — * false), or whether publishability could not be determined (network error, * unexpected status — null; callers must not block on that). */ async function npmVersionPublished(name, version, options = {}) { try { const suffix = options.bustCache ? `?bust=${Date.now()}-${Math.random()}` : ""; const res = await fetchResponse(`https://registry.npmjs.org/${name}/${version}${suffix}`, { headers: { Accept: "application/json" } }); if (res.status === 200) return true; if (res.status === 404) return false; return null; } catch { return null; } } function readFrameworkPackageManifests(configDir) { const manifests = []; for (const name of FRAMEWORK_PACKAGE_NAMES) { const manifestPath = join(configDir, "packages", name, "package.json"); if (!existsSync(manifestPath)) continue; const version = JSON.parse(readFileSync(manifestPath, "utf-8")).version; if (version) manifests.push({ name, version }); } return manifests; } const DEFAULT_PUBLISH_WAIT = { intervalMs: 15e3, budgetMs: 9e5 }; /** * Waits out the Deploy/Release race on version-bump merges: both trains * trigger on the same push, and the Release workflow needs minutes to * publish the bumped versions. Instead of refusing (bundles never ship * ahead of the registry — that invariant stands), preflight parks here * until every workspace framework version is on npm, up to a bounded * budget; a timeout keeps the original fail-loud behavior with a pointer * at the Release run. */ async function waitForFrameworkPackages(configDir, options = {}) { const intervalMs = options.intervalMs ?? DEFAULT_PUBLISH_WAIT.intervalMs; const budgetMs = options.budgetMs ?? DEFAULT_PUBLISH_WAIT.budgetMs; const sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))); const now = options.now ?? Date.now; const probe = options.probe ?? ((name, version) => npmVersionPublished(name, version, { bustCache: true })); const manifests = readFrameworkPackageManifests(configDir); if (manifests.length === 0) return { kind: "ok" }; const listing = (packages) => packages.map((pkg) => `${pkg.name}@${pkg.version}`).join(", "); const states = await probePackages(manifests, probe); if (states.every((entry) => entry.state === true)) return { kind: "ok" }; let pending = states.filter((entry) => entry.state === false).map((entry) => entry.pkg); console.log(` Waiting for the Release workflow to publish ${colors.cyan(listing(pending))} to npm (polling every ${Math.round(intervalMs / 1e3)}s, budget ${Math.round(budgetMs / 6e4)} min)`); const startedAt = now(); const deadline = startedAt + budgetMs; let lastProgressLog = startedAt; while (true) { await sleep(intervalMs); const results = await probePackages(pending, probe); for (const entry of results.filter((check) => check.state === true)) console.log(` ✓ ${entry.pkg.name}@${entry.pkg.version} published`); pending = results.filter((check) => check.state === false).map((check) => check.pkg); if (pending.length === 0) { console.log(" ✓ framework packages cleared the npm gate — resuming the deploy train"); return { kind: "ok" }; } if (now() >= deadline) return { kind: "error", error: `Framework package(s) ${listing(pending)} were not published to npm within ${Math.round(budgetMs / 6e4)} min — deploys must not ship bundles ahead of the registry (child scaffolds and update checks read these versions). The Release workflow for this commit may still be publishing or may have failed — check its run, then re-run the deploy once the packages are on npm.` }; if (now() - lastProgressLog >= 6e4) { lastProgressLog = now(); console.log(` Still unpublished: ${listing(pending)} (${Math.round((now() - startedAt) / 1e3)}s elapsed)`); } } } async function probePackages(packages, probe) { const results = []; for (const pkg of packages) { const state = await probe(pkg.name, pkg.version); if (state === null) console.log(colors.yellow(` ! Could not verify ${pkg.name}@${pkg.version} on npm (registry unreachable) — continuing`)); results.push({ pkg, state }); } return results; } async function preflightPublish(input) { const { configDir } = input; const bosConfig = input.bosConfig; const isStaging = input.env === "staging"; const account = isStaging ? bosConfig.staging?.account ?? bosConfig.account : bosConfig.account; const gateway = isStaging ? bosConfig.staging?.domain ?? bosConfig.domain : bosConfig.domain; if (!gateway) return { kind: "error", registryUrl: "", error: "authored config must define domain to publish" }; const network = input.network ?? getNetworkIdForAccount(account); const registryUrl = buildRegistryConfigUrlForNetwork(network, account, gateway, input.registry); const fail = (error) => ({ kind: "error", registryUrl, error }); const sessionFile = readSessionHandle(configDir); const publishAuth = bosConfig.publish?.auth; const governsWalletPublish = (publishAuth === "session" || input.wallet) && !input.privateKey; let credential; if (governsWalletPublish) { if (!sessionFile?.credential) return fail((input.wallet ? "--wallet requires" : "the authored config sets publish.auth = \"session\", but") + " no CLI session is stored in .bos/ for this project. Run bos login to create one."); if (sessionFile.credential.accountId && sessionFile.credential.accountId !== account) return fail(`The CLI session was created for ${sessionFile.credential.accountId}, but the configured account is ${account}. Gasless wallet publish relays the FastKV write under the session's NEAR account. Run bos login again under the matching account.`); credential = sessionFile.credential; } const useCustody = publishAuth === "custody" && !input.privateKey && !input.wallet; let custodyWallet; if (useCustody) { const wallet = sessionFile?.custodyWallet; if (!wallet) return fail("the authored config sets publish.auth = \"custody\", but no custody wallet is stored in .bos/. Run `bos login --custody` first."); if (wallet.network !== network) return fail(`The custody wallet was registered on ${wallet.network}, but this project publishes on ${network}. Run \`bos login --custody\` from a ${network} account.`); if (wallet.nearAccountId !== account) return fail(`publish.auth = "custody" publishes under the custody wallet's account, but the configured account is ${account} and the custody wallet account is ${wallet.nearAccountId}. Set the authored config's account to the custody wallet account.`); custodyWallet = wallet; } if (input.dryRun) return { kind: "dry-run", registryUrl }; const useWallet = input.wallet === true; let strategy; if (useWallet) console.log(` Signing via ${colors.cyan("gasless NEP-366 delegate action (relayed by the platform relayer)")}`); else try { strategy = await resolveSigningStrategy({ privateKey: input.privateKey, account, network }); console.log(` Signing via ${colors.cyan(describeSigningStrategy(strategy))}`); } catch (error) { return fail(error instanceof Error ? error.message : "Unknown error"); } let cdnDeploy = { cdnOrigin: void 0, storageOrigin: "", apiKey: void 0 }; if (input.build) { const wait = await waitForFrameworkPackages(configDir); if (wait.kind === "error") return fail(wait.error); cdnDeploy = resolveCdnDeployInputs({ env: process.env, bosConfig, session: sessionFile?.credential ?? null, custodyAccount: useCustody ? custodyWallet?.nearAccountId : void 0, account, gateway, uploadsPlanned: input.build }); if (cdnDeploy.error) return fail(cdnDeploy.error); if (cdnDeploy.warning) console.log(colors.yellow(` ! ${cdnDeploy.warning}`)); if (!cdnDeploy.cdnOrigin) return fail("CDN deploy resolved no bundle origin"); const probeError = await probeStorageOrigin(cdnDeploy.storageOrigin); if (probeError) return fail(`The bundle upload origin ${cdnDeploy.storageOrigin} is not running the platform API — ${probeError}. Check BOS_STORAGE_ORIGIN / the bos login session, then re-run.`); } let publishedConfig = null; let publishedConfigState = "missing"; try { publishedConfig = await fetchPublishedConfigFromFastKv(registryUrl); publishedConfigState = "fetched"; } catch (error) { if ((error instanceof Error ? error.message : String(error)).startsWith("No config found")) console.log(colors.dim(" Note: no published config found yet (first publish) — continuing")); else { publishedConfigState = "unreachable"; console.log(colors.dim(" Note: registry read failed — continuing")); } } return { kind: "ready", plan: { isStaging, account, gateway, network, registryUrl, registryNamespace: getRegistryNamespaceForNetwork(network, input.registry), targets: selectWorkspaceTargets(input.packages, bosConfig), useWallet, useCustody, strategy, cdnOrigin: cdnDeploy.cdnOrigin, storageOrigin: cdnDeploy.storageOrigin, storageApiKey: cdnDeploy.apiKey, publishedConfig, publishedConfigState, ...custodyWallet ? { custodyWallet } : {}, ...credential ? { credential } : {} } }; } //#endregion export { npmVersionPublished, preflightPublish, waitForFrameworkPackages }; //# sourceMappingURL=preflight.mjs.map