Files
Gnuboard7/resources/js/core/template-engine/ComponentRegistry.ts
T
HeuJung 15cd4452bf feat(core): 정적 최적화 서버 대응 자산 URL 이중 모드
nginx 의 정규식 location 은 프리픽스 location 보다 먼저 매칭되므로,
`location ~* \.(js|css|json)$` 블록이 있는 서버에서는 확장자 붙은 동적
엔드포인트가 `try_files ... /index.php` 폴백이 실행될 기회 없이 404 가 된다.
aaPanel/CyberPanel/Plesk 기본 템플릿에 들어있어 드물지 않으며, 관리자 화면조차
뜨지 않아 "서버 설정을 고치세요" 안내가 순환 참조가 된다.

관례를 깬 쪽이 G7 이므로 해소 책임도 G7 에 두고, 두 형태를 모두 서빙한 뒤
환경에 따라 택일한다. 확장자 형태는 영구 유지한다 — 제거하면 URL 을 하드코딩한
서드파티 확장이 깨진다.

- 라우트: dualSuffix / dualSuffixSegment / dualAsset 매크로로 23개 엔드포인트와
 프로브를 이중 등록. 확장자 형태를 먼저 등록한다 — 확장자 없는 쪽이 더 느슨한
 패턴이라 순서가 뒤집히면 `.json` 요청까지 삼킨다
- URL 생성: 서버 App\Support\AssetUrl, 프론트 core/support/assetUrl.ts 로 집약.
 기본 모드에서 생성 결과는 치환 이전과 문자열까지 동일하다 (쿼리 순서 포함 —
 순서가 바뀌면 의미는 같아도 HTTP 캐시 키가 갈린다)
- 자가 복구: 부트스트랩 자산 로드 실패 시 확장자 없는 형태로 1회 단방향 전환.
 역방향 금지 + 기존 재시도 예산 공유로 무한 왕복을 막는다
- 감지·전환: 인스톨러 프로브(설치 시 확정) / 관리자 환경설정 일반 탭 /
 g7:asset-url-mode. 판정은 상태코드가 아니라 매직 토큰 + Content-Type 으로 한다.
 상태코드만 보면 "404 대신 200 + 에러 HTML" 환경에서 영원히 오판한다
- 봇은 JavaScript 를 실행하지 않아 자가 복구가 닿지 않으므로, 모드 변경 시
 SEO 프리렌더 캐시를 비워 재생성시킨다

가드: audit 룰 2종(dynamic-route-static-extension / asset-url-builder-required),
Playwright 6건(정적 블록 가로채기 시뮬레이션), 루프 방지 불변식 L1~L9 전수 red 증명.

부수 정리: 양 Composer 에 중복돼 있던 확장 에셋 수집 123줄을 트레이트로 통합하고,
자산 확장자 화이트리스트 누락(.map)과 경로 정규화 우회 가능성을 함께 교정.

sir.kr 커뮤니티의 hang 님께서 제보해주셨습니다.
2026-07-23 11:34:32 +09:00

589 lines
16 KiB
TypeScript

