Files

264 lines
6.8 KiB
JavaScript

import { spawnSync } from "node:child_process";
import { existsSync, readFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const scriptPath = fileURLToPath(import.meta.url);
const __dirname = dirname(scriptPath);
const repoRoot = resolve(__dirname, "..");
const webDir = resolve(repoRoot, "apps/web");
if (process.argv[1] === scriptPath) {
main(process.argv.slice(2));
}
export function main(args = process.argv.slice(2), env = process.env) {
const target = args[0];
if (target !== "staging" && target !== "prod") {
console.error(
"Usage: node scripts/deploy-cloudflare-pages.mjs <staging|prod>",
);
process.exit(1);
}
const viteMode = target === "prod" ? "production" : "staging";
const projectName =
env.CF_PAGES_PROJECT_NAME ??
env.CLOUDFLARE_PAGES_PROJECT_NAME ??
"lolympus";
const deployPlan = resolveDeployPlan(target, env);
validateEnv(viteMode, env);
run("pnpm", ["--filter", "web", "run", `build:${target}`], repoRoot);
const deployArgs = createPagesDeployArgs(projectName, deployPlan.pagesBranch);
console.error(
[
`Deploying ${target} from ${deployPlan.sourceBranch}`,
`to Cloudflare Pages branch ${deployPlan.pagesBranch}`,
].join(" "),
);
run("pnpm", deployArgs, webDir);
}
export function createPagesDeployArgs(projectName, branch) {
const deployArgs = [
"exec",
"wrangler",
"pages",
"deploy",
"dist",
"--project-name",
projectName,
];
if (branch) deployArgs.push("--branch", branch);
return deployArgs;
}
export function resolveStagingBranch(env = process.env) {
return resolveDeployPlan("staging", env).pagesBranch;
}
export function resolveDeployPlan(
target,
env = process.env,
releaseBranchRowsProvider = () => {
refreshRemoteReleaseBranches();
return listReleaseBranchRefs();
},
) {
const sourceBranch = resolveSourceBranch(
target,
env,
releaseBranchRowsProvider,
);
const pagesBranch =
target === "prod" ? resolveProductionBranch(env) : sourceBranch;
return { sourceBranch, pagesBranch };
}
function resolveSourceBranch(target, env, releaseBranchRowsProvider) {
const sourceEnvKey =
target === "prod" ? "CF_PAGES_RELEASE_BRANCH" : "CF_PAGES_STAGING_BRANCH";
const configuredBranch = env[sourceEnvKey]?.trim();
if (configuredBranch) return configuredBranch;
const latestReleaseBranch = selectLatestReleaseBranch(
releaseBranchRowsProvider(),
);
if (latestReleaseBranch) return latestReleaseBranch;
console.error(
[
`No release/* branch found for ${target} deploy.`,
"Create a release branch, for example: git push origin main:release/66",
`Or set ${sourceEnvKey} explicitly.`,
].join("\n"),
);
process.exit(1);
}
function resolveProductionBranch(env) {
return (
env.CF_PAGES_PRODUCTION_BRANCH?.trim() ||
env.CF_PAGES_PROD_BRANCH?.trim() ||
"main"
);
}
export function selectLatestReleaseBranch(refRows) {
const latestByBranch = new Map();
for (const row of refRows) {
const [timestampText, refName] = row.split("\t");
const branch = normalizeReleaseBranch(refName);
const timestamp = Number(timestampText);
if (!branch || !Number.isFinite(timestamp)) continue;
const current = latestByBranch.get(branch);
if (!current || timestamp > current.timestamp) {
latestByBranch.set(branch, { branch, timestamp });
}
}
const [latest] = [...latestByBranch.values()].sort((left, right) => {
if (left.timestamp !== right.timestamp) {
return right.timestamp - left.timestamp;
}
return right.branch.localeCompare(left.branch, "en", { numeric: true });
});
return latest?.branch;
}
export function normalizeReleaseBranch(refName) {
const branch = refName?.trim();
if (!branch) return undefined;
if (branch.startsWith("origin/release/")) {
return branch.slice("origin/".length);
}
if (branch.startsWith("release/")) return branch;
return undefined;
}
function listReleaseBranchRefs() {
const result = spawnSync(
"git",
[
"for-each-ref",
"--sort=-committerdate",
"--format=%(committerdate:unix)%09%(refname:short)",
"refs/remotes/origin/release",
"refs/heads/release",
],
{
cwd: repoRoot,
encoding: "utf8",
shell: process.platform === "win32",
},
);
if (result.status !== 0) {
const stderr = result.stderr?.trim();
if (stderr) console.error(stderr);
return [];
}
return result.stdout.split(/\r?\n/).filter(Boolean);
}
function refreshRemoteReleaseBranches() {
spawnSync("git", ["remote", "prune", "origin"], {
cwd: repoRoot,
stdio: "ignore",
shell: process.platform === "win32",
});
spawnSync(
"git",
[
"fetch",
"--prune",
"origin",
"+refs/heads/release/*:refs/remotes/origin/release/*",
],
{
cwd: repoRoot,
stdio: "ignore",
shell: process.platform === "win32",
},
);
}
function run(command, args, cwd) {
const result = spawnSync(command, args, {
cwd,
stdio: "inherit",
shell: process.platform === "win32",
});
if (result.status !== 0) {
process.exit(result.status ?? 1);
}
}
function validateEnv(mode, env) {
const fileEnv = [
".env",
".env.local",
`.env.${mode}`,
`.env.${mode}.local`,
].reduce((acc, fileName) => {
const envFile = resolve(webDir, fileName);
if (!existsSync(envFile)) return acc;
return { ...acc, ...parseEnvFile(envFile) };
}, {});
const requiredKeys = [
"VITE_API_BASE_URL",
"VITE_DEFAULT_COMMUNITY_ID",
"VITE_MSAL_CLIENT_ID",
"VITE_MSAL_AUTHORITY",
"VITE_MSAL_API_SCOPE",
"VITE_MSAL_REDIRECT_URI",
];
const missing = requiredKeys.filter((key) => {
const value = env[key] ?? fileEnv[key];
return !value || value.includes("<");
});
if (missing.length === 0) return;
console.error(
[
`Missing Cloudflare Pages ${mode} build env: ${missing.join(", ")}`,
`Create apps/web/.env.${mode}, apps/web/.env.${mode}.local, or export these variables before deploy.`,
`Use apps/web/.env.${mode}.example as a template.`,
].join("\n"),
);
process.exit(1);
}
function parseEnvFile(path) {
return Object.fromEntries(
readFileSync(path, "utf8")
.split(/\r?\n/)
.map((line) => line.trim())
.filter((line) => line && !line.startsWith("#"))
.map((line) => {
const separatorIndex = line.indexOf("=");
if (separatorIndex === -1) return [line, ""];
const key = line.slice(0, separatorIndex).trim();
let value = line.slice(separatorIndex + 1).trim();
if (
(value.startsWith('"') && value.endsWith('"')) ||
(value.startsWith("'") && value.endsWith("'"))
) {
value = value.slice(1, -1);
}
return [key, value];
}),
);
}