Compare commits
5
Commits
eadae789c8
...
release/66
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e63fba0286 | ||
|
|
245a096606 | ||
|
|
6e0afe84cd | ||
|
|
6accb4b166 | ||
|
|
f3d05004ce |
No files matched your search
@@ -0,0 +1 @@
|
|||||||
|
66
|
||||||
@@ -90,3 +90,19 @@ pnpm --filter web build:staging
|
|||||||
```
|
```
|
||||||
|
|
||||||
현재 정리된 기준으로 API 테스트와 웹 테스트 빌드를 통과합니다.
|
현재 정리된 기준으로 API 테스트와 웹 테스트 빌드를 통과합니다.
|
||||||
|
|
||||||
|
## Deployment branches
|
||||||
|
|
||||||
|
`main`은 항상 배포 가능한 trunk로 유지하고 dev 배포 기준으로 사용합니다.
|
||||||
|
빌드 번호는 `BUILD_NUMBER` 파일에서 1씩 증가시키며, 현재 시작 번호는 `66`입니다.
|
||||||
|
staging 검증이 필요할 때는 `release/66` 같은 임시 브랜치를 만들고,
|
||||||
|
검증이 끝나면 삭제합니다.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git push origin main:release/66
|
||||||
|
pnpm deploy:web:staging
|
||||||
|
```
|
||||||
|
|
||||||
|
staging Pages 배포 스크립트는 `CF_PAGES_STAGING_BRANCH`가 있으면 그 값을
|
||||||
|
사용하고, 없으면 최신 `release/*` 브랜치를 자동으로 선택합니다. 최신 기준은
|
||||||
|
브랜치가 가리키는 커밋 시각이며, 동률이면 브랜치명 내림차순입니다.
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
import {
|
||||||
|
createCorsOrigin,
|
||||||
|
isAllowedCorsOrigin,
|
||||||
|
resolveWebOrigins,
|
||||||
|
} from './cors-origin';
|
||||||
|
|
||||||
|
describe('CORS origin resolution', () => {
|
||||||
|
it('allows Cloudflare Pages preview origins in dev and staging', () => {
|
||||||
|
const origin = 'https://807e0ea6.lolympus.pages.dev';
|
||||||
|
|
||||||
|
expect(isAllowedCorsOrigin(origin, 'dev')).toBe(true);
|
||||||
|
expect(isAllowedCorsOrigin(origin, 'staging')).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not allow Cloudflare Pages preview origins in prod', () => {
|
||||||
|
expect(
|
||||||
|
isAllowedCorsOrigin('https://807e0ea6.lolympus.pages.dev', 'prod'),
|
||||||
|
).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects similar but unsafe Pages origins', () => {
|
||||||
|
expect(
|
||||||
|
isAllowedCorsOrigin('http://807e0ea6.lolympus.pages.dev', 'staging'),
|
||||||
|
).toBe(false);
|
||||||
|
expect(isAllowedCorsOrigin('https://lolympus.pages.dev', 'staging')).toBe(
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
isAllowedCorsOrigin('https://a.b.lolympus.pages.dev', 'staging'),
|
||||||
|
).toBe(false);
|
||||||
|
expect(
|
||||||
|
isAllowedCorsOrigin(
|
||||||
|
'https://807e0ea6.lolympus.pages.dev.evil.com',
|
||||||
|
'staging',
|
||||||
|
),
|
||||||
|
).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps configured web origins allowed', () => {
|
||||||
|
expect(
|
||||||
|
isAllowedCorsOrigin('https://example.com', 'prod', [
|
||||||
|
'https://example.com',
|
||||||
|
]),
|
||||||
|
).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('falls back to default web origins when WEB_ORIGIN is empty', () => {
|
||||||
|
expect(resolveWebOrigins('')).toContain('http://localhost:5173');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('creates a Nest CORS callback from the same rules', (done) => {
|
||||||
|
const corsOrigin = createCorsOrigin('staging');
|
||||||
|
|
||||||
|
expect(corsOrigin).not.toBe(true);
|
||||||
|
if (corsOrigin === true) return;
|
||||||
|
|
||||||
|
corsOrigin('https://807e0ea6.lolympus.pages.dev', (error, allow) => {
|
||||||
|
expect(error).toBeNull();
|
||||||
|
expect(allow).toBe(true);
|
||||||
|
done();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps dev CORS permissive for local development', () => {
|
||||||
|
expect(createCorsOrigin('dev')).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
import type { CustomOrigin } from '@nestjs/common/interfaces/external/cors-options.interface';
|
||||||
|
|
||||||
|
const DEFAULT_WEB_ORIGINS = [
|
||||||
|
'http://localhost:5173',
|
||||||
|
'http://126.dahyeon.us:5173',
|
||||||
|
'https://lolympus.dahyeon.us',
|
||||||
|
];
|
||||||
|
|
||||||
|
const PAGES_DEV_ORIGIN_HOST_PATTERN =
|
||||||
|
/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.lolympus\.pages\.dev$/i;
|
||||||
|
|
||||||
|
const PAGES_DEV_CORS_ENVIRONMENTS = new Set(['dev', 'staging']);
|
||||||
|
|
||||||
|
function parseOrigin(origin: string, allowPath: boolean): URL | null {
|
||||||
|
const trimmedOrigin = origin.trim();
|
||||||
|
if (trimmedOrigin.length === 0) return null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const url = new URL(trimmedOrigin);
|
||||||
|
if (
|
||||||
|
!allowPath &&
|
||||||
|
(url.pathname !== '/' || url.search !== '' || url.hash !== '')
|
||||||
|
) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return url;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeOrigin(origin: string, allowPath = false): string | null {
|
||||||
|
const url = parseOrigin(origin, allowPath);
|
||||||
|
if (!url) return null;
|
||||||
|
|
||||||
|
return `${url.protocol}//${url.host}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveWebOrigins(
|
||||||
|
webOrigin = process.env.WEB_ORIGIN,
|
||||||
|
): string[] {
|
||||||
|
const configuredOrigins = webOrigin
|
||||||
|
?.split(',')
|
||||||
|
.map((origin) => normalizeOrigin(origin, true))
|
||||||
|
.filter((origin): origin is string => origin !== null);
|
||||||
|
|
||||||
|
if (configuredOrigins && configuredOrigins.length > 0) {
|
||||||
|
return configuredOrigins;
|
||||||
|
}
|
||||||
|
|
||||||
|
return [...DEFAULT_WEB_ORIGINS];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isLolympusPagesDevOrigin(origin: string): boolean {
|
||||||
|
const url = parseOrigin(origin, false);
|
||||||
|
if (!url) return false;
|
||||||
|
|
||||||
|
return (
|
||||||
|
url.protocol === 'https:' &&
|
||||||
|
url.port === '' &&
|
||||||
|
PAGES_DEV_ORIGIN_HOST_PATTERN.test(url.hostname)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isAllowedCorsOrigin(
|
||||||
|
requestOrigin: string | undefined,
|
||||||
|
nodeEnv = process.env.NODE_ENV,
|
||||||
|
webOrigins = resolveWebOrigins(),
|
||||||
|
): boolean {
|
||||||
|
if (!requestOrigin) return false;
|
||||||
|
|
||||||
|
const normalizedRequestOrigin = normalizeOrigin(requestOrigin);
|
||||||
|
if (!normalizedRequestOrigin) return false;
|
||||||
|
|
||||||
|
const normalizedWebOrigins = webOrigins
|
||||||
|
.map((origin) => normalizeOrigin(origin, true))
|
||||||
|
.filter((origin): origin is string => origin !== null);
|
||||||
|
|
||||||
|
if (normalizedWebOrigins.includes(normalizedRequestOrigin)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
PAGES_DEV_CORS_ENVIRONMENTS.has(nodeEnv ?? '') &&
|
||||||
|
isLolympusPagesDevOrigin(requestOrigin)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createCorsOrigin(
|
||||||
|
nodeEnv = process.env.NODE_ENV,
|
||||||
|
webOrigin = process.env.WEB_ORIGIN,
|
||||||
|
): true | CustomOrigin {
|
||||||
|
if (nodeEnv === 'dev') return true;
|
||||||
|
|
||||||
|
const webOrigins = resolveWebOrigins(webOrigin);
|
||||||
|
|
||||||
|
return (requestOrigin, callback) => {
|
||||||
|
callback(null, isAllowedCorsOrigin(requestOrigin, nodeEnv, webOrigins));
|
||||||
|
};
|
||||||
|
}
|
||||||
+5
-10
@@ -1,23 +1,18 @@
|
|||||||
import { ValidationPipe } from '@nestjs/common';
|
import { ValidationPipe } from '@nestjs/common';
|
||||||
import { NestFactory } from '@nestjs/core';
|
import { NestFactory } from '@nestjs/core';
|
||||||
import { AppModule } from './app.module';
|
import { AppModule } from './app.module';
|
||||||
|
import { createCorsOrigin } from './cors-origin';
|
||||||
|
|
||||||
async function bootstrap() {
|
async function bootstrap() {
|
||||||
const app = await NestFactory.create(AppModule, {
|
const app = await NestFactory.create(AppModule, {
|
||||||
rawBody: true,
|
rawBody: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
const isDev = process.env.NODE_ENV === 'dev';
|
const nodeEnv = process.env.NODE_ENV;
|
||||||
const webOrigins = process.env.WEB_ORIGIN?.split(',').map((origin) =>
|
const isDev = nodeEnv === 'dev';
|
||||||
origin.trim(),
|
|
||||||
) ?? [
|
|
||||||
'http://localhost:5173',
|
|
||||||
'http://126.dahyeon.us:5173',
|
|
||||||
'https://lolympus.dahyeon.us',
|
|
||||||
];
|
|
||||||
|
|
||||||
app.enableCors({
|
app.enableCors({
|
||||||
origin: isDev ? true : webOrigins,
|
origin: createCorsOrigin(nodeEnv),
|
||||||
credentials: true,
|
credentials: true,
|
||||||
allowedHeaders: ['Authorization', 'Content-Type', 'X-Auth-User-Id'],
|
allowedHeaders: ['Authorization', 'Content-Type', 'X-Auth-User-Id'],
|
||||||
});
|
});
|
||||||
@@ -31,4 +26,4 @@ async function bootstrap() {
|
|||||||
);
|
);
|
||||||
await app.listen(isDev ? 3000 : 10712);
|
await app.listen(isDev ? 3000 : 10712);
|
||||||
}
|
}
|
||||||
bootstrap();
|
void bootstrap();
|
||||||
@@ -97,6 +97,10 @@ describe('DakaoPublisher', () => {
|
|||||||
eventSource: 'lolympus',
|
eventSource: 'lolympus',
|
||||||
type: 'chat.send-message',
|
type: 'chat.send-message',
|
||||||
correlationId: 'chat-log-1',
|
correlationId: 'chat-log-1',
|
||||||
|
resultSubjects: {
|
||||||
|
succeeded: 'staging.lolympus.dakao.chat.send-message.succeeded.v1',
|
||||||
|
failed: 'staging.lolympus.dakao.chat.send-message.failed.v1',
|
||||||
|
},
|
||||||
});
|
});
|
||||||
expect(getPublishedEnvelope(outboxService)).not.toHaveProperty(
|
expect(getPublishedEnvelope(outboxService)).not.toHaveProperty(
|
||||||
'replySubject',
|
'replySubject',
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { randomUUID } from 'crypto';
|
|||||||
import { SecretService } from '../global/secret/secret.service';
|
import { SecretService } from '../global/secret/secret.service';
|
||||||
import {
|
import {
|
||||||
DakaoCommandEnvelope,
|
DakaoCommandEnvelope,
|
||||||
|
DakaoResultSubjects,
|
||||||
DakaoSegment,
|
DakaoSegment,
|
||||||
DakaoSendMessagePayload,
|
DakaoSendMessagePayload,
|
||||||
} from './dakao.types';
|
} from './dakao.types';
|
||||||
@@ -16,7 +17,12 @@ const EVENT_SOURCE_DEFAULT = 'lolympus';
|
|||||||
@Injectable()
|
@Injectable()
|
||||||
export class DakaoPublisher implements OnModuleInit {
|
export class DakaoPublisher implements OnModuleInit {
|
||||||
private readonly logger = new Logger(DakaoPublisher.name);
|
private readonly logger = new Logger(DakaoPublisher.name);
|
||||||
private sendMessageSubject = resolveDakaoNatsNames().subjects.chatSendMessage;
|
private readonly names = resolveDakaoNatsNames();
|
||||||
|
private sendMessageSubject = this.names.subjects.chatSendMessage;
|
||||||
|
private resultSubjects: DakaoResultSubjects = {
|
||||||
|
succeeded: this.names.subjects.chatSendMessageSucceeded,
|
||||||
|
failed: this.names.subjects.chatSendMessageFailed,
|
||||||
|
};
|
||||||
private eventSource = EVENT_SOURCE_DEFAULT;
|
private eventSource = EVENT_SOURCE_DEFAULT;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
@@ -35,6 +41,10 @@ export class DakaoPublisher implements OnModuleInit {
|
|||||||
|
|
||||||
this.sendMessageSubject =
|
this.sendMessageSubject =
|
||||||
sendOverride || resolveDakaoNatsNames().subjects.chatSendMessage;
|
sendOverride || resolveDakaoNatsNames().subjects.chatSendMessage;
|
||||||
|
this.resultSubjects = {
|
||||||
|
succeeded: this.names.subjects.chatSendMessageSucceeded,
|
||||||
|
failed: this.names.subjects.chatSendMessageFailed,
|
||||||
|
};
|
||||||
this.eventSource = sourceOverride || EVENT_SOURCE_DEFAULT;
|
this.eventSource = sourceOverride || EVENT_SOURCE_DEFAULT;
|
||||||
|
|
||||||
this.logger.log(
|
this.logger.log(
|
||||||
@@ -63,6 +73,7 @@ export class DakaoPublisher implements OnModuleInit {
|
|||||||
type: 'chat.send-message',
|
type: 'chat.send-message',
|
||||||
eventSource: this.eventSource,
|
eventSource: this.eventSource,
|
||||||
correlationId: params.correlationId,
|
correlationId: params.correlationId,
|
||||||
|
resultSubjects: this.resultSubjects,
|
||||||
payload,
|
payload,
|
||||||
};
|
};
|
||||||
await this.outboxService.enqueueAndPublish({
|
await this.outboxService.enqueueAndPublish({
|
||||||
|
|||||||
@@ -75,12 +75,18 @@ export interface DakaoSendMessagePayload {
|
|||||||
silence?: boolean;
|
silence?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface DakaoResultSubjects {
|
||||||
|
succeeded: string;
|
||||||
|
failed: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface DakaoCommandEnvelope<TPayload> {
|
export interface DakaoCommandEnvelope<TPayload> {
|
||||||
schema: 'dakao.command.v1';
|
schema: 'dakao.command.v1';
|
||||||
eventId: string;
|
eventId: string;
|
||||||
type: string;
|
type: string;
|
||||||
eventSource: string;
|
eventSource: string;
|
||||||
correlationId?: string;
|
correlationId?: string;
|
||||||
|
resultSubjects?: DakaoResultSubjects;
|
||||||
payload: TPayload;
|
payload: TPayload;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
VITE_API_BASE_URL=https://lolympus-staging-api.dahyeon.us
|
VITE_API_BASE_URL=https://lolympus-api-staging.dahyeon.us
|
||||||
VITE_DEFAULT_COMMUNITY_ID=69ebe0adf627c11be2f020a1
|
VITE_DEFAULT_COMMUNITY_ID=69ebe0adf627c11be2f020a1
|
||||||
VITE_MSAL_CLIENT_ID=15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3
|
VITE_MSAL_CLIENT_ID=15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3
|
||||||
VITE_MSAL_AUTHORITY=https://login.microsoftonline.com/5ef88004-e953-4b04-93db-64bbf49c6863
|
VITE_MSAL_AUTHORITY=https://login.microsoftonline.com/5ef88004-e953-4b04-93db-64bbf49c6863
|
||||||
|
|||||||
+22
-22
@@ -1,22 +1,22 @@
|
|||||||
import { BrowserRouter, Link, Route, Routes } from 'react-router';
|
import { BrowserRouter, Link, Route, Routes } from "react-router";
|
||||||
import { useMsal } from '@azure/msal-react';
|
import { useMsal } from "@azure/msal-react";
|
||||||
import DevAuthSwitcher from './components/DevAuthSwitcher';
|
import DevAuthSwitcher from "./components/DevAuthSwitcher";
|
||||||
import { DEFAULT_COMMUNITY_ID } from './config';
|
import { DEFAULT_COMMUNITY_ID } from "./config";
|
||||||
import { useCommunity } from './api/hooks';
|
import { useCommunity } from "./api/hooks";
|
||||||
import { isMsalConfigured } from './lib/auth/msal.config';
|
import { isMsalConfigured } from "./lib/auth/msal.config";
|
||||||
import AuthCallbackPage from './pages/AuthCallback';
|
import AuthCallbackPage from "./pages/AuthCallback";
|
||||||
import HomePage from './pages/HomePage';
|
import HomePage from "./pages/HomePage";
|
||||||
import LoginPage from './pages/Login';
|
import LoginPage from "./pages/Login";
|
||||||
import MatchDetailPage from './pages/MatchDetailPage';
|
import MatchDetailPage from "./pages/MatchDetailPage";
|
||||||
import MatchTeamProgressPage from './pages/MatchTeamProgressPage';
|
import MatchTeamProgressPage from "./pages/MatchTeamProgressPage";
|
||||||
import AuctionPage from './pages/AuctionPage';
|
import AuctionPage from "./pages/AuctionPage";
|
||||||
import UserHistoryPage from './pages/UserHistoryPage';
|
import UserHistoryPage from "./pages/UserHistoryPage";
|
||||||
import CommunityInternalStatsPage from './pages/CommunityInternalStatsPage';
|
import CommunityInternalStatsPage from "./pages/CommunityInternalStatsPage";
|
||||||
import InternalMatchDetailPage from './pages/InternalMatchDetailPage';
|
import InternalMatchDetailPage from "./pages/InternalMatchDetailPage";
|
||||||
import LegacyImportPage from './pages/admin/LegacyImportPage';
|
import LegacyImportPage from "./pages/admin/LegacyImportPage";
|
||||||
import LegacyMatchesPage from './pages/admin/LegacyMatchesPage';
|
import LegacyMatchesPage from "./pages/admin/LegacyMatchesPage";
|
||||||
import MatchAdminPage from './pages/admin/MatchAdminPage';
|
import MatchAdminPage from "./pages/admin/MatchAdminPage";
|
||||||
import TournamentCodesPage from './pages/admin/TournamentCodesPage';
|
import TournamentCodesPage from "./pages/admin/TournamentCodesPage";
|
||||||
|
|
||||||
function MsalHeaderActions() {
|
function MsalHeaderActions() {
|
||||||
const { accounts, instance } = useMsal();
|
const { accounts, instance } = useMsal();
|
||||||
@@ -43,7 +43,7 @@ function MsalHeaderActions() {
|
|||||||
|
|
||||||
function App() {
|
function App() {
|
||||||
const communityQuery = useCommunity(DEFAULT_COMMUNITY_ID);
|
const communityQuery = useCommunity(DEFAULT_COMMUNITY_ID);
|
||||||
const communityLabel = communityQuery.data?.name ?? 'LOLYMPUS';
|
const communityLabel = communityQuery.data?.name ?? "LOLYMPUS";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<BrowserRouter>
|
<BrowserRouter>
|
||||||
@@ -57,7 +57,7 @@ function App() {
|
|||||||
{communityLabel}
|
{communityLabel}
|
||||||
</Link>
|
</Link>
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
{DEFAULT_COMMUNITY_ID ? (
|
{/* {DEFAULT_COMMUNITY_ID ? (
|
||||||
<span className="text-[10px] uppercase tracking-wider text-base-content/25">
|
<span className="text-[10px] uppercase tracking-wider text-base-content/25">
|
||||||
API Live
|
API Live
|
||||||
</span>
|
</span>
|
||||||
@@ -65,7 +65,7 @@ function App() {
|
|||||||
<span className="text-[10px] uppercase tracking-wider text-amber-500/70">
|
<span className="text-[10px] uppercase tracking-wider text-amber-500/70">
|
||||||
Set `VITE_DEFAULT_COMMUNITY_ID`
|
Set `VITE_DEFAULT_COMMUNITY_ID`
|
||||||
</span>
|
</span>
|
||||||
)}
|
)} */}
|
||||||
{isMsalConfigured && <MsalHeaderActions />}
|
{isMsalConfigured && <MsalHeaderActions />}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -3,43 +3,159 @@ import { existsSync, readFileSync } from "node:fs";
|
|||||||
import { dirname, resolve } from "node:path";
|
import { dirname, resolve } from "node:path";
|
||||||
import { fileURLToPath } from "node:url";
|
import { fileURLToPath } from "node:url";
|
||||||
|
|
||||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
const scriptPath = fileURLToPath(import.meta.url);
|
||||||
|
const __dirname = dirname(scriptPath);
|
||||||
const repoRoot = resolve(__dirname, "..");
|
const repoRoot = resolve(__dirname, "..");
|
||||||
const webDir = resolve(repoRoot, "apps/web");
|
const webDir = resolve(repoRoot, "apps/web");
|
||||||
|
|
||||||
const target = process.argv[2];
|
if (process.argv[1] === scriptPath) {
|
||||||
if (target !== "staging" && target !== "prod") {
|
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 stagingBranch =
|
||||||
|
target === "staging" ? resolveStagingBranch(env) : undefined;
|
||||||
|
|
||||||
|
validateEnv(viteMode, env);
|
||||||
|
run("pnpm", ["--filter", "web", "run", `build:${target}`], repoRoot);
|
||||||
|
|
||||||
|
const deployArgs = [
|
||||||
|
"exec",
|
||||||
|
"wrangler",
|
||||||
|
"pages",
|
||||||
|
"deploy",
|
||||||
|
"dist",
|
||||||
|
"--project-name",
|
||||||
|
projectName,
|
||||||
|
];
|
||||||
|
|
||||||
|
if (target === "staging") {
|
||||||
|
deployArgs.push("--branch", stagingBranch);
|
||||||
|
console.error(
|
||||||
|
`Deploying staging to Cloudflare Pages branch ${stagingBranch}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
run("pnpm", deployArgs, webDir);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveStagingBranch(env = process.env) {
|
||||||
|
const configuredBranch = env.CF_PAGES_STAGING_BRANCH?.trim();
|
||||||
|
if (configuredBranch) return configuredBranch;
|
||||||
|
|
||||||
|
refreshRemoteReleaseBranches();
|
||||||
|
|
||||||
|
const latestReleaseBranch = selectLatestReleaseBranch(
|
||||||
|
listReleaseBranchRefs(),
|
||||||
|
);
|
||||||
|
if (latestReleaseBranch) return latestReleaseBranch;
|
||||||
|
|
||||||
console.error(
|
console.error(
|
||||||
"Usage: node scripts/deploy-cloudflare-pages.mjs <staging|prod>",
|
[
|
||||||
|
"No release/* branch found for staging deploy.",
|
||||||
|
"Create a release branch, for example: git push origin main:release/66",
|
||||||
|
"Or set CF_PAGES_STAGING_BRANCH explicitly.",
|
||||||
|
].join("\n"),
|
||||||
);
|
);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
const viteMode = target === "prod" ? "production" : "staging";
|
export function selectLatestReleaseBranch(refRows) {
|
||||||
const projectName =
|
const latestByBranch = new Map();
|
||||||
process.env.CF_PAGES_PROJECT_NAME ??
|
|
||||||
process.env.CLOUDFLARE_PAGES_PROJECT_NAME ??
|
|
||||||
"lolympus";
|
|
||||||
const stagingBranch = process.env.CF_PAGES_STAGING_BRANCH ?? "staging";
|
|
||||||
|
|
||||||
validateEnv(viteMode);
|
for (const row of refRows) {
|
||||||
run("pnpm", ["--filter", "web", "run", `build:${target}`], repoRoot);
|
const [timestampText, refName] = row.split("\t");
|
||||||
|
const branch = normalizeReleaseBranch(refName);
|
||||||
|
const timestamp = Number(timestampText);
|
||||||
|
if (!branch || !Number.isFinite(timestamp)) continue;
|
||||||
|
|
||||||
const deployArgs = [
|
const current = latestByBranch.get(branch);
|
||||||
"exec",
|
if (!current || timestamp > current.timestamp) {
|
||||||
"wrangler",
|
latestByBranch.set(branch, { branch, timestamp });
|
||||||
"pages",
|
}
|
||||||
"deploy",
|
}
|
||||||
"dist",
|
|
||||||
"--project-name",
|
|
||||||
projectName,
|
|
||||||
];
|
|
||||||
|
|
||||||
if (target === "staging") {
|
const [latest] = [...latestByBranch.values()].sort((left, right) => {
|
||||||
deployArgs.push("--branch", stagingBranch);
|
if (left.timestamp !== right.timestamp) {
|
||||||
|
return right.timestamp - left.timestamp;
|
||||||
|
}
|
||||||
|
return right.branch.localeCompare(left.branch, "en", { numeric: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
return latest?.branch;
|
||||||
}
|
}
|
||||||
|
|
||||||
run("pnpm", deployArgs, webDir);
|
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) {
|
function run(command, args, cwd) {
|
||||||
const result = spawnSync(command, args, {
|
const result = spawnSync(command, args, {
|
||||||
@@ -52,7 +168,7 @@ function run(command, args, cwd) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function validateEnv(mode) {
|
function validateEnv(mode, env) {
|
||||||
const fileEnv = [
|
const fileEnv = [
|
||||||
".env",
|
".env",
|
||||||
".env.local",
|
".env.local",
|
||||||
@@ -72,7 +188,7 @@ function validateEnv(mode) {
|
|||||||
"VITE_MSAL_REDIRECT_URI",
|
"VITE_MSAL_REDIRECT_URI",
|
||||||
];
|
];
|
||||||
const missing = requiredKeys.filter((key) => {
|
const missing = requiredKeys.filter((key) => {
|
||||||
const value = process.env[key] ?? fileEnv[key];
|
const value = env[key] ?? fileEnv[key];
|
||||||
return !value || value.includes("<");
|
return !value || value.includes("<");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user