활성 모듈/플러그인마다 프론트엔드 IIFE JS·CSS 가 개별 HTTP 요청으로 로드되어
확장 수에 비례해 요청이 늘어나는 오버헤드를, 종류별 1개 번들로 서버 병합해 줄인다.
각 확장 IIFE 자가등록 계약(핸들러/리스너/preblocker)은 priority 순 물리 병합으로
실행 순서가 보존되어 그대로 동작한다.
## 백엔드
- 신규 ExtensionBundleService — 정렬(uasort priority)·필터(global)·concat(\n;\n
구분자로 ASI 경계 보호)·소스맵(prod strip / dev rewrite)·version-in-path 디스크
캐시·확장별 fine-grained try/catch(한 확장 실패가 번들 전체를 붕괴시키지 않음)
- AbstractModule/AbstractPlugin::getBuiltAssetAbsolutePaths — _bundled 경로
정확 해석용 절대경로 게터(getAssetFilePath 하드코딩 복제 회피)
- PublicModule/PluginController::serveBundle{Js,Css} + routes/api.php 4개
(/api/{modules,plugins}/bundle.{js,css}?v={version}, fileResponse ETag/304 재사용)
- config/filesystems.php ext-bundles 디스크 + storage/.gitignore + 루트 .gitignore
- 신규 ext-bundles:cleanup 커맨드 + {module,plugin,template}:cache-clear 번들
정리 통합 + dev-dashboard 버튼
## 프론트엔드 (engine-v1.52.0)
- TemplateApp.loadExtensionAssets — 개별 로딩 → bundleUrls 기반 모듈→플러그인
순 번들 로딩. bundleUrls 부재 시 개별 로딩 폴백(회귀 안전)
- ModuleAssetLoader.loadBundle + parseBundleUrlsFromConfig + ExtensionBundleUrls
- TemplateComposer/UserTemplateComposer bundleUrls 뷰변수 + app/admin.blade.php
- core:build 재빌드 산출물(public/build/core/*)
## 버전 동기화 판정 ( 결정)
코어 add-only(개별 서빙 라우트 존치 + 프론트 폴백). 6개 프론트 에셋 확장이 신규
코어 표면을 자기 코드에서 호출하지 않아 코어 7.0.0 에서도 동작 → 실제 의존 없음.
확장 g7_version 상향 안 함(>=7.0.0 유지). 코어 버전 무변경(7.0.1 accumulate).
## 규정/audit/문서/테스트
- ("확장 번들 병합" 절+파일유형표+E2E경로) / AGENTS.md /
docs/extension/module-assets.md / docs/cheatsheet.md
- coverage.json 4항목 + codified 룰 4종(url-same-origin, concat-separator,
asset-path-getter, clears-template-caches-no-file-delete)
- 루트 CHANGELOG [7.0.1] Added / 엔진 CHANGELOG engine-v1.52.0 Added
- Vitest 11(loadBundle + concat 자가등록) + PHPUnit 17(Service 12 + Feature 5)
+ Playwright spec + 시나리오 매니페스트
- 브라우저 실측(g7.dev): 홈/관리자 번들 각 1건·개별 iife 0건, gdpr 인터셉터
정상, 활성화 토글 반영, 장바구니→체크아웃·게시판 글쓰기 정상. g7_2.dev 미적용
대비 확장 요청 11~12→4건, DOMContentLoaded ~843~957→605~741ms(페이로드 무손실)
## 도구 보완
- pre-commit-review 스킬 에 엔진 경로 감지 게이트(5-pre + 보고 5e행) 신설 —
매핑 표에 엔진 파일이 있으면 엔진 CHANGELOG 판정을 강제(이번 초기 누락 재발 방지)
156 lines
5.9 KiB
PHP
156 lines
5.9 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers\Api\Public;
|
|
|
|
use App\Http\Controllers\Api\Base\PublicBaseController;
|
|
use App\Http\Requests\Public\Module\ServeModuleAssetRequest;
|
|
use App\Services\ExtensionBundleService;
|
|
use App\Services\ModuleService;
|
|
use Illuminate\Http\JsonResponse;
|
|
use Illuminate\Http\Response;
|
|
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
|
|
|
/**
|
|
* 공개 모듈 API 컨트롤러
|
|
*
|
|
* 모듈 에셋 서빙을 담당합니다.
|
|
*/
|
|
class PublicModuleController extends PublicBaseController
|
|
{
|
|
public function __construct(
|
|
private readonly ModuleService $moduleService,
|
|
private readonly ExtensionBundleService $bundleService
|
|
) {
|
|
parent::__construct();
|
|
}
|
|
|
|
/**
|
|
* 활성 모듈 프론트엔드 IIFE 병합 번들(JS)을 서빙합니다.
|
|
*
|
|
* 활성 global 모듈 에셋이 없으면 빈 200 응답(text/javascript)을 반환한다
|
|
* (프론트는 빈 스크립트 로드로 무해). 그 외에는 병합 파일을 fileResponse 로
|
|
* 서빙(ETag/304/환경별 Cache-Control 재사용).
|
|
*
|
|
* @return BinaryFileResponse|Response 병합 JS 파일 응답 또는 빈 응답
|
|
*/
|
|
public function serveBundleJs(): BinaryFileResponse|Response
|
|
{
|
|
$this->logApiUsage('modules.bundle', ['kind' => 'js']);
|
|
|
|
$version = $this->bundleService->getCurrentVersion();
|
|
$path = $this->bundleService->getBundleFilePath('module', 'js', $version);
|
|
|
|
if ($path === '') {
|
|
return response('', 200)->header('Content-Type', 'text/javascript');
|
|
}
|
|
|
|
return $this->fileResponse($path, 'text/javascript', 31536000);
|
|
}
|
|
|
|
/**
|
|
* 활성 모듈 프론트엔드 병합 번들(CSS)을 서빙합니다.
|
|
*
|
|
* @return BinaryFileResponse|Response 병합 CSS 파일 응답 또는 빈 응답
|
|
*/
|
|
public function serveBundleCss(): BinaryFileResponse|Response
|
|
{
|
|
$this->logApiUsage('modules.bundle', ['kind' => 'css']);
|
|
|
|
$version = $this->bundleService->getCurrentVersion();
|
|
$path = $this->bundleService->getBundleFilePath('module', 'css', $version);
|
|
|
|
if ($path === '') {
|
|
return response('', 200)->header('Content-Type', 'text/css');
|
|
}
|
|
|
|
return $this->fileResponse($path, 'text/css', 31536000);
|
|
}
|
|
|
|
/**
|
|
* 모듈 에셋 서빙
|
|
*
|
|
* @param ServeModuleAssetRequest $request 검증된 요청 (경로, 확장자 검증 완료)
|
|
* @param string $identifier 모듈 식별자 (vendor-module 형식)
|
|
* @param string $path 에셋 경로 (dist/js/module.iife.js 등)
|
|
* @return BinaryFileResponse|JsonResponse|Response 파일 응답 또는 에러 응답
|
|
*/
|
|
public function serveAsset(
|
|
ServeModuleAssetRequest $request,
|
|
string $identifier,
|
|
string $path
|
|
): BinaryFileResponse|JsonResponse|Response {
|
|
// FormRequest에서 이미 보안 검증 완료
|
|
// API 사용량 기록
|
|
$this->logApiUsage('modules.assets', ['identifier' => $identifier, 'path' => $path]);
|
|
|
|
// Service에서 파일 경로 조회 (검증은 FormRequest에서 완료됨)
|
|
$result = $this->moduleService->getAssetFilePath($identifier, $path);
|
|
|
|
// 에러 처리
|
|
if (! $result['success']) {
|
|
return match ($result['error']) {
|
|
'module_not_found' => $this->notFound(__('modules.errors.not_found', ['module' => $identifier])),
|
|
'file_not_found' => $this->notFound(__('modules.errors.file_not_found')),
|
|
'file_type_not_allowed' => $this->forbidden(__('modules.errors.file_type_not_allowed')),
|
|
default => $this->error(__('modules.errors.unknown_error'), 500),
|
|
};
|
|
}
|
|
|
|
// 파일 반환 (ETag 및 환경별 캐싱 헤더 포함, 1년 캐시)
|
|
return $this->fileResponse($result['filePath'], $result['mimeType'], 31536000);
|
|
}
|
|
|
|
/**
|
|
* 모듈 편집기 스펙 조회 — editor-spec.json 반환
|
|
*
|
|
* 활성 모듈만 대상으로 하며, 활성 디렉토리 → _bundled 폴백 순으로 읽어
|
|
* 템플릿 serveEditorSpec 과 동일한 응답 형태(`data.spec`)로 반환한다.
|
|
* 비활성/미존재 모듈은 404. 파일 미작성은 spec=null 정상 응답.
|
|
*
|
|
* @param string $identifier 모듈 식별자 (vendor-module 형식)
|
|
* @return JsonResponse 편집기 스펙 응답
|
|
*/
|
|
public function serveEditorSpec(string $identifier): JsonResponse
|
|
{
|
|
$this->logApiUsage('modules.editor_spec', ['identifier' => $identifier]);
|
|
|
|
$result = $this->moduleService->getEditorSpec($identifier);
|
|
|
|
if (! $result['success']) {
|
|
return $this->notFound(__('modules.errors.not_found', ['module' => $identifier]));
|
|
}
|
|
|
|
$message = $result['spec'] === null
|
|
? __('templates.messages.editor_spec_empty')
|
|
: __('templates.messages.editor_spec_retrieved');
|
|
|
|
return $this->success($message, [
|
|
'identifier' => $identifier,
|
|
'spec' => $result['spec'],
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* 모듈 컴포넌트 정의 파일 서빙 — components.json 반환
|
|
*
|
|
* 편집 모드 부팅 시 ComponentRegistry 가 활성 확장 매니페스트를 네임스페이스
|
|
* 병합하기 위해 fetch 한다. 미생성(구버전 모듈) 시 빈 components 로
|
|
* 폴백한다(무손실 보존 디그레이드).
|
|
*
|
|
* @param string $identifier 모듈 식별자
|
|
* @return JsonResponse 컴포넌트 정의 응답
|
|
*/
|
|
public function serveComponents(string $identifier): JsonResponse
|
|
{
|
|
$this->logApiUsage('modules.components', ['identifier' => $identifier]);
|
|
|
|
$result = $this->moduleService->getComponents($identifier);
|
|
|
|
if (! $result['success']) {
|
|
return $this->notFound(__('modules.errors.not_found', ['module' => $identifier]));
|
|
}
|
|
|
|
return $this->cachedJsonResponse($result['components'] ?? new \stdClass, 3600);
|
|
}
|
|
}
|