/**
* ComponentRegistry.ts
*
* 템플릿 컴포넌트를 동적으로 로드하고 전역 레지스트리에 등록하는 클래스
*
* 역할:
* - /build/template/dist/components.js 동적 로딩
* - components.json 매니페스트 검증
* - 컴포넌트 타입별 분류 (basic, composite, layout)
* - 전역 레지스트리 관리 및 캐싱
*/
import React, { type ComponentType } from 'react';
import { createLogger } from '../utils/Logger';
import { fetchWithRetry } from './networkResilience';
import { suffixed } from '../support/assetUrl';
const logger = createLogger('ComponentRegistry');
/**
* 컴포넌트 타입 정의
*/
export type ComponentTypeEnum = 'basic' | 'composite' | 'layout';
/**
* 컴포넌트 메타데이터 인터페이스
*/
export interface ComponentMetadata {
/** 컴포넌트 이름 */
name: string;
/** 컴포넌트 타입 */
type: ComponentTypeEnum;
/** 컴포넌트 설명 */
description?: string;
/** 허용된 props 목록 */
props?: string[];
/** children 허용 여부 */
allowsChildren?: boolean;
/**
* 바인딩 처리를 건너뛸 props 키 목록
*
* 컴포넌트가 내부적으로 row/iteration 컨텍스트 등을 사용하여
* 자체적으로 바인딩을 처리해야 하는 props 키를 지정합니다.
*
* 예시: DataGrid는 ['cellChildren', 'expandChildren', 'expandContext', 'render']
*/
skipBindingKeys?: string[];
/**
* Form 자동 바인딩 시 boolean 값의 바인딩 타입
*
* - 'checked': 항상 checked prop으로 바인딩 (Toggle, Checkbox 등)
* - 'checkable': type이 checkbox/radio일 때만 checked, 그 외 value (Input)
* - 미지정: 항상 value prop으로 바인딩 (RadioGroup, Select 등 기본값)
*/
bindingType?: 'checked' | 'checkable';
}
/**
* components.json 매니페스트 스키마
*/
export interface ComponentManifest {
/** 매니페스트 버전 */
version: string;
/** 템플릿 식별자 */
templateId: string;
/** 컴포넌트 목록 */
components: {
/** 기본 컴포넌트 목록 */
basic: ComponentMetadata[];
/** 집합 컴포넌트 목록 */
composite: ComponentMetadata[];
/** 레이아웃 컴포넌트 목록 */
layout: ComponentMetadata[];
};
}
/**
* 레지스트리 맵 인터페이스
*/
export interface RegistryMap {
[componentName: string]: {
component: ComponentType<any>;
metadata: ComponentMetadata;
};
}
/**
* 로딩 상태 타입
*/
export type LoadingState = 'idle' | 'loading' | 'loaded' | 'error';
/**
* ComponentRegistry 에러 클래스
*/
export class ComponentRegistryError extends Error {
constructor(message: string, public code: string, public details?: any) {
super(message);
this.name = 'ComponentRegistryError';
}
}
/**
* ComponentRegistry 클래스
*
* 싱글톤 패턴으로 전역 컴포넌트 레지스트리 관리
*/
export class ComponentRegistry {
private static instance: ComponentRegistry | null = null;
/** 매니페스트 캐시 (템플릿별) */
private static manifestCache = new Map<string, ComponentManifest>();
/** 컴포넌트 레지스트리 맵 */
private registry: RegistryMap = {};
/** 컴포넌트 매니페스트 */
private manifest: ComponentManifest | null = null;
/** 로딩 상태 */
private loadingState: LoadingState = 'idle';
/** 에러 정보 */
private error: Error | null = null;
/** 템플릿 ID */
private templateId: string | null = null;
/** 템플릿 타입 (admin 또는 user) */
private templateType: string | null = null;
/**
* private 생성자 (싱글톤 패턴)
*/
private constructor() {}
/**
* 싱글톤 인스턴스 반환
*/
public static getInstance(): ComponentRegistry {
if (!ComponentRegistry.instance) {
ComponentRegistry.instance = new ComponentRegistry();
}
return ComponentRegistry.instance;
}
/**
* 격리 인스턴스 생성 — 싱글톤과 독립된 별도 ComponentRegistry.
*
* 레이아웃 편집기 캔버스 처럼 한 페이지에서 호스트 템플릿과
* 편집 대상 템플릿이 동시에 살아 있어야 하는 케이스용. 싱글톤을 점유 중인
* 호스트(`getInstance()`)의 등록 상태와 충돌하지 않도록, 격리 인스턴스는
* 정적 manifestCache 만 공유하고 registry/manifest/loadingState 는 자기
* 인스턴스 안에만 존재한다.
*
* `loadComponents()` 등 인스턴스 메서드는 싱글톤과 동일하게 사용 가능.
*
* @since engine-v1.50.0
*/
public static createIsolatedInstance(): ComponentRegistry {
return new ComponentRegistry();
}
/**
* 레지스트리 초기화 (테스트용)
*/
public static resetInstance(): void {
ComponentRegistry.instance = null;
}
/**
* 템플릿 컴포넌트 로드 및 등록
*
* @param templateId 템플릿 식별자
* @param templateType 템플릿 타입 (admin 또는 user)
*/
public async loadComponents(templateId: string, templateType: string): Promise<void> {
if (this.loadingState === 'loading') {
throw new ComponentRegistryError(
'Components are already being loaded',
'LOADING_IN_PROGRESS'
);
}
if (this.loadingState === 'loaded' && this.templateId === templateId && this.templateType === templateType) {
logger.log('Components already loaded for template:', templateId, templateType);
return;
}
this.loadingState = 'loading';
this.templateId = templateId;
this.templateType = templateType;
this.error = null;
try {
// 1. components.json 매니페스트 로드
await this.loadManifest();
// 2. 컴포넌트 번들 동적 import
await this.loadComponentBundle();
// 3. 로딩 완료
this.loadingState = 'loaded';
logger.log('Successfully loaded components:', Object.keys(this.registry).length);
} catch (error) {
this.loadingState = 'error';
this.error = error instanceof Error ? error : new Error(String(error));
throw new ComponentRegistryError(
`Failed to load components: ${this.error.message}`,
'LOAD_FAILED',
{ originalError: this.error }
);
}
}
/**
* components.json 매니페스트 로드 및 검증 (캐싱 지원)
*/
private async loadManifest(): Promise<void> {
try {
if (!this.templateId) {
throw new ComponentRegistryError(
'Template ID not set',
'TEMPLATE_ID_NOT_SET'
);
}
// 캐시 키 생성
const cacheKey = `${this.templateId}:${this.templateType}`;
// 캐시 확인
if (ComponentRegistry.manifestCache.has(cacheKey)) {
this.manifest = ComponentRegistry.manifestCache.get(cacheKey)!;
logger.log('Manifest loaded from cache:', this.manifest.templateId);
return;
}
// 캐시 미스 - API에서 로드
// 네트워크 일시 실패(응답 없음)에만 재시도. HTTP 에러는 아래 !ok 분기가 종전대로 처리.
// @since engine-v1.53.0
const manifestUrl = suffixed(`/api/templates/${this.templateId}/components`, 'json');
const response = await fetchWithRetry(manifestUrl, { label: 'components.json' });
if (!response.ok) {
throw new ComponentRegistryError(
`Failed to fetch manifest: ${response.status} ${response.statusText}`,
'MANIFEST_FETCH_FAILED',
{ status: response.status, statusText: response.statusText }
);
}
const manifest = await response.json();
// 매니페스트 검증
this.validateManifest(manifest);
this.manifest = manifest;
// 캐시에 저장
ComponentRegistry.manifestCache.set(cacheKey, manifest);
logger.log('Manifest loaded and cached:', manifest.templateId);
} catch (error) {
if (error instanceof ComponentRegistryError) {
throw error;
}
throw new ComponentRegistryError(
'Failed to load component manifest',
'MANIFEST_LOAD_FAILED',
{ originalError: error }
);
}
}
/**
* 매니페스트 검증
*/
private validateManifest(manifest: any): void {
// 필수 필드 검증
if (!manifest.version) {
throw new ComponentRegistryError(
'Manifest missing required field: version',
'MANIFEST_INVALID',
{ field: 'version' }
);
}
if (!manifest.templateId) {
throw new ComponentRegistryError(
'Manifest missing required field: templateId',
'MANIFEST_INVALID',
{ field: 'templateId' }
);
}
// 컴포넌트 객체 검증
if (!manifest.components || typeof manifest.components !== 'object') {
throw new ComponentRegistryError(
'Manifest missing required field: components',
'MANIFEST_INVALID',
{ field: 'components' }
);
}
// 컴포넌트 배열 검증
const componentTypes: ComponentTypeEnum[] = ['basic', 'composite', 'layout'];
for (const type of componentTypes) {
if (!Array.isArray(manifest.components[type])) {
throw new ComponentRegistryError(
`Manifest field 'components.${type}' must be an array`,
'MANIFEST_INVALID',
{ field: `components.${type}`, value: manifest.components[type] }
);
}
// 각 컴포넌트 메타데이터 검증
manifest.components[type].forEach((meta: any, index: number) => {
if (!meta.name || typeof meta.name !== 'string') {
throw new ComponentRegistryError(
`Invalid component metadata at ${type}[${index}]: missing or invalid 'name'`,
'MANIFEST_INVALID',
{ type, index, metadata: meta }
);
}
if (!meta.type || typeof meta.type !== 'string') {
throw new ComponentRegistryError(
`Invalid component metadata at ${type}[${index}]: missing or invalid 'type'`,
'MANIFEST_INVALID',
{ type, index, metadata: meta }
);
}
});
}
logger.log('Manifest validation passed');
}
/**
* 컴포넌트 번들에서 컴포넌트 가져오기
*
* admin.blade.php에서 이미 IIFE 번들을 로드했으므로,
* 전역 변수에서 컴포넌트를 가져옵니다 (HTTP 요청 불필요).
*/
private async loadComponentBundle(): Promise<void> {
try {
if (!this.templateId) {
throw new ComponentRegistryError(
'Template ID not set',
'TEMPLATE_ID_NOT_SET'
);
}
// 전역 객체에서 컴포넌트 가져오기
// admin.blade.php에서 이미 <script> 태그로 로드되어 전역 변수에 노출됨
const globalVarName = this.getGlobalVariableName();
const module = (window as any)[globalVarName];
if (!module || typeof module !== 'object') {
throw new ComponentRegistryError(
`Component bundle not loaded. Expected global variable: ${globalVarName}. ` +
`Ensure admin.blade.php includes the IIFE bundle script.`,
'BUNDLE_NOT_LOADED',
{ expectedVariable: globalVarName }
);
}
// 매니페스트의 모든 컴포넌트 등록
await this.registerComponentsFromManifest(module);
logger.log('Component bundle loaded from global variable:', globalVarName);
} catch (error) {
if (error instanceof ComponentRegistryError) {
throw error;
}
throw new ComponentRegistryError(
'Failed to load component bundle',
'BUNDLE_LOAD_FAILED',
{ originalError: error }
);
}
}
/**
* 템플릿 ID로부터 전역 변수명 생성
*/
private getGlobalVariableName(): string {
if (!this.templateId) {
throw new ComponentRegistryError(
'Template ID not set',
'TEMPLATE_ID_NOT_SET'
);
}
// sirsoft-admin_basic -> SirsoftAdminBasic
return this.templateId
.split(/[-_]/)
.map(part => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())
.join('');
}
/**
* 매니페스트 기반 컴포넌트 등록
*/
private async registerComponentsFromManifest(module: any): Promise<void> {
if (!this.manifest) {
throw new ComponentRegistryError(
'Manifest not loaded',
'MANIFEST_NOT_LOADED'
);
}
const componentTypes: ComponentTypeEnum[] = ['basic', 'composite', 'layout'];
for (const type of componentTypes) {
const components = this.manifest.components[type] || [];
for (const metadata of components) {
const componentName = metadata.name;
const component = module[componentName];
if (!component) {
logger.warn(`Component '${componentName}' not found in bundle`);
continue;
}
// 컴포넌트 등록
this.registerComponent(componentName, component, metadata);
}
}
}
/**
* 개별 컴포넌트 등록
*
* 등록 시 React.memo로 자동 래핑하여, props가 변경되지 않은 컴포넌트의
* 불필요한 리렌더링을 방지합니다.
*
* @since engine-v1.25.0
*/
private registerComponent(
name: string,
component: ComponentType<any>,
metadata: ComponentMetadata
): void {
if (this.registry[name]) {
logger.warn(`Component '${name}' already registered, overwriting`);
}
// 성능 최적화: React.memo 자동 래핑 (engine-v1.25.0)
// - basic/composite/layout 모든 타입에 적용
// - forwardRef 컴포넌트도 memo(forwardRef(...)) 패턴으로 정상 작동
// - 내부 useState/useRef는 memo와 무관 (외부 props 비교만 수행)
// - worst case: memo 비교 실패 → 기존과 동일하게 리렌더 (회귀 없음)
const memoizedComponent = React.memo(component);
this.registry[name] = {
component: memoizedComponent,
metadata,
};
logger.log(`[ComponentRegistry] Registered component: ${name} (${metadata.type})`);
}
/**
* 컴포넌트 조회
*
* @param name 컴포넌트 이름
* @returns 컴포넌트 또는 null
*/
public getComponent(name: string): ComponentType<any> | null {
const entry = this.registry[name];
return entry ? entry.component : null;
}
/**
* 컴포넌트 메타데이터 조회
*
* @param name 컴포넌트 이름
* @returns 메타데이터 또는 null
*/
public getMetadata(name: string): ComponentMetadata | null {
const entry = this.registry[name];
return entry ? entry.metadata : null;
}
/**
* 컴포넌트 존재 여부 확인
*
* @param name 컴포넌트 이름
* @returns 존재 여부
*/
public hasComponent(name: string): boolean {
return name in this.registry;
}
/**
* 타입별 컴포넌트 목록 조회
*
* @param type 컴포넌트 타입
* @returns 컴포넌트 이름 배열
*/
public getComponentsByType(type: ComponentTypeEnum): string[] {
return Object.entries(this.registry)
.filter(([_, entry]) => entry.metadata.type === type)
.map(([name, _]) => name);
}
/**
* 모든 컴포넌트 목록 조회
*
* @returns 컴포넌트 이름 배열
*/
public getAllComponents(): string[] {
return Object.keys(this.registry);
}
/**
* 전체 컴포넌트 맵 반환
*
* 컴포넌트 이름을 키로, React 컴포넌트를 값으로 하는 맵을 반환합니다.
* CardGrid 등 composite 컴포넌트에서 renderItemChildren 호출 시 사용합니다.
*
* @returns 컴포넌트 이름 → React 컴포넌트 맵
*/
public getComponentMap(): Record<string, ComponentType<any>> {
const map: Record<string, ComponentType<any>> = {};
for (const [name, entry] of Object.entries(this.registry)) {
map[name] = entry.component;
}
return map;
}
/**
* 로딩 상태 조회
*/
public getLoadingState(): LoadingState {
return this.loadingState;
}
/**
* 에러 정보 조회
*/
public getError(): Error | null {
return this.error;
}
/**
* 현재 템플릿 ID 조회
*/
public getTemplateId(): string | null {
return this.templateId;
}
/**
* 매니페스트 조회
*/
public getManifest(): ComponentManifest | null {
return this.manifest;
}
/**
* 레지스트리 클리어 (테스트용)
*/
public clear(): void {
this.registry = {};
this.manifest = null;
this.loadingState = 'idle';
this.error = null;
this.templateId = null;
this.templateType = null;
logger.log('Registry cleared');
}
}
// 전역 export
export default ComponentRegistry;