공개 저장소 이슈 gnuboard/g7 (@bigmsg) 제보에서 출발한 작업이다. 브라우저가 화면을 그리려고 제3자 CDN 에 도달해야 하면, 그 도달 실패는 예외도 로그도 남기지 않고 화면 기능만 조용히 사라진다. 폐쇄망·방화벽·광고차단기에서 재현되는데 자체 서버 로그에는 흔적이 없어 운영자가 원인을 특정할 수 없다. 제보된 것은 편집기 하나였지만 같은 구조가 아이콘·글꼴·코드편집기·압축 라이브러리·설치 마법사·개발 대시보드에 똑같이 있었으므로, 번들 확장과 템플릿 전체를 자체 제공으로 옮겼다. 런타임에 외부로 나가는 것은 주소 검색 서비스 하나만 남았다. 자체 제공만으로는 부족하다 — 자기 서버에서 받는 파일도 실패할 수 있고, 종전에는 그 실패가 무음이었다. CSS 경로에 재시도 계층을 세우고(스크립트 경로와 동형), 서버가 HTML 에 직접 심는 externals 까지 실패를 붙잡아 안내 배너와 [다시 시도]로 표면화했다. 편집기·코드편집기는 확보 실패 시 평문 입력으로 내려앉되 저장 계약을 유지한다. 두 번째 축은 운영자가 CSS 를 덧붙일 자리가 없던 문제다(sir.kr 문의). 확장 디렉토리의 custom/ 을 운영자 소유로 정해, 확장 교체가 그 디렉토리만은 보존하게 했다. 출처에 의존하지 않는 서술자로 해석하므로 나중에 다른 출처가 붙어도 소비자는 바뀌지 않는다. 확장 자산과 같은 메커니즘으로 정적 게시되어 CSS 내부 상대 url 도 해석되고, 파일을 고치면 그 변경을 감지해 재게시까지 예약된다. FTP 접근이 없는 운영자에게는 그 자리도 없는 것과 같으므로 레이아웃 편집기에서 직접 넣고 고칠 수 있게 했다. 모듈·플러그인·템플릿이 한 엔드포인트를 공유한다 — 타입별로 나누면 같은 검증이 세 벌로 갈리고 그중 약한 하나가 우회로가 된다. 여기서 올린 스크립트는 그 레이아웃 한 장이 아니라 사이트 전 화면에서 실행되므로 레이아웃 편집과 분리된 전용 권한으로 연다. 운영자 CSS 가 화면을 조작 불능으로 만들면 그것을 고칠 화면에도 같은 CSS 가 실려 스스로 갇히므로, 서버가 목록을 비우는 탈출구(?custom=off)를 함께 뒀다. 동봉 자산은 재생성 경로에 버전 대조 가드를 붙였다. 선언과 다른 버전을 버전 디렉토리에 써 넣는 조용한 거짓말은 배포된 뒤에는 드러나지 않는다.
363 lines
13 KiB
PHP
363 lines
13 KiB
PHP
<?php
|
|
|
|
namespace App\Console\Commands\Template;
|
|
|
|
use App\Console\Commands\Concerns\PrunesBuildOutput;
|
|
use App\Extension\TemplateManager;
|
|
use App\Extension\Traits\ClearsTemplateCaches;
|
|
use Illuminate\Console\Command;
|
|
use Illuminate\Support\Facades\Log;
|
|
use Symfony\Component\Process\Process;
|
|
|
|
class BuildTemplateCommand extends Command
|
|
{
|
|
use ClearsTemplateCaches;
|
|
use PrunesBuildOutput;
|
|
|
|
/**
|
|
* The name and signature of the console command.
|
|
*/
|
|
protected $signature = 'template:build
|
|
{identifier? : 빌드할 템플릿 식별자 (생략 시 --all 필요)}
|
|
{--all : 모든 템플릿 빌드}
|
|
{--watch : 파일 변경 감시 모드}
|
|
{--production : 프로덕션 빌드}
|
|
{--active : 활성 디렉토리에서 빌드}';
|
|
|
|
/**
|
|
* The console command description.
|
|
*/
|
|
protected $description = '템플릿의 프론트엔드 에셋을 빌드합니다 (기본: _bundled 디렉토리)';
|
|
|
|
/**
|
|
* 템플릿 관리자
|
|
*/
|
|
public function __construct(
|
|
private TemplateManager $templateManager
|
|
) {
|
|
parent::__construct();
|
|
}
|
|
|
|
/**
|
|
* Execute the console command.
|
|
*
|
|
* @return int 명령 실행 결과 코드
|
|
*/
|
|
public function handle(): int
|
|
{
|
|
$identifier = $this->argument('identifier');
|
|
$buildAll = $this->option('all');
|
|
$watchMode = $this->option('watch');
|
|
$productionMode = $this->option('production');
|
|
|
|
if (! $identifier && ! $buildAll) {
|
|
$this->error('❌ 템플릿 식별자를 지정하거나 --all 옵션을 사용하세요.');
|
|
$this->line('');
|
|
$this->line('사용법:');
|
|
$this->line(' php artisan template:build sirsoft-admin_basic');
|
|
$this->line(' php artisan template:build --all');
|
|
$this->line(' php artisan template:build sirsoft-admin_basic --watch');
|
|
$this->line(' php artisan template:build --all --production');
|
|
$this->line(' php artisan template:build sirsoft-admin_basic --active');
|
|
|
|
return Command::FAILURE;
|
|
}
|
|
|
|
try {
|
|
// 템플릿 로드
|
|
$this->templateManager->loadTemplates();
|
|
|
|
if ($buildAll) {
|
|
return $this->buildAllTemplates($productionMode);
|
|
}
|
|
|
|
return $this->buildTemplate($identifier, $watchMode, $productionMode);
|
|
} catch (\Exception $e) {
|
|
$this->error('❌ '.$e->getMessage());
|
|
Log::error('템플릿 빌드 실패', [
|
|
'template' => $identifier ?? 'all',
|
|
'error' => $e->getMessage(),
|
|
]);
|
|
|
|
return Command::FAILURE;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 빌드 대상 경로를 결정합니다.
|
|
*
|
|
* 기본값: _bundled 디렉토리. --active 옵션 시 활성 디렉토리.
|
|
* --watch 모드에서는 활성 디렉토리를 사용합니다 (실시간 개발용).
|
|
*
|
|
* @param string $identifier 템플릿 식별자
|
|
* @return array|null ['path' => string, 'source' => 'bundled'|'active'] 또는 null
|
|
*/
|
|
private function resolveBuildPath(string $identifier): ?array
|
|
{
|
|
$bundledPath = base_path("templates/_bundled/{$identifier}");
|
|
$activePath = base_path("templates/{$identifier}");
|
|
|
|
// --active 명시 → 활성 디렉토리
|
|
if ($this->option('active')) {
|
|
return is_dir($activePath)
|
|
? ['path' => $activePath, 'source' => 'active']
|
|
: null;
|
|
}
|
|
|
|
// --watch 모드 → 활성 디렉토리 (실시간 개발용)
|
|
if ($this->option('watch')) {
|
|
if (is_dir($activePath)) {
|
|
return ['path' => $activePath, 'source' => 'active'];
|
|
}
|
|
}
|
|
|
|
// 기본값: _bundled 우선
|
|
if (is_dir($bundledPath)) {
|
|
return ['path' => $bundledPath, 'source' => 'bundled'];
|
|
}
|
|
|
|
// _bundled에 없으면 활성 디렉토리 폴백
|
|
if (is_dir($activePath)) {
|
|
return ['path' => $activePath, 'source' => 'active'];
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
/**
|
|
* 단일 템플릿 빌드
|
|
*
|
|
* @param string $identifier 템플릿 식별자
|
|
* @param bool $watchMode 파일 감시 모드
|
|
* @param bool $productionMode 프로덕션 빌드
|
|
* @return int 명령 실행 결과 코드
|
|
*/
|
|
private function buildTemplate(string $identifier, bool $watchMode, bool $productionMode): int
|
|
{
|
|
// 경로 결정
|
|
$resolved = $this->resolveBuildPath($identifier);
|
|
if (! $resolved) {
|
|
$this->error("❌ 템플릿을 찾을 수 없습니다: {$identifier}");
|
|
$this->line(' _bundled 및 활성 디렉토리 모두 존재하지 않습니다.');
|
|
|
|
return Command::FAILURE;
|
|
}
|
|
|
|
$buildPath = $resolved['path'];
|
|
$source = $resolved['source'];
|
|
|
|
// 소스 표시
|
|
$sourceLabel = $source === 'bundled' ? '_bundled' : '활성';
|
|
$this->info("📂 빌드 소스: {$sourceLabel} ({$buildPath})");
|
|
|
|
// package.json 존재 확인
|
|
$packageJsonPath = $buildPath.'/package.json';
|
|
if (! file_exists($packageJsonPath)) {
|
|
$this->error('❌ package.json 파일이 없습니다: '.$packageJsonPath);
|
|
$this->line(' 템플릿 프론트엔드 구조를 먼저 생성하세요.');
|
|
|
|
return Command::FAILURE;
|
|
}
|
|
|
|
// node_modules 확인 및 설치
|
|
if (! is_dir($buildPath.'/node_modules')) {
|
|
$this->info('📦 의존성 설치 중...');
|
|
$installResult = $this->runNpmCommand(['npm', 'install'], $buildPath);
|
|
|
|
if ($installResult !== Command::SUCCESS) {
|
|
$this->error('❌ npm install 실패');
|
|
|
|
return Command::FAILURE;
|
|
}
|
|
}
|
|
|
|
// 빌드 명령 결정
|
|
$buildCommand = ['npm', 'run'];
|
|
|
|
if ($watchMode) {
|
|
$buildCommand[] = 'dev';
|
|
$this->info("👀 파일 감시 모드로 빌드 시작: {$identifier}");
|
|
$this->line(' Ctrl+C로 종료할 수 있습니다.');
|
|
} else {
|
|
$buildCommand[] = 'build';
|
|
$this->info("🔨 빌드 시작: {$identifier}".($productionMode ? ' (프로덕션)' : ''));
|
|
}
|
|
|
|
// 이전 산출물 정리 (동봉 vendor 는 보존 — vite emptyOutDir 대체)
|
|
if (! $watchMode) {
|
|
$removed = $this->pruneBuildOutput($buildPath);
|
|
|
|
if ($removed !== []) {
|
|
$this->line(' 🧹 이전 산출물 정리: '.implode(', ', $removed));
|
|
}
|
|
}
|
|
// 빌드 실행 (감시 모드에는 소스맵 억제를 주입하지 않는다 — 개발 중 디버깅 필요)
|
|
$result = $this->runNpmCommand(
|
|
$buildCommand,
|
|
$buildPath,
|
|
! $watchMode,
|
|
$watchMode ? [] : $this->buildEnv($productionMode)
|
|
);
|
|
|
|
if ($result === Command::SUCCESS && ! $watchMode) {
|
|
$this->info("✅ 빌드 완료: {$identifier}");
|
|
|
|
// 빌드 결과 파일 확인
|
|
$distPath = $buildPath.'/dist';
|
|
if (is_dir($distPath)) {
|
|
$this->line(' 빌드 결과:');
|
|
|
|
// JS 파일 확인
|
|
$jsFiles = glob($distPath.'/*.js');
|
|
foreach ($jsFiles as $jsFile) {
|
|
$fileName = basename($jsFile);
|
|
$fileSize = number_format(filesize($jsFile) / 1024, 2);
|
|
$this->line(" - {$fileName} ({$fileSize} KB)");
|
|
}
|
|
|
|
// CSS 파일 확인
|
|
$cssFiles = glob($distPath.'/*.css');
|
|
foreach ($cssFiles as $cssFile) {
|
|
$fileName = basename($cssFile);
|
|
$fileSize = number_format(filesize($cssFile) / 1024, 2);
|
|
$this->line(" - {$fileName} ({$fileSize} KB)");
|
|
}
|
|
}
|
|
|
|
// 캐시 버전 증가 (브라우저 캐시 무효화)
|
|
$this->incrementExtensionCacheVersion();
|
|
$this->line(' - 캐시 버전 갱신됨');
|
|
|
|
// _bundled 빌드 시 활성 반영 안내
|
|
if ($source === 'bundled') {
|
|
$this->line('');
|
|
$this->info("💡 활성 디렉토리에 반영하려면: php artisan template:update {$identifier}");
|
|
}
|
|
}
|
|
|
|
return $result;
|
|
}
|
|
|
|
/**
|
|
* 모든 템플릿 빌드
|
|
*
|
|
* @param bool $productionMode 프로덕션 빌드
|
|
* @return int 명령 실행 결과 코드
|
|
*/
|
|
private function buildAllTemplates(bool $productionMode): int
|
|
{
|
|
$buildTargets = [];
|
|
|
|
if ($this->option('active')) {
|
|
// --active: 활성 디렉토리만 대상
|
|
$templates = $this->templateManager->getAllTemplates();
|
|
foreach ($templates as $identifier => $template) {
|
|
$templatePath = base_path("templates/{$identifier}");
|
|
if (file_exists($templatePath.'/package.json')) {
|
|
$buildTargets[$identifier] = true;
|
|
}
|
|
}
|
|
} else {
|
|
// 기본값: _bundled 디렉토리 스캔
|
|
$bundledTemplates = $this->templateManager->getBundledTemplates();
|
|
foreach ($bundledTemplates as $identifier => $metadata) {
|
|
$bundledPath = $metadata['source_path'];
|
|
if (file_exists($bundledPath.'/package.json')) {
|
|
$buildTargets[$identifier] = true;
|
|
}
|
|
}
|
|
}
|
|
|
|
if (empty($buildTargets)) {
|
|
$this->warn('⚠️ 빌드할 템플릿이 없습니다.');
|
|
|
|
return Command::SUCCESS;
|
|
}
|
|
|
|
$sourceLabel = $this->option('active') ? '활성' : '_bundled';
|
|
$this->info("🔨 모든 템플릿 빌드 시작 ({$sourceLabel})".($productionMode ? ' (프로덕션)' : ''));
|
|
$this->line(' 대상 템플릿: '.implode(', ', array_keys($buildTargets)));
|
|
$this->line('');
|
|
|
|
$successCount = 0;
|
|
$failCount = 0;
|
|
|
|
foreach ($buildTargets as $identifier => $value) {
|
|
$this->line(" [{$identifier}]");
|
|
$result = $this->buildTemplate($identifier, false, $productionMode);
|
|
|
|
if ($result === Command::SUCCESS) {
|
|
$successCount++;
|
|
} else {
|
|
$failCount++;
|
|
}
|
|
|
|
$this->line('');
|
|
}
|
|
|
|
$this->info("📊 빌드 결과: 성공 {$successCount}개, 실패 {$failCount}개");
|
|
|
|
return $failCount > 0 ? Command::FAILURE : Command::SUCCESS;
|
|
}
|
|
|
|
/**
|
|
* 빌드 프로세스에 주입할 환경변수를 구성합니다.
|
|
*
|
|
* 프로덕션 빌드에서는 소스맵을 생성하지 않습니다. 배포 산출물에 원본 코드가
|
|
* 포함되는 것을 막기 위함이며, 각 vite config 가 이 값을 읽습니다.
|
|
*
|
|
* @param bool $productionMode 프로덕션 빌드 여부
|
|
* @return array<string, string> Process 에 주입할 환경변수
|
|
*/
|
|
private function buildEnv(bool $productionMode): array
|
|
{
|
|
return $productionMode ? ['G7_BUILD_SOURCEMAP' => '0'] : [];
|
|
}
|
|
|
|
/**
|
|
* npm 명령 실행
|
|
*
|
|
* @param array $command 실행할 명령
|
|
* @param string $cwd 작업 디렉토리
|
|
* @param bool $waitForCompletion 완료 대기 여부
|
|
* @param array<string, string> $env 추가로 주입할 환경변수 (부모 환경에 병합됨)
|
|
* @return int 명령 실행 결과 코드
|
|
*/
|
|
private function runNpmCommand(array $command, string $cwd, bool $waitForCompletion = true, array $env = []): int
|
|
{
|
|
// Windows 환경에서는 cmd /c 사용
|
|
if (PHP_OS_FAMILY === 'Windows') {
|
|
$command = array_merge(['cmd', '/c'], $command);
|
|
}
|
|
|
|
$process = new Process($command);
|
|
$process->setWorkingDirectory($cwd);
|
|
|
|
// Symfony Process 는 지정한 env 를 부모 환경에 병합하므로(PATH 등 유지) 추가분만 넘긴다.
|
|
if ($env !== []) {
|
|
$process->setEnv($env);
|
|
}
|
|
$process->setTimeout(null); // 타임아웃 없음
|
|
|
|
if ($waitForCompletion) {
|
|
$process->run(function ($type, $buffer) {
|
|
$this->output->write($buffer);
|
|
});
|
|
|
|
return $process->isSuccessful() ? Command::SUCCESS : Command::FAILURE;
|
|
}
|
|
|
|
// 감시 모드: 인터럽트까지 실행
|
|
$process->start(function ($type, $buffer) {
|
|
$this->output->write($buffer);
|
|
});
|
|
|
|
// 프로세스가 실행 중인 동안 대기
|
|
while ($process->isRunning()) {
|
|
usleep(100000); // 100ms
|
|
}
|
|
|
|
return Command::SUCCESS;
|
|
}
|
|
}
|