활성 모듈/플러그인마다 프론트엔드 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/*)
## 버전
- 코어 7.0.1 → 7.0.2 bump. 7.0.1 이 이미 2026-07-03 공개 릴리스이므로 그 위 신규
기능은 +1 bump(new-bump). config/app.php(SSoT) + .env{.example,.testing.example,
.testing} + README 뱃지 + INSTALL 예시 + 루트 CHANGELOG 신규 [7.0.2] 섹션 동기화.
- 확장 g7_version 상향 안 함(>=7.0.0 유지) — 6개 프론트 에셋 확장이 신규 코어
표면을 자기 코드에서 호출하지 않고 개별 서빙 라우트 존치+프론트 폴백으로 코어
7.0.0 에서도 동작 → 실제 의존 없음( 결정).
- 부수 결함 수정: config/app.php 편집으로 활성화된 core-update-targets-coverage
룰이 v1.51.0 에서 추가된 vite.config.{editor,devtools}.js 가 app.update.targets
에 미등재됨을 검출 → 추가. 코어 업데이트 시 편집기/devtools 빌드 설정 갱신 누락
방지(CHANGELOG [7.0.2] Fixed).
## 규정/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.2] Added/Fixed / 엔진 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 판정을 강제(이번 초기 누락 재발 방지)
308 lines
11 KiB
PHP
308 lines
11 KiB
PHP
<?php
|
|
|
|
namespace Tests\Unit\Services;
|
|
|
|
use App\Extension\ModuleManager;
|
|
use App\Extension\PluginManager;
|
|
use App\Services\ExtensionBundleService;
|
|
use Illuminate\Support\Facades\File;
|
|
use Mockery;
|
|
use Tests\TestCase;
|
|
|
|
/**
|
|
* ExtensionBundleService 단위 테스트
|
|
*
|
|
* 활성 확장 IIFE/CSS 의 priority 정렬, `\n;\n` 구분자 병합, sourceMappingURL
|
|
* 처리, 확장별 fault tolerance, 캐시 파일 생성/정리를 검증한다.
|
|
*/
|
|
class ExtensionBundleServiceTest extends TestCase
|
|
{
|
|
private string $fixtureDir;
|
|
|
|
private ModuleManager $moduleManager;
|
|
|
|
private PluginManager $pluginManager;
|
|
|
|
protected function setUp(): void
|
|
{
|
|
parent::setUp();
|
|
|
|
$this->fixtureDir = storage_path('framework/testing/ext-bundle-fixtures');
|
|
File::ensureDirectoryExists($this->fixtureDir);
|
|
|
|
$this->moduleManager = Mockery::mock(ModuleManager::class);
|
|
$this->pluginManager = Mockery::mock(PluginManager::class);
|
|
|
|
// 번들 캐시 디렉토리 초기화 (테스트 격리)
|
|
$bundleDir = storage_path('app/ext-bundles');
|
|
if (is_dir($bundleDir)) {
|
|
foreach (glob($bundleDir.'/*.{js,css}', GLOB_BRACE) as $f) {
|
|
@unlink($f);
|
|
}
|
|
}
|
|
}
|
|
|
|
protected function tearDown(): void
|
|
{
|
|
if (is_dir($this->fixtureDir)) {
|
|
foreach (glob($this->fixtureDir.'/*') as $f) {
|
|
@unlink($f);
|
|
}
|
|
@rmdir($this->fixtureDir);
|
|
}
|
|
|
|
$bundleDir = storage_path('app/ext-bundles');
|
|
if (is_dir($bundleDir)) {
|
|
foreach (glob($bundleDir.'/*.{js,css}', GLOB_BRACE) as $f) {
|
|
@unlink($f);
|
|
}
|
|
}
|
|
|
|
Mockery::close();
|
|
parent::tearDown();
|
|
}
|
|
|
|
/**
|
|
* 지정 내용으로 fixture 에셋 파일을 만들고 절대 경로를 반환한다.
|
|
*/
|
|
private function writeFixture(string $name, string $content): string
|
|
{
|
|
$path = $this->fixtureDir.'/'.$name;
|
|
File::put($path, $content);
|
|
|
|
return $path;
|
|
}
|
|
|
|
/**
|
|
* hasAssets/getAssetLoadingConfig/getBuiltAssetAbsolutePaths/getIdentifier 를
|
|
* 노출하는 가짜 확장 인스턴스를 만든다.
|
|
*/
|
|
private function fakeExtension(string $identifier, int $priority, ?string $jsPath, ?string $cssPath, string $strategy = 'global'): object
|
|
{
|
|
$ext = Mockery::mock();
|
|
$ext->shouldReceive('hasAssets')->andReturn(true);
|
|
$ext->shouldReceive('getIdentifier')->andReturn($identifier);
|
|
$ext->shouldReceive('getAssetLoadingConfig')->andReturn([
|
|
'strategy' => $strategy,
|
|
'priority' => $priority,
|
|
'dependencies' => [],
|
|
]);
|
|
|
|
$paths = [];
|
|
if ($jsPath !== null) {
|
|
$paths['js'] = $jsPath;
|
|
}
|
|
if ($cssPath !== null) {
|
|
$paths['css'] = $cssPath;
|
|
}
|
|
$ext->shouldReceive('getBuiltAssetAbsolutePaths')->andReturn($paths);
|
|
|
|
return $ext;
|
|
}
|
|
|
|
private function service(): ExtensionBundleService
|
|
{
|
|
return new ExtensionBundleService($this->moduleManager, $this->pluginManager);
|
|
}
|
|
|
|
public function test_orders_global_assets_by_priority_ascending(): void
|
|
{
|
|
$a = $this->writeFixture('a.js', '(function(){})()');
|
|
$b = $this->writeFixture('b.js', '(function(){})()');
|
|
$c = $this->writeFixture('c.js', '(function(){})()');
|
|
|
|
$this->moduleManager->shouldReceive('getActiveModules')->andReturn([
|
|
'ext-c' => $this->fakeExtension('ext-c', 30, $c, null),
|
|
'ext-a' => $this->fakeExtension('ext-a', 10, $a, null),
|
|
'ext-b' => $this->fakeExtension('ext-b', 20, $b, null),
|
|
]);
|
|
|
|
$ordered = $this->service()->getOrderedGlobalAssetPaths('module');
|
|
|
|
$this->assertSame(['ext-a', 'ext-b', 'ext-c'], array_keys($ordered));
|
|
}
|
|
|
|
public function test_skips_non_global_strategy(): void
|
|
{
|
|
$g = $this->writeFixture('g.js', '(function(){})()');
|
|
$l = $this->writeFixture('l.js', '(function(){})()');
|
|
|
|
$this->moduleManager->shouldReceive('getActiveModules')->andReturn([
|
|
'ext-global' => $this->fakeExtension('ext-global', 100, $g, null, 'global'),
|
|
'ext-layout' => $this->fakeExtension('ext-layout', 100, $l, null, 'layout'),
|
|
]);
|
|
|
|
$ordered = $this->service()->getOrderedGlobalAssetPaths('module');
|
|
|
|
$this->assertArrayHasKey('ext-global', $ordered);
|
|
$this->assertArrayNotHasKey('ext-layout', $ordered);
|
|
}
|
|
|
|
public function test_js_bundle_joins_iife_with_semicolon_newline_separator(): void
|
|
{
|
|
// 세미콜론 없이 끝나는 IIFE 2개 (ecommerce 형태)
|
|
$a = $this->writeFixture('a.js', '(function(){window.A=1})()');
|
|
$b = $this->writeFixture('b.js', '(function(){window.B=2})()');
|
|
|
|
$this->moduleManager->shouldReceive('getActiveModules')->andReturn([
|
|
'ext-a' => $this->fakeExtension('ext-a', 10, $a, null),
|
|
'ext-b' => $this->fakeExtension('ext-b', 20, $b, null),
|
|
]);
|
|
|
|
$js = $this->service()->buildJsBundle('module');
|
|
|
|
// 두 IIFE 가 모두 포함되고 `\n;\n` 구분자로 구분
|
|
$this->assertStringContainsString('window.A=1', $js);
|
|
$this->assertStringContainsString('window.B=2', $js);
|
|
$this->assertStringContainsString("\n;\n", $js);
|
|
// priority 순서 (a 가 b 보다 먼저)
|
|
$this->assertLessThan(strpos($js, 'window.B=2'), strpos($js, 'window.A=1'));
|
|
}
|
|
|
|
public function test_prod_strips_source_mapping_url(): void
|
|
{
|
|
$this->app['env'] = 'production';
|
|
app()->detectEnvironment(fn () => 'production');
|
|
|
|
$a = $this->writeFixture('a.js', "(function(){})()\n//# sourceMappingURL=a.js.map");
|
|
|
|
$this->moduleManager->shouldReceive('getActiveModules')->andReturn([
|
|
'ext-a' => $this->fakeExtension('ext-a', 10, $a, null),
|
|
]);
|
|
|
|
$js = $this->service()->buildJsBundle('module');
|
|
|
|
$this->assertStringNotContainsString('sourceMappingURL', $js);
|
|
}
|
|
|
|
public function test_dev_rewrites_source_mapping_url_to_asset_serving_path(): void
|
|
{
|
|
// 기본 testing 환경 = 비프로덕션 → dev rewrite 경로
|
|
$a = $this->writeFixture('a.js', "(function(){})()\n//# sourceMappingURL=a.js.map");
|
|
|
|
$this->moduleManager->shouldReceive('getActiveModules')->andReturn([
|
|
'ext-a' => $this->fakeExtension('ext-a', 10, $a, null),
|
|
]);
|
|
|
|
$js = $this->service()->buildJsBundle('module');
|
|
|
|
$this->assertStringContainsString('sourceMappingURL=/api/modules/assets/ext-a/dist/js/a.js.map', $js);
|
|
}
|
|
|
|
public function test_per_extension_fault_tolerance_skips_missing_file(): void
|
|
{
|
|
$good = $this->writeFixture('good.js', '(function(){window.GOOD=1})()');
|
|
$missing = $this->fixtureDir.'/does-not-exist.js';
|
|
|
|
$this->moduleManager->shouldReceive('getActiveModules')->andReturn([
|
|
'ext-missing' => $this->fakeExtension('ext-missing', 10, $missing, null),
|
|
'ext-good' => $this->fakeExtension('ext-good', 20, $good, null),
|
|
]);
|
|
|
|
$js = $this->service()->buildJsBundle('module');
|
|
|
|
// 없는 파일은 skip, 정상 확장은 여전히 포함 (번들 전체 붕괴 안 함)
|
|
$this->assertStringContainsString('window.GOOD=1', $js);
|
|
}
|
|
|
|
public function test_css_with_relative_url_is_excluded(): void
|
|
{
|
|
$safe = $this->writeFixture('safe.css', '.a{color:red}');
|
|
$relative = $this->writeFixture('rel.css', '.b{background:url(./img/x.png)}');
|
|
|
|
$this->moduleManager->shouldReceive('getActiveModules')->andReturn([
|
|
'ext-safe' => $this->fakeExtension('ext-safe', 10, null, $safe),
|
|
'ext-rel' => $this->fakeExtension('ext-rel', 20, null, $relative),
|
|
]);
|
|
|
|
$css = $this->service()->buildCssBundle('module');
|
|
|
|
$this->assertStringContainsString('.a{color:red}', $css);
|
|
$this->assertStringNotContainsString('url(./img/x.png)', $css);
|
|
}
|
|
|
|
public function test_empty_bundle_returns_empty_path(): void
|
|
{
|
|
$this->moduleManager->shouldReceive('getActiveModules')->andReturn([]);
|
|
|
|
$path = $this->service()->getBundleFilePath('module', 'js', 12345);
|
|
|
|
$this->assertSame('', $path);
|
|
}
|
|
|
|
public function test_prod_writes_versioned_cache_file_and_reuses_it(): void
|
|
{
|
|
$this->app['env'] = 'production';
|
|
app()->detectEnvironment(fn () => 'production');
|
|
|
|
$a = $this->writeFixture('a.js', '(function(){window.A=1})()');
|
|
// getActiveModules 는 두 번 호출될 수 있으므로 안정적으로 반환
|
|
$this->moduleManager->shouldReceive('getActiveModules')->andReturn([
|
|
'ext-a' => $this->fakeExtension('ext-a', 10, $a, null),
|
|
]);
|
|
|
|
$svc = $this->service();
|
|
$path1 = $svc->getBundleFilePath('module', 'js', 999);
|
|
|
|
$this->assertNotSame('', $path1);
|
|
$this->assertFileExists($path1);
|
|
$this->assertStringContainsString('module.999.js', $path1);
|
|
|
|
// 같은 version 재요청 → 동일 파일 (캐시 히트)
|
|
$path2 = $svc->getBundleFilePath('module', 'js', 999);
|
|
$this->assertSame($path1, $path2);
|
|
}
|
|
|
|
public function test_cleanup_removes_stale_version_bundles_only(): void
|
|
{
|
|
$bundleDir = storage_path('app/ext-bundles');
|
|
File::ensureDirectoryExists($bundleDir);
|
|
File::put($bundleDir.'/module.100.js', 'old');
|
|
File::put($bundleDir.'/module.200.js', 'current');
|
|
File::put($bundleDir.'/plugin.100.css', 'old');
|
|
|
|
$this->moduleManager->shouldReceive('getActiveModules')->andReturn([]);
|
|
|
|
$deleted = $this->service()->cleanupStaleBundles(200);
|
|
|
|
// version 200 외 파일만 삭제 (module.100.js, plugin.100.css = 2건)
|
|
$this->assertSame(2, $deleted);
|
|
$this->assertFileExists($bundleDir.'/module.200.js');
|
|
$this->assertFileDoesNotExist($bundleDir.'/module.100.js');
|
|
$this->assertFileDoesNotExist($bundleDir.'/plugin.100.css');
|
|
}
|
|
|
|
public function test_clear_bundles_by_type(): void
|
|
{
|
|
$bundleDir = storage_path('app/ext-bundles');
|
|
File::ensureDirectoryExists($bundleDir);
|
|
File::put($bundleDir.'/module.100.js', 'm');
|
|
File::put($bundleDir.'/plugin.100.js', 'p');
|
|
|
|
$deleted = $this->service()->clearBundles('module');
|
|
|
|
$this->assertSame(1, $deleted);
|
|
$this->assertFileDoesNotExist($bundleDir.'/module.100.js');
|
|
$this->assertFileExists($bundleDir.'/plugin.100.js');
|
|
}
|
|
|
|
public function test_plugin_bundle_orders_by_priority_gdpr_first_when_lowest(): void
|
|
{
|
|
// gdpr 가 priority 50 으로 최상단(제약 1 회귀 가드) — 이름 하드코딩 아닌 선언 결과
|
|
$gdpr = $this->writeFixture('gdpr.js', '(function(){window.GDPR=1})()');
|
|
$other = $this->writeFixture('other.js', '(function(){window.OTHER=1})()');
|
|
|
|
$this->pluginManager->shouldReceive('getActivePlugins')->andReturn([
|
|
'sirsoft-other' => $this->fakeExtension('sirsoft-other', 100, $other, null),
|
|
'sirsoft-gdpr' => $this->fakeExtension('sirsoft-gdpr', 50, $gdpr, null),
|
|
]);
|
|
|
|
$ordered = $this->service()->getOrderedGlobalAssetPaths('plugin');
|
|
|
|
$this->assertSame('sirsoft-gdpr', array_key_first($ordered));
|
|
|
|
$js = $this->service()->buildJsBundle('plugin');
|
|
$this->assertLessThan(strpos($js, 'window.OTHER=1'), strpos($js, 'window.GDPR=1'));
|
|
}
|
|
}
|