feat(core): 모듈/플러그인 프론트엔드 에셋 서버측 번들 병합

활성 모듈/플러그인마다 프론트엔드 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 판정을 강제(이번 초기 누락 재발 방지)
This commit is contained in:
HeuJung committed 2026-07-04 22:19:55 +09:00
1 parent 7c18adc09d
commit f267f21ea6
35 files changed
+1754 -53

No files matched your search

+43 -20
View File
@@ -26,7 +26,7 @@ import { getErrorHandlingResolver } from './error';
import type { ErrorHandlingMap } from './types/ErrorHandling';
import { createLogger, Logger } from './utils/Logger';
import { webSocketManager } from './websocket/WebSocketManager';
import { getModuleAssetLoader, parseModuleAssetsFromConfig, parsePluginAssetsFromConfig } from './modules';
import { getModuleAssetLoader, parseModuleAssetsFromConfig, parsePluginAssetsFromConfig, parseBundleUrlsFromConfig } from './modules';
import { SystemBannerManager } from './template-engine/SystemBannerManager';
/**
* DevTools 추적 - G7DevToolsCore.getInstance() 직접 호출 대신 G7Core.devTools를 사용합니다.
@@ -722,41 +722,64 @@ export class TemplateApp {
}
/**
* 모듈/플러그인 에셋 로드
* 모듈/플러그인 에셋 로드 (서버측 병합 번들)
*
* window.G7Config.moduleAssets 및 pluginAssets에서 에셋 정보를 읽어
* 동적으로 JS/CSS를 로드합니다.
* window.G7Config.bundleUrls 에서 병합 번들 URL 을 읽어 모듈 번들 →
* 플러그인 번들 순으로 로드한다. 각 번들은 활성 확장 IIFE 를 priority 순으로
* 이어붙인 단일 파일이며, 로드 즉시 각 IIFE 가 자가등록(핸들러/리스너)을
* 실행한다. 개별 로딩(loadActiveExtensionAssets)과 실행 계약은 동일하다.
*
* 모듈 JS는 IIFE 형태로 빌드되어 로드 즉시 initModule()이 실행되고,
* ActionDispatcher에 핸들러가 등록됩니다.
* 모듈 → 플러그인 순서를 유지하는 이유: gdpr preblocker 등 인터셉터가
* 플러그인 번들 내 priority 최상단으로 오되 모듈보다는 뒤에 실행된다
* (2번들 구조). bundleUrls 가 없으면(구버전 blade) 개별 로딩으로 폴백한다.
*
* @since engine-v1.52.0 (서버측 번들 로딩으로 전환)
*/
private async loadExtensionAssets(): Promise<void> {
try {
const moduleAssetLoader = getModuleAssetLoader();
const bundleUrls = parseBundleUrlsFromConfig();
// 모듈 에셋 로드
const moduleAssets = parseModuleAssetsFromConfig();
if (moduleAssets.length > 0) {
logger.log('Loading module assets:', moduleAssets.map(m => m.identifier));
await moduleAssetLoader.loadActiveExtensionAssets(moduleAssets);
// bundleUrls 부재 시 개별 로딩 폴백 (회귀 안전)
if (!bundleUrls) {
await this.loadExtensionAssetsIndividually();
return;
}
// 플러그인 에셋 로드
const pluginAssets = parsePluginAssetsFromConfig();
if (pluginAssets.length > 0) {
logger.log('Loading plugin assets:', pluginAssets.map(p => p.identifier));
await moduleAssetLoader.loadActiveExtensionAssets(pluginAssets);
}
// 모듈 번들 → 플러그인 번들 순서 (gdpr 는 플러그인 번들 내 최상단)
await moduleAssetLoader.loadBundle('module', bundleUrls.moduleJs, bundleUrls.moduleCss);
await moduleAssetLoader.loadBundle('plugin', bundleUrls.pluginJs, bundleUrls.pluginCss);
if (moduleAssets.length > 0 || pluginAssets.length > 0) {
logger.log('Extension assets loaded successfully');
}
logger.log('Extension bundle assets loaded successfully');
} catch (error) {
// 에셋 로드 실패는 경고만 출력하고 앱 계속 진행
logger.warn('Failed to load extension assets:', error);
}
}
/**
* 개별 확장 에셋 로드 (bundleUrls 부재 시 폴백)
*
* window.G7Config.moduleAssets/pluginAssets 에서 확장별 개별 URL 을 읽어
* priority 순으로 각각 로드한다. 서버측 번들이 준비되지 않은 구버전 blade
* 환경 회귀 안전용.
*/
private async loadExtensionAssetsIndividually(): Promise<void> {
const moduleAssetLoader = getModuleAssetLoader();
const moduleAssets = parseModuleAssetsFromConfig();
if (moduleAssets.length > 0) {
logger.log('Loading module assets (individual fallback):', moduleAssets.map(m => m.identifier));
await moduleAssetLoader.loadActiveExtensionAssets(moduleAssets);
}
const pluginAssets = parsePluginAssetsFromConfig();
if (pluginAssets.length > 0) {
logger.log('Loading plugin assets (individual fallback):', pluginAssets.map(p => p.identifier));
await moduleAssetLoader.loadActiveExtensionAssets(pluginAssets);
}
}
/**
* 라우트 변경 핸들러
*/
@@ -96,6 +96,121 @@ export class ModuleAssetLoader {
logger.log('All module assets loaded successfully');
}
/**
* 서버측에서 병합된 확장 번들(JS/CSS)을 로드합니다.
*
* 활성 모듈/플러그인 IIFE 를 priority 순으로 이어붙인 단일 파일을 하나의
* `<script async=false>` 로, CSS 는 하나의 `<link>` 로 append 한다. 개별
* 로딩과 달리 확장 수와 무관하게 요청 1(+1)건으로 끝난다. `<script async=false>`
* 는 번들 내부 물리 순서로 실행되므로 병합 시 priority 정렬이 곧 실행 순서다.
*
* 중복 append 가드 — 같은 key(module/plugin) 는 최초 1회만 로드한다.
*
* @param key 번들 구분 키 (예: 'module' | 'plugin')
* @param jsUrl 병합 JS URL (없으면 스킵)
* @param cssUrl 병합 CSS URL (없으면 스킵)
* @since engine-v1.52.0
*/
async loadBundle(key: string, jsUrl?: string | null, cssUrl?: string | null): Promise<void> {
const promises: Promise<void>[] = [];
if (cssUrl) {
promises.push(this.loadBundleCss(key, cssUrl));
}
if (jsUrl) {
promises.push(this.loadBundleJs(key, jsUrl));
}
if (promises.length === 0) {
logger.log(`No bundle assets to load for: ${key}`);
return;
}
await Promise.all(promises);
}
/**
* 병합 CSS 번들을 단일 `<link>` 로 로드합니다(중복 가드).
*
* @param key 번들 구분 키
* @param url 병합 CSS URL
*/
private async loadBundleCss(key: string, url: string): Promise<void> {
const elementId = `ext-bundle-css-${key}`;
if (document.getElementById(elementId)) {
logger.log(`Bundle CSS already loaded: ${key}`);
return;
}
return new Promise<void>((resolve) => {
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = url;
link.id = elementId;
link.onload = () => {
logger.log(`Bundle CSS loaded: ${key}`);
this.registerLoadedAsset(`bundle-${key}`, { type: 'css', element: link });
resolve();
};
link.onerror = () => {
logger.warn(`Failed to load bundle CSS: ${key} (${url})`);
resolve();
};
document.head.appendChild(link);
});
}
/**
* 병합 JS 번들을 단일 `<script async=false>` 로 로드합니다(중복 가드).
*
* @param key 번들 구분 키
* @param url 병합 JS URL
*/
private async loadBundleJs(key: string, url: string): Promise<void> {
const elementId = `ext-bundle-js-${key}`;
if (document.getElementById(elementId)) {
logger.log(`Bundle JS already loaded: ${key}`);
return;
}
const existingPromise = this.loadingPromises.get(elementId);
if (existingPromise) {
logger.log(`Bundle JS already loading: ${key}`);
return existingPromise;
}
const loadPromise = new Promise<void>((resolve) => {
const script = document.createElement('script');
script.src = url;
script.id = elementId;
script.async = false; // 번들 내부 물리 순서로 실행 보장
script.onload = () => {
logger.log(`Bundle JS loaded: ${key}`);
this.registerLoadedAsset(`bundle-${key}`, { type: 'js', element: script });
this.loadingPromises.delete(elementId);
resolve();
};
script.onerror = () => {
logger.warn(`Failed to load bundle JS: ${key} (${url})`);
this.loadingPromises.delete(elementId);
resolve();
};
document.head.appendChild(script);
});
this.loadingPromises.set(elementId, loadPromise);
return loadPromise;
}
/**
* CSS 파일을 동적으로 로드합니다.
*
@@ -306,6 +421,42 @@ export function parseModuleAssetsFromConfig(): ModuleAsset[] {
return moduleAssets;
}
/**
* 확장 병합 번들 URL 정보 인터페이스
*/
export interface ExtensionBundleUrls {
/** 모듈 병합 JS 번들 URL */
moduleJs?: string | null;
/** 모듈 병합 CSS 번들 URL */
moduleCss?: string | null;
/** 플러그인 병합 JS 번들 URL */
pluginJs?: string | null;
/** 플러그인 병합 CSS 번들 URL */
pluginCss?: string | null;
}
/**
* window.G7Config.bundleUrls 에서 병합 번들 URL 을 파싱합니다.
*
* 활성 global 에셋이 없는 타입은 서버가 null 을 내려주므로, 프론트는 해당
* 번들 로드를 스킵한다. bundleUrls 자체가 없으면(구버전 blade 등) null 반환.
*
* @returns 번들 URL 객체 또는 null
* @since engine-v1.52.0
*/
export function parseBundleUrlsFromConfig(): ExtensionBundleUrls | null {
if (typeof window === 'undefined') {
return null;
}
const g7Config = (window as any).G7Config;
if (!g7Config?.bundleUrls) {
return null;
}
return g7Config.bundleUrls as ExtensionBundleUrls;
}
/**
* 플러그인 에셋을 파싱합니다.
*
@@ -18,7 +18,7 @@ describe('ModuleAssetLoader', () => {
afterEach(() => {
vi.restoreAllMocks();
document.head.querySelectorAll('[id^="module-js-"],[id^="module-css-"]')
document.head.querySelectorAll('[id^="module-js-"],[id^="module-css-"],[id^="ext-bundle-js-"],[id^="ext-bundle-css-"]')
.forEach(el => el.remove());
});
@@ -165,4 +165,110 @@ describe('ModuleAssetLoader', () => {
await expect(loader.loadActiveExtensionAssets([])).resolves.toBeUndefined();
});
});
describe('loadBundle (서버측 병합 번들)', () => {
it('단일 script + 단일 link 를 1개씩만 append 한다', async () => {
const scriptAppends: string[] = [];
const linkAppends: string[] = [];
const appendSpy = vi.spyOn(document.head, 'appendChild').mockImplementation(((node: any) => {
if (node.tagName === 'SCRIPT') {
scriptAppends.push(node.id);
queueMicrotask(() => node.onload?.());
} else if (node.tagName === 'LINK') {
linkAppends.push(node.id);
queueMicrotask(() => node.onload?.());
}
return node;
}) as any);
await loader.loadBundle('module', '/api/modules/bundle.js?v=1', '/api/modules/bundle.css?v=1');
expect(scriptAppends).toEqual(['ext-bundle-js-module']);
expect(linkAppends).toEqual(['ext-bundle-css-module']);
appendSpy.mockRestore();
});
it('번들 script 는 async=false 여야 한다 (내부 순서 실행 보장)', async () => {
const created: HTMLScriptElement[] = [];
const appendSpy = vi.spyOn(document.head, 'appendChild').mockImplementation(((node: any) => {
if (node.tagName === 'SCRIPT') {
created.push(node);
queueMicrotask(() => node.onload?.());
}
return node;
}) as any);
await loader.loadBundle('plugin', '/api/plugins/bundle.js?v=1', null);
expect(created).toHaveLength(1);
expect(created[0].async).toBe(false);
appendSpy.mockRestore();
});
it('같은 key 를 중복 로드하지 않는다 (중복 가드)', async () => {
let scriptCount = 0;
// 실제 DOM 에 삽입해 element id 가 등록되어야 getElementById 중복 가드가 동작
const appendSpy = vi.spyOn(document.head, 'appendChild').mockImplementation(((node: any) => {
if (node.tagName === 'SCRIPT') {
scriptCount++;
queueMicrotask(() => node.onload?.());
}
// jsdom 실제 삽입 (id 등록 → 두 번째 호출 시 getElementById 가 찾아 중복 방지)
Node.prototype.appendChild.call(document.head, node);
return node;
}) as any);
await loader.loadBundle('module', '/api/modules/bundle.js?v=1', null);
await loader.loadBundle('module', '/api/modules/bundle.js?v=1', null);
expect(scriptCount).toBe(1);
appendSpy.mockRestore();
});
it('jsUrl/cssUrl 모두 null 이면 no-op', async () => {
const appendSpy = vi.spyOn(document.head, 'appendChild');
await expect(loader.loadBundle('module', null, null)).resolves.toBeUndefined();
expect(appendSpy).not.toHaveBeenCalled();
appendSpy.mockRestore();
});
});
describe('concat 자가등록 (IIFE 병합 계약)', () => {
it(';\\n 로 이어붙인 2개 IIFE 가 모두 실행되어 레지스트리에 자가등록된다', () => {
// 모의 IIFE 2개 — ecommerce IIFE 처럼 세미콜론 없이 끝나도 `\n;\n` 구분자로 ASI 경계 보호
const registry: Record<string, unknown> = {};
(globalThis as any).__G7TestRegistry = registry;
const iifeA = `(function(){"use strict";globalThis.__G7TestRegistry["mod-a"]={handler:"mod-a.doThing"}})()`;
// 세미콜론 없이 끝나는 IIFE (sourceMappingURL 주석 strip 후 형태)
const iifeB = `(function(){"use strict";globalThis.__G7TestRegistry["mod-b"]={handler:"mod-b.doThing"}})()`;
const bundle = [iifeA, iifeB].join('\n;\n');
// 번들 실행 (단일 <script> 실행 시뮬레이션)
// eslint-disable-next-line no-new-func
new Function(bundle)();
expect(registry['mod-a']).toEqual({ handler: 'mod-a.doThing' });
expect(registry['mod-b']).toEqual({ handler: 'mod-b.doThing' });
// 핸들러 네임스페이스 격리 — 각 확장 prefix
expect((registry['mod-a'] as any).handler).toContain('mod-a.');
expect((registry['mod-b'] as any).handler).toContain('mod-b.');
delete (globalThis as any).__G7TestRegistry;
});
it('구분자 없이 이어붙이면 ASI 경계가 깨진다 (구분자 필요성 회귀 가드)', () => {
// 세미콜론 없이 끝나는 IIFE 뒤에 즉시 다음 IIFE 를 붙이면 파싱 에러
const iifeA = `(function(){return 1})()`;
const iifeB = `(function(){return 2})()`;
// 구분자 없는 병합 → `()()(function...` 형태로 호출 연쇄 파싱 (런타임 에러)
expect(() => new Function(iifeA + '\n' + iifeB)()).toThrow();
// 구분자 있는 병합 → 정상
expect(() => new Function(iifeA + '\n;\n' + iifeB)()).not.toThrow();
});
});
});
+2 -1
View File
@@ -7,6 +7,7 @@ export {
getModuleAssetLoader,
parseModuleAssetsFromConfig,
parsePluginAssetsFromConfig,
parseBundleUrlsFromConfig,
} from './ModuleAssetLoader';
export type { ModuleAsset, ExternalScript } from './ModuleAssetLoader';
export type { ModuleAsset, ExternalScript, ExtensionBundleUrls } from './ModuleAssetLoader';
@@ -5,6 +5,19 @@
>
> 형식: [Keep a Changelog](https://keepachangelog.com/ko/1.1.0/)
## [engine-v1.52.0] - 2026-07-04
### Added
#### 확장 프론트엔드 에셋 서버측 번들 로딩
- `TemplateApp.loadExtensionAssets()` — 활성 모듈/플러그인 에셋을 확장별 개별 로딩에서 **서버측 병합 번들 로딩**으로 전환한다. `window.G7Config.bundleUrls`(blade 주입)를 읽어 `ModuleAssetLoader.loadBundle('module', ...)` → `loadBundle('plugin', ...)` 순으로 종류별 1개 번들만 로드한다. 확장 IIFE 자가등록 계약(핸들러/리스너/preblocker)은 priority 순 물리 병합으로 실행 순서가 보존되어 그대로 동작한다. `bundleUrls` 부재 시(구버전 blade) 기존 개별 로딩(`loadExtensionAssetsIndividually`)으로 폴백한다.
- `ModuleAssetLoader.loadBundle(key, jsUrl?, cssUrl?)`(신규) — 병합 번들을 단일 `<script async=false>` + 단일 `<link>` 로 append 하고 key(module/plugin)별 중복 로드를 가드한다. `<script async=false>` 로 번들 내부 물리 순서(=priority 정렬)가 곧 실행 순서다.
- `ModuleAssetLoader.parseBundleUrlsFromConfig()` + `ExtensionBundleUrls` 타입(신규) — `G7Config.bundleUrls` 파서. 활성 global 에셋이 없는 타입은 서버가 null 을 내려주어 프론트가 로드를 스킵한다.
- 기존 `loadActiveExtensionAssets`/`parse{Module,Plugin}AssetsFromConfig` 는 폴백 경로로 유지(dead-but-tested).
> 코어 측 번들 병합 서비스(`ExtensionBundleService`)·서빙 엔드포인트·캐시 정책은 루트 CHANGELOG [7.0.1] 및 `docs/extension/module-assets.md` "서버측 번들 병합" 참조.
## [engine-v1.51.0] - 2026-07-03
### Changed
+1
View File
@@ -39,6 +39,7 @@
modules: @json($moduleSettings ?? []),
moduleAssets: @json($moduleAssets ?? []),
pluginAssets: @json($pluginAssets ?? []),
bundleUrls: @json($bundleUrls ?? null),
activeModules: @json($activeModulesMeta ?? []),
activePlugins: @json($activePluginsMeta ?? []),
appConfig: @json($appConfig ?? []),
+1
View File
@@ -39,6 +39,7 @@
modules: @json($moduleSettings ?? []),
moduleAssets: @json($moduleAssets ?? []),
pluginAssets: @json($pluginAssets ?? []),
bundleUrls: @json($bundleUrls ?? null),
activeModules: @json($activeModulesMeta ?? []),
activePlugins: @json($activePluginsMeta ?? []),
appConfig: @json($appConfig ?? []),
+4
View File
@@ -870,6 +870,10 @@ if (isset($_GET['ajax_action'])) {
<span>레이아웃 미리보기 정리</span>
<span class="text-[10px] opacity-60">(layout-previews:cleanup)</span>
</button>
<button onclick="runCommand('ext-bundles:cleanup')" class="inline-flex items-center gap-1.5 px-3 py-2 bg-amber-600 hover:bg-amber-700 text-white text-xs font-medium rounded transition-colors">
<span>확장 번들 정리</span>
<span class="text-[10px] opacity-60">(ext-bundles:cleanup)</span>
</button>
<button onclick="runCommand('geoip:update')" class="inline-flex items-center gap-1.5 px-3 py-2 bg-blue-600 hover:bg-blue-700 text-white text-xs font-medium rounded transition-colors">
<span>GeoIP DB 갱신</span>
<span class="text-[10px] opacity-60">(geoip:update)</span>