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

@@ -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';