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 님께서 제보해주셨습니다.
This commit is contained in:
HeuJung committed 2026-07-23 11:34:32 +09:00
1 parent 74df8a4b09
commit 15cd4452bf
90 files changed
+4279 -546

No files matched your search

+5 -4
View File
@@ -29,6 +29,7 @@ import { webSocketManager } from './websocket/WebSocketManager';
import { getModuleAssetLoader, parseModuleAssetsFromConfig, parsePluginAssetsFromConfig, parseBundleUrlsFromConfig } from './modules';
import { SystemBannerManager } from './template-engine/SystemBannerManager';
import { fetchWithRetry, installUnloadGuard, isDocumentUnloading } from './template-engine/networkResilience';
import { suffixed } from './support/assetUrl';
import { resetLocalInitTracking } from './template-engine/localInitSlot';
/**
* DevTools 추적 - G7DevToolsCore.getInstance() 직접 호출 대신 G7Core.devTools를 사용합니다.
@@ -472,7 +473,7 @@ export class TemplateApp {
// routes.json 로딩 (저장된 캐시 버전 사용)
// 네트워크 일시 실패(응답 없음)에만 재시도한다. HTTP 에러는 아래 체인이 종전대로 throw.
fetchWithRetry(
`/api/templates/${this.config.templateId}/routes.json${storedCacheVersion > 0 ? `?v=${storedCacheVersion}` : ''}`,
suffixed(`/api/templates/${this.config.templateId}/routes`, 'json', storedCacheVersion > 0 ? storedCacheVersion : null),
{ label: 'routes.json' }
)
.then(response => {
@@ -494,7 +495,7 @@ export class TemplateApp {
// 사용자 정보 프리로드 (에러 발생 시 무시)
authManager.preloadAuth(this.config.templateType === 'admin' ? 'admin' : 'user'),
// 템플릿 config.json 로딩 (errorHandling 파싱)
fetch(`/api/templates/${this.config.templateId}/config.json`)
fetch(suffixed(`/api/templates/${this.config.templateId}/config`, 'json'))
.then(response => {
if (!response.ok) {
// config.json 로드 실패는 무시 (선택적)
@@ -532,7 +533,7 @@ export class TemplateApp {
logger.log('Cache version changed, reloading routes...');
// routes.json을 새 캐시 버전으로 다시 로드
const newRoutesData = await fetchWithRetry(
`/api/templates/${this.config.templateId}/routes.json?v=${this.extensionCacheVersion}`,
suffixed(`/api/templates/${this.config.templateId}/routes`, 'json', this.extensionCacheVersion),
{ label: 'routes.json (reload)' }
)
.then(response => {
@@ -2807,7 +2808,7 @@ export class TemplateApp {
let newVersion: number | undefined;
try {
const configResponse = await fetch(
`/api/templates/${this.config.templateId}/config.json?_=${Date.now()}`
suffixed(`/api/templates/${this.config.templateId}/config`, 'json', null, `_=${Date.now()}`)
);
if (configResponse.ok) {
const configResult = await configResponse.json();
+15 -5
View File
@@ -8,6 +8,7 @@
import { createLogger } from '../utils/Logger';
import { loadScriptWithRetry } from '../template-engine/networkResilience';
import { convertToCurrentMode } from '../support/assetUrl';
const logger = createLogger('ModuleAssetLoader');
@@ -452,8 +453,8 @@ export function parseModuleAssetsFromConfig(): ModuleAsset[] {
moduleAssets.push({
identifier,
js: typedAsset.js,
css: typedAsset.css,
js: typedAsset.js ? convertToCurrentMode(typedAsset.js) : typedAsset.js,
css: typedAsset.css ? convertToCurrentMode(typedAsset.css) : typedAsset.css,
priority: typedAsset.priority,
external: typedAsset.external,
});
@@ -495,7 +496,16 @@ export function parseBundleUrlsFromConfig(): ExtensionBundleUrls | null {
return null;
}
return g7Config.bundleUrls as ExtensionBundleUrls;
// 서버가 확장자 형태로 굳혀 내려준 URL 을 현재 모드로 변환한다.
// 부트스트랩 자가 복구가 런타임에 모드를 뒤집은 경우 원본은 이미 옛 형태다.
const urls = g7Config.bundleUrls as ExtensionBundleUrls;
return {
moduleJs: urls.moduleJs ? convertToCurrentMode(urls.moduleJs) : urls.moduleJs,
moduleCss: urls.moduleCss ? convertToCurrentMode(urls.moduleCss) : urls.moduleCss,
pluginJs: urls.pluginJs ? convertToCurrentMode(urls.pluginJs) : urls.pluginJs,
pluginCss: urls.pluginCss ? convertToCurrentMode(urls.pluginCss) : urls.pluginCss,
} as ExtensionBundleUrls;
}
/**
@@ -525,8 +535,8 @@ export function parsePluginAssetsFromConfig(): ModuleAsset[] {
pluginAssets.push({
identifier,
js: typedAsset.js,
css: typedAsset.css,
js: typedAsset.js ? convertToCurrentMode(typedAsset.js) : typedAsset.js,
css: typedAsset.css ? convertToCurrentMode(typedAsset.css) : typedAsset.css,
priority: typedAsset.priority,
external: typedAsset.external,
});
+5 -4
View File
@@ -1,5 +1,6 @@
import { AuthManager } from '../auth/AuthManager';
import { createLogger } from '../utils/Logger';
import { suffixed } from '../support/assetUrl';
const logger = createLogger('Router');
@@ -107,10 +108,10 @@ export class Router {
*/
async loadRoutes(cacheVersion?: number): Promise<void> {
try {
const versionQuery = cacheVersion !== undefined && cacheVersion > 0
? `?v=${cacheVersion}`
: '';
const response = await fetch(`/api/templates/${this.templateIdentifier}/routes.json${versionQuery}`);
const version = cacheVersion !== undefined && cacheVersion > 0 ? cacheVersion : null;
const response = await fetch(
suffixed(`/api/templates/${this.templateIdentifier}/routes`, 'json', version),
);
if (!response.ok) {
throw new Error(`Failed to load routes: ${response.statusText}`);
@@ -0,0 +1,223 @@
/**
* 자산 URL 빌더(프론트) 가드 — 이슈 #486 단위 C.
*
* 단위 C 의 회귀 조건은 "기본 모드에서 치환 이전 URL 문자열과 바이트 동일" 이다.
* 아래 확장자 모드 기대값은 치환 이전 소스에 하드코딩되어 있던 문자열을 그대로 옮긴 것으로,
* 빌더 도입이 URL 을 한 글자도 바꾸지 않았음을 고정한다.
*
* 서버측 `App\Support\AssetUrl` 와 규칙이 일치해야 한다 — 한쪽만 바뀌면 그 자산만 404 가 된다.
*/
// e2e:allow 순수 URL 문자열 생성 유닛. 브라우저 거동은 단위 D(자가 복구) spec 이 커버한다.
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import {
MODE_EXTENSION,
MODE_EXTENSIONLESS,
getAssetUrlMode,
isExtensionless,
setAssetUrlMode,
restoreCachedMode,
templateAsset,
moduleAsset,
pluginAsset,
extensionBundle,
suffixed,
layoutUrl,
layoutPreviewUrl,
} from '../assetUrl';
/**
* G7Config 를 지정 모드로 초기화합니다.
*/
function setConfig(mode?: string, cacheVersion = 7): void {
// 자가 복구가 기록하는 독립 전역까지 초기화한다 — 남아 있으면 이후 케이스가
// 앞 케이스의 전환 결과를 물려받아 거짓 실패/거짓 통과가 난다.
delete (globalThis as any).__g7AssetUrlMode;
(globalThis as any).G7Config = {
cache_version: cacheVersion,
...(mode ? { assetUrlMode: mode } : {}),
};
}
describe('assetUrl (프론트 자산 URL 빌더)', () => {
beforeEach(() => {
globalThis.localStorage?.clear();
setConfig(MODE_EXTENSION);
});
afterEach(() => {
delete (globalThis as any).G7Config;
delete (globalThis as any).__g7AssetUrlMode;
globalThis.localStorage?.clear();
});
describe('모드 판정', () => {
it('G7Config 부재 시 기본 모드는 확장자 유지', () => {
delete (globalThis as any).G7Config;
expect(getAssetUrlMode()).toBe(MODE_EXTENSION);
expect(isExtensionless()).toBe(false);
});
it('런타임 키가 설정값보다 우선한다', () => {
(globalThis as any).G7Config = {
assetUrlMode: MODE_EXTENSIONLESS,
settings: { general: { asset_url_mode: MODE_EXTENSION } },
};
expect(getAssetUrlMode()).toBe(MODE_EXTENSIONLESS);
});
it('런타임 키가 없으면 설정값을 따른다', () => {
(globalThis as any).G7Config = {
settings: { general: { asset_url_mode: MODE_EXTENSIONLESS } },
};
expect(getAssetUrlMode()).toBe(MODE_EXTENSIONLESS);
});
it('알 수 없는 값은 기본 모드로 폴백한다', () => {
(globalThis as any).G7Config = { assetUrlMode: 'nonsense' };
expect(getAssetUrlMode()).toBe(MODE_EXTENSION);
});
});
describe('확장자 모드 — 치환 이전 문자열과 바이트 동일', () => {
it('Router.ts:113 routes.json (버전 있음/없음)', () => {
expect(suffixed('/api/templates/sirsoft-basic/routes', 'json', 7)).toBe(
'/api/templates/sirsoft-basic/routes.json?v=7',
);
expect(suffixed('/api/templates/sirsoft-basic/routes', 'json', null)).toBe(
'/api/templates/sirsoft-basic/routes.json',
);
});
it('ComponentRegistry.ts:250 components.json', () => {
expect(suffixed('/api/templates/sirsoft-basic/components', 'json')).toBe(
'/api/templates/sirsoft-basic/components.json',
);
});
it('TemplateApp.ts:2810 config.json + 캐시버스트 쿼리', () => {
expect(suffixed('/api/templates/sirsoft-basic/config', 'json', null, '_=1699999999')).toBe(
'/api/templates/sirsoft-basic/config.json?_=1699999999',
);
});
it('LayoutLoader.ts:750,752 레이아웃 / 미리보기', () => {
expect(layoutUrl('sirsoft-basic', 'home', 7)).toBe('/api/layouts/sirsoft-basic/home.json?v=7');
expect(layoutPreviewUrl('abc-def')).toBe('/api/layouts/preview/abc-def.json');
});
it('편집기 문서 로드 — with_source_meta 가 v 보다 앞 (캐시 키 보존)', () => {
expect(
suffixed('/api/layouts/sirsoft-basic/home', 'json', '7.3', 'with_source_meta=1'),
).toBe('/api/layouts/sirsoft-basic/home.json?with_source_meta=1&v=7.3');
});
it('자산 URL — 템플릿/모듈/플러그인', () => {
expect(templateAsset('sirsoft-basic', 'js/components.iife.js', 7)).toBe(
'/api/templates/assets/sirsoft-basic/js/components.iife.js?v=7',
);
expect(moduleAsset('sirsoft-ecommerce', 'dist/js/module.iife.js', 7)).toBe(
'/api/modules/assets/sirsoft-ecommerce/dist/js/module.iife.js?v=7',
);
expect(pluginAsset('sirsoft-gdpr', 'dist/css/plugin.css')).toBe(
'/api/plugins/assets/sirsoft-gdpr/dist/css/plugin.css',
);
});
it('병합 번들', () => {
expect(extensionBundle('modules', 'js', 7)).toBe('/api/modules/bundle.js?v=7');
expect(extensionBundle('plugins', 'css', 7)).toBe('/api/plugins/bundle.css?v=7');
});
});
describe('확장자 없는 모드', () => {
beforeEach(() => setConfig(MODE_EXTENSIONLESS));
it('고정 접미사를 제거한다', () => {
expect(suffixed('/api/templates/sirsoft-basic/routes', 'json', 7)).toBe(
'/api/templates/sirsoft-basic/routes?v=7',
);
expect(layoutUrl('sirsoft-basic', 'home', 7)).toBe('/api/layouts/sirsoft-basic/home?v=7');
});
it('자산 경로를 file 쿼리로 옮긴다', () => {
expect(templateAsset('sirsoft-basic', 'js/components.iife.js', 7)).toBe(
'/api/templates/assets/sirsoft-basic?file=js%2Fcomponents.iife.js&v=7',
);
});
it('번들 접미사를 경로 세그먼트로 내린다', () => {
expect(extensionBundle('modules', 'js', 7)).toBe('/api/modules/bundle/js?v=7');
expect(extensionBundle('plugins', 'css')).toBe('/api/plugins/bundle/css');
});
it('생성된 모든 URL 의 경로에 정적 확장자가 남지 않는다', () => {
const urls = [
suffixed('/api/templates/t/routes', 'json', 7),
layoutUrl('t', 'home', 7),
layoutPreviewUrl('abc'),
templateAsset('t', 'js/a.js', 7),
moduleAsset('m', 'dist/js/a.js'),
pluginAsset('p', 'dist/css/a.css'),
extensionBundle('modules', 'js', 7),
];
for (const url of urls) {
const path = url.split('?')[0];
expect(path, `경로에 정적 확장자 잔존: ${url}`).not.toMatch(/\.(js|mjs|css|json|map)$/i);
}
});
});
describe('런타임 전환 (§12 L1 — 단방향 1회)', () => {
it('extension → extensionless 전환은 허용된다', () => {
expect(setAssetUrlMode(MODE_EXTENSIONLESS)).toBe(true);
expect(getAssetUrlMode()).toBe(MODE_EXTENSIONLESS);
});
it('역방향 전환은 거부된다 (무한 왕복 차단)', () => {
setAssetUrlMode(MODE_EXTENSIONLESS);
expect(setAssetUrlMode(MODE_EXTENSION as any)).toBe(false);
expect(getAssetUrlMode()).toBe(MODE_EXTENSIONLESS);
});
it('이미 전환된 상태에서 재전환은 false 를 반환한다 (1회 제한)', () => {
expect(setAssetUrlMode(MODE_EXTENSIONLESS)).toBe(true);
expect(setAssetUrlMode(MODE_EXTENSIONLESS)).toBe(false);
});
});
describe('localStorage 캐시 (§12 L7)', () => {
it('전환 결과가 캐시되어 재방문 시 복원된다', () => {
setAssetUrlMode(MODE_EXTENSIONLESS);
setConfig(MODE_EXTENSION);
expect(restoreCachedMode()).toBe(true);
expect(getAssetUrlMode()).toBe(MODE_EXTENSIONLESS);
});
it('cache_version 이 바뀌면 옛 캐시가 무시된다', () => {
setAssetUrlMode(MODE_EXTENSIONLESS);
setConfig(MODE_EXTENSION, 8);
expect(restoreCachedMode()).toBe(false);
expect(getAssetUrlMode()).toBe(MODE_EXTENSION);
});
it('TTL 을 넘긴 캐시는 무시되고 제거된다', () => {
const stale = JSON.stringify({ mode: MODE_EXTENSIONLESS, at: Date.now() - 25 * 60 * 60 * 1000 });
globalThis.localStorage.setItem('g7_asset_url_mode:7', stale);
setConfig(MODE_EXTENSION);
expect(restoreCachedMode()).toBe(false);
expect(globalThis.localStorage.getItem('g7_asset_url_mode:7')).toBeNull();
});
});
});
@@ -0,0 +1,301 @@
/**
* 자산 URL 자가 복구 불변식 가드 — 이슈 #486 단위 D (§12 L1~L9).
*
* 자가 복구는 "실패했으니 다시 시도한다" 는 구조라 루프 위험이 내재한다.
* 계획서 §12 는 이를 구현 불변식으로 못박았고, 각각에 대응 테스트를 요구한다.
* 여기서는 브라우저 없이 검증 가능한 불변식(L1·L5·L7)과, blade 인라인 복구기와
* TS 빌더의 **규칙 드리프트**를 다룬다. 요청 횟수·리로드·폴백 UI(L2·L3·L4·L8)는
* 브라우저 계층이므로 Playwright spec 이 담당한다.
*/
// e2e:allow 불변식의 순수 로직 단위. 브라우저 계층(L2·L3·L4·L8)은 asset-url-mode.spec.ts 가 커버한다.
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { readFileSync, readdirSync } from 'node:fs';
import { resolve, join } from 'node:path';
import {
MODE_EXTENSION,
MODE_EXTENSIONLESS,
getAssetUrlMode,
setAssetUrlMode,
convertToCurrentMode,
} from '../assetUrl';
/**
* blade 파샬의 인라인 `toExtensionless` 를 추출해 실행 가능한 함수로 만든다.
*
* 부트스트랩은 코어 번들 로드 전에 동작해야 해서 import 를 쓸 수 없고, 그래서 변환 규칙이
* blade 인라인 JS 에 한 벌 더 존재한다. 두 구현이 갈라지면 서버가 만든 URL 과
* 클라이언트가 만든 URL 이 어긋나 그 자산만 404 가 되므로, 실제 blade 소스에서
* 함수를 뽑아 TS 구현과 대조한다.
*/
function loadInlineConverter(): (url: string) => string | null {
const bladePath = resolve(__dirname, '../../../../views/partials/asset-url-recovery.blade.php');
const source = readFileSync(bladePath, 'utf-8');
const start = source.indexOf('function toExtensionless(url) {');
expect(start, 'blade 파샬에서 toExtensionless 를 찾지 못했다').toBeGreaterThan(-1);
// 균형 중괄호로 함수 본문 끝을 찾는다
let depth = 0;
let end = start;
for (let i = source.indexOf('{', start); i < source.length; i += 1) {
if (source[i] === '{') depth += 1;
else if (source[i] === '}') {
depth -= 1;
if (depth === 0) {
end = i + 1;
break;
}
}
}
const fnSource = source.slice(start, end);
// 함수가 참조하는 파샬 상단 상수를 함께 주입한다 (blade 스코프 재현)
// eslint-disable-next-line no-new-func
return new Function(
`var FILE_QUERY_PARAM = 'file';\n${fnSource}\nreturn toExtensionless;`,
)() as (url: string) => string | null;
}
describe('자산 URL 자가 복구 불변식 (§12)', () => {
beforeEach(() => {
delete (globalThis as any).__g7AssetUrlMode;
(globalThis as any).G7Config = { cache_version: 7 };
globalThis.localStorage?.clear();
});
afterEach(() => {
delete (globalThis as any).__g7AssetUrlMode;
delete (globalThis as any).G7Config;
globalThis.localStorage?.clear();
});
describe('L1 — 전환은 단방향 1회', () => {
it('extension → extensionless 는 1회만 성공한다', () => {
expect(setAssetUrlMode(MODE_EXTENSIONLESS)).toBe(true);
expect(setAssetUrlMode(MODE_EXTENSIONLESS)).toBe(false);
});
it('역방향 전환 경로가 존재하지 않는다', () => {
setAssetUrlMode(MODE_EXTENSIONLESS);
expect(setAssetUrlMode(MODE_EXTENSION as any)).toBe(false);
expect(getAssetUrlMode()).toBe(MODE_EXTENSIONLESS);
});
it('G7Config 가 재대입되어도 전환 결과가 유지된다', () => {
setAssetUrlMode(MODE_EXTENSIONLESS);
// <body> 의 `window.G7Config = {...}` 재대입 모사
(globalThis as any).G7Config = { cache_version: 7, assetUrlMode: MODE_EXTENSION };
expect(getAssetUrlMode()).toBe(MODE_EXTENSIONLESS);
});
});
describe('L5 — 클라이언트는 서버 설정을 쓰지 않는다', () => {
it('전환이 settings 원본을 변경하지 않는다', () => {
(globalThis as any).G7Config = {
cache_version: 7,
settings: { general: { asset_url_mode: MODE_EXTENSION } },
};
setAssetUrlMode(MODE_EXTENSIONLESS);
expect((globalThis as any).G7Config.settings.general.asset_url_mode).toBe(MODE_EXTENSION);
});
});
describe('L7 — 캐시는 cache_version 을 포함하고 TTL 을 둔다', () => {
it('캐시 키에 cache_version 이 포함된다', () => {
setAssetUrlMode(MODE_EXTENSIONLESS);
expect(globalThis.localStorage.getItem('g7_asset_url_mode:7')).not.toBeNull();
});
});
describe('변환 규칙 — blade 인라인 복구기와 TS 빌더 동등성', () => {
const cases = [
'/api/templates/assets/sirsoft-basic/js/components.iife.js?v=7',
'/api/templates/assets/sirsoft-basic/css/components.css?v=7',
'/api/modules/assets/sirsoft-ecommerce/dist/js/module.iife.js?v=7',
'/api/plugins/assets/sirsoft-gdpr/dist/css/plugin.css',
'/api/modules/bundle.js?v=7',
'/api/plugins/bundle.css',
'/api/templates/sirsoft-basic/routes.json?v=7',
'/api/layouts/sirsoft-basic/home.json?with_source_meta=1&v=7',
];
it('모든 대표 URL 에서 두 구현의 결과가 동일하다', () => {
const inline = loadInlineConverter();
(globalThis as any).__g7AssetUrlMode = MODE_EXTENSIONLESS;
for (const url of cases) {
expect(inline(url), `blade 인라인 변환기가 ${url} 을 변환하지 못했다`).not.toBeNull();
expect(inline(url), `변환 규칙 드리프트: ${url}`).toBe(convertToCurrentMode(url));
}
});
it('코어 엔진 번들은 두 구현 모두 변환하지 않는다', () => {
const inline = loadInlineConverter();
(globalThis as any).__g7AssetUrlMode = MODE_EXTENSIONLESS;
const coreBundle = '/build/core/template-engine.min.js?v=123';
// public/ 의 실물 정적 파일 — 변환하면 오히려 깨진다
expect(inline(coreBundle)).toBeNull();
expect(convertToCurrentMode(coreBundle)).toBe(coreBundle);
});
it('확장자 모드에서는 TS 빌더가 원본을 그대로 돌려준다', () => {
(globalThis as any).__g7AssetUrlMode = undefined;
(globalThis as any).G7Config = { cache_version: 7, assetUrlMode: MODE_EXTENSION };
for (const url of cases) {
expect(convertToCurrentMode(url)).toBe(url);
}
});
});
describe('L6 — 인스톨러 프로브도 본문 토큰 + Content-Type 으로 판정', () => {
/**
* 프로브 판정 로직은 두 곳에 존재한다 — 관리자 핸들러(`detectAssetUrlModeHandler`)와
* 인스톨러(`installer.js`). 전자는 동작 테스트로 red 증명까지 마쳤지만,
* 인스톨러는 코어 번들 이전에 도는 순수 브라우저 스크립트라 vitest 하네스가 없다.
*
* 하네스를 새로 만드는 대신 소스 수준 드리프트 가드를 둔다 — 두 검사 중 하나라도
* 사라지면 이 테스트가 red 가 된다. `200 + 에러 HTML` 을 반환하는 서버에서
* 설치가 영원히 `extension` 으로 오판되는 것을 막는 검사다.
*/
it('인스톨러 프로브가 두 검사를 모두 수행한다', () => {
const installerPath = resolve(
__dirname,
'../../../../../public/install/assets/js/installer.js',
);
const source = readFileSync(installerPath, 'utf-8');
const start = source.indexOf('async function detectAssetUrlMode(');
expect(start, 'installer.js 에서 detectAssetUrlMode 를 찾지 못했다').toBeGreaterThan(-1);
// 주석은 제거하고 실행 코드만 본다 — 주석에 남은 "Content-Type" 문구가
// 검사 삭제를 가려주면 가드가 무력해진다(실제로 겪은 오탐).
const body = source
.slice(start, start + 2500)
.replace(/\/\*[\s\S]*?\*\//g, '')
.replace(/\/\/[^\n]*/g, '');
expect(
/headers\s*\.\s*get\(\s*['"]content-type['"]/i.test(body),
'L6 위반: 인스톨러 프로브가 Content-Type 을 읽지 않는다 (200+HTML 오판)',
).toBe(true);
expect(
/javascript|ecmascript/i.test(body),
'L6 위반: 인스톨러 프로브에 스크립트 MIME 판정이 없다',
).toBe(true);
expect(
/includes\(\s*TOKEN\s*\)/.test(body),
'L6 위반: 인스톨러 프로브에 매직 토큰 검사가 없다 (무관한 200 응답 오판)',
).toBe(true);
});
});
describe('L9 — 감지 주체는 부트스트랩 하나', () => {
/**
* 엔진 레이어(Router/LayoutLoader/ComponentRegistry/TranslationEngine 등)는
* 확정된 모드를 **읽기만** 해야 한다. 계층마다 독립적으로 재감지하면
* 감지 캐스케이드가 중첩되어 요청이 폭증한다.
*
* 프로브 엔드포인트를 호출하는 코드가 엔진에 새로 들어오면 이 테스트가 잡는다.
*/
it('엔진 소스에 프로브 엔드포인트 호출이 없다', () => {
const engineRoot = resolve(__dirname, '../../');
const offenders: string[] = [];
const walk = (dir: string): void => {
for (const entry of readdirSync(dir, { withFileTypes: true })) {
const full = join(dir, entry.name);
if (entry.isDirectory()) {
if (entry.name === '__tests__' || entry.name === 'node_modules') continue;
walk(full);
continue;
}
if (!/\.(ts|tsx)$/.test(entry.name)) continue;
const src = readFileSync(full, 'utf-8');
if (src.includes('asset-probe')) {
offenders.push(full.replace(engineRoot, ''));
}
}
};
walk(engineRoot);
expect(
offenders,
`엔진 레이어가 프로브를 직접 호출한다 (L9 위반 — 감지는 부트스트랩 단독):\n${offenders.join('\n')}`,
).toEqual([]);
});
});
describe('convertToCurrentMode 변환 결과', () => {
beforeEach(() => {
(globalThis as any).__g7AssetUrlMode = MODE_EXTENSIONLESS;
});
it('자산은 file 쿼리로, 번들은 세그먼트로, 접미사는 제거로', () => {
expect(convertToCurrentMode('/api/templates/assets/t/js/a.js?v=7')).toBe(
'/api/templates/assets/t?file=js%2Fa.js&v=7',
);
expect(convertToCurrentMode('/api/modules/bundle.js?v=7')).toBe('/api/modules/bundle/js?v=7');
expect(convertToCurrentMode('/api/templates/t/routes.json')).toBe('/api/templates/t/routes');
});
it('변환 결과 경로에 정적 확장자가 남지 않는다', () => {
for (const url of [
'/api/templates/assets/t/js/a.js?v=7',
'/api/modules/bundle.js',
'/api/templates/t/routes.json',
'/api/layouts/t/home.json?v=7',
]) {
const path = convertToCurrentMode(url).split('?')[0];
expect(path, `경로에 확장자 잔존: ${url}`).not.toMatch(/\.(js|css|json)$/i);
}
});
it('외부 origin URL 은 건드리지 않는다', () => {
const external = 'https://cdn.example.com/lib.js';
expect(convertToCurrentMode(external)).toBe(external);
});
// 회귀: `<script>.src` / `<link>.href` 는 절대 URL 을 돌려준다. same-origin
// 접두사를 벗기지 않으면 부트스트랩 재시도에서 변환이 항상 null 이 되어
// 자가 복구가 통째로 죽는다 — 외형은 "3회 재시도 후 폴백 UI" 라 원인이 안 보인다.
it('same-origin 절대 URL 도 변환한다 (DOM 프로퍼티 형태)', () => {
const origin = globalThis.location.origin;
expect(convertToCurrentMode(`${origin}/api/templates/assets/t/js/a.js?v=7`)).toBe(
'/api/templates/assets/t?file=js%2Fa.js&v=7',
);
expect(convertToCurrentMode(`${origin}/api/modules/bundle.js?v=7`)).toBe(
'/api/modules/bundle/js?v=7',
);
});
it('blade 인라인 복구기도 same-origin 절대 URL 을 변환한다', () => {
const inline = loadInlineConverter();
const origin = globalThis.location.origin;
expect(inline(`${origin}/api/templates/assets/t/js/a.js?v=7`)).toBe(
'/api/templates/assets/t?file=js%2Fa.js&v=7',
);
});
});
});
+436
View File
@@ -0,0 +1,436 @@
/**
* 자산·동적 엔드포인트 URL 생성기 (프론트측 SSoT).
*
* 서버측 `App\Support\AssetUrl` 와 **동일한 규칙**을 구현한다. 한쪽만 바뀌면
* 서버가 만든 URL 과 클라이언트가 만든 URL 이 어긋나 그 자산만 404 가 되므로,
* 규칙을 바꿀 때는 반드시 양쪽을 함께 수정한다.
*
* ## 배경
*
* nginx/Apache 의 표준적 정적 최적화 블록은 URL 마지막 확장자로 분기한다.
*
* ```nginx
* location ~* \.(js|css|json)$ { expires max; access_log off; }
* ```
*
* nginx 에서 정규식 location 은 프리픽스 location 보다 먼저 매칭되므로
* `try_files ... /index.php` 폴백이 실행될 기회가 없다. 그런 환경에서는
* 확장자 붙은 동적 응답이 PHP 에 도달하지 못하고 404 가 된다.
*
* ## 모드
*
* | 모드 | 의미 |
* |---|---|
* | `extension` (기본) | 확장자 유지 — 정상 환경 |
* | `extensionless` | 확장자 제거 — 정적 블록이 가로채는 환경 |
*
* 초기값은 서버가 `window.G7Config.assetUrlMode` 로 내려준다. 부트스트랩
* 자가 복구가 확장자 형태 실패를 감지하면 런타임에 `extensionless` 로 전환한다
* (단방향 1회 — 역방향 전환은 만들지 않는다. 무한 왕복 방지).
*
* @since engine-v1.54.0
*/
/** 확장자 유지 모드 식별자. */
export const MODE_EXTENSION = 'extension';
/** 확장자 제거 모드 식별자. */
export const MODE_EXTENSIONLESS = 'extensionless';
/** 자산 URL 모드 타입. */
export type AssetUrlMode = typeof MODE_EXTENSION | typeof MODE_EXTENSIONLESS;
/** 확장자 없는 자산 URL 에서 파일 경로를 담는 쿼리 파라미터명. */
export const FILE_QUERY_PARAM = 'file';
/** localStorage 캐시 키 접두사 (cache_version 을 포함해 서버 정상화 후 고착 방지). */
const STORAGE_KEY_PREFIX = 'g7_asset_url_mode';
/** localStorage 캐시 TTL (24시간). 서버가 정상화되면 자동으로 재판정된다. */
const STORAGE_TTL_MS = 24 * 60 * 60 * 1000;
/**
* 현재 자산 URL 모드를 반환합니다.
*
* 우선순위: 런타임 전환값(`G7Config.assetUrlMode`) → 설정값
* (`G7Config.settings.general.asset_url_mode`) → 기본값 `extension`.
*
* @returns 현재 모드
*/
export function getAssetUrlMode(): AssetUrlMode {
const config = (globalThis as any)?.G7Config;
// 부트스트랩 자가 복구가 기록하는 독립 전역이 최우선이다. `<head>` 파샬이 이 값을
// 확정한 뒤 `<body>` 에서 G7Config 객체가 통째로 재대입되는 순서라, G7Config 만
// 보면 전환 결과를 놓칠 수 있다.
const recovered = (globalThis as any)?.__g7AssetUrlMode;
if (recovered === MODE_EXTENSIONLESS) {
return MODE_EXTENSIONLESS;
}
const runtime = config?.assetUrlMode;
if (runtime === MODE_EXTENSIONLESS || runtime === MODE_EXTENSION) {
return runtime;
}
const configured = config?.settings?.general?.asset_url_mode;
if (configured === MODE_EXTENSIONLESS) {
return MODE_EXTENSIONLESS;
}
return MODE_EXTENSION;
}
/**
* 현재 모드가 확장자 없는 모드인지 여부를 반환합니다.
*
* @returns 확장자 없는 모드이면 true
*/
export function isExtensionless(): boolean {
return getAssetUrlMode() === MODE_EXTENSIONLESS;
}
/**
* 자산 URL 모드를 런타임에 전환합니다 (단방향).
*
* `extension → extensionless` 만 허용한다. 역방향을 허용하면 양쪽 형태가 모두
* 실패하는 상황(PHP 다운·WAF 차단)에서 `ext → extless → ext → …` 무한 왕복이 된다.
*
* 서버 설정은 바꾸지 않는다 — 미인증 클라이언트가 전역 설정을 뒤집을 수 있으면 안 된다.
*
* @param mode 전환할 모드
* @returns 실제로 전환되었으면 true
*/
export function setAssetUrlMode(mode: AssetUrlMode): boolean {
if (mode !== MODE_EXTENSIONLESS) {
return false;
}
if ((globalThis as any)?.__g7AssetUrlMode === MODE_EXTENSIONLESS) {
return false;
}
const config = (globalThis as any)?.G7Config;
if (config?.assetUrlMode === MODE_EXTENSIONLESS) {
return false;
}
(globalThis as any).__g7AssetUrlMode = MODE_EXTENSIONLESS;
if (config) {
config.assetUrlMode = MODE_EXTENSIONLESS;
}
persistMode(MODE_EXTENSIONLESS);
return true;
}
/**
* 캐시된 모드를 읽어 적용합니다 (같은 브라우저 재방문 시 첫 요청부터 정타).
*
* 캐시 키에 `cache_version` 을 포함하고 TTL 을 두어, 서버가 정상화된 뒤에도
* 클라이언트가 옛 모드에 영구 고착되지 않도록 한다.
*
* @returns 캐시가 적용되었으면 true
*/
export function restoreCachedMode(): boolean {
try {
const raw = globalThis.localStorage?.getItem(storageKey());
if (!raw) {
return false;
}
const parsed = JSON.parse(raw) as { mode?: string; at?: number };
if (parsed?.mode !== MODE_EXTENSIONLESS) {
return false;
}
if (typeof parsed.at !== 'number' || Date.now() - parsed.at > STORAGE_TTL_MS) {
globalThis.localStorage?.removeItem(storageKey());
return false;
}
(globalThis as any).__g7AssetUrlMode = MODE_EXTENSIONLESS;
const config = (globalThis as any)?.G7Config;
if (config) {
config.assetUrlMode = MODE_EXTENSIONLESS;
}
return true;
} catch {
// localStorage 접근 불가(사파리 프라이빗 등)는 치명적이지 않다 — 캐시 없이 진행
return false;
}
}
/**
* 템플릿 자산 URL 을 생성합니다.
*
* 템플릿은 서버가 `dist/` 를 자동 부가하므로 `path` 에 `dist/` 를 포함하지 않는다.
*
* @param identifier 템플릿 식별자
* @param path `dist/` 이하 파일 경로 (예: `js/components.iife.js`)
* @param version 캐시 무효화 버전 (없으면 미부착)
* @returns 생성된 URL
*/
export function templateAsset(identifier: string, path: string, version?: number | string | null): string {
return extensionAsset('templates', identifier, path, version);
}
/**
* 모듈 자산 URL 을 생성합니다.
*
* 모듈은 모듈 루트 기준이라 `path` 에 `dist/` 를 직접 포함한다 (템플릿과 비대칭).
*
* @param identifier 모듈 식별자
* @param path 모듈 루트 기준 파일 경로
* @param version 캐시 무효화 버전
* @returns 생성된 URL
*/
export function moduleAsset(identifier: string, path: string, version?: number | string | null): string {
return extensionAsset('modules', identifier, path, version);
}
/**
* 플러그인 자산 URL 을 생성합니다.
*
* @param identifier 플러그인 식별자
* @param path 플러그인 루트 기준 파일 경로
* @param version 캐시 무효화 버전
* @returns 생성된 URL
*/
export function pluginAsset(identifier: string, path: string, version?: number | string | null): string {
return extensionAsset('plugins', identifier, path, version);
}
/**
* 확장 타입을 인자로 받는 자산 URL 생성기.
*
* 확장자 없는 모드에서는 파일 경로를 `?file=` 쿼리로 옮긴다. 경로가 곧 파일명이라
* 접미사만 떼어낼 수 없기 때문이며, nginx 의 location 정규식이 쿼리스트링을 제외한
* 경로에만 매칭되므로 이 형태가 안전하다.
*
* @param type `templates` | `modules` | `plugins`
* @param identifier 확장 식별자
* @param path 파일 경로
* @param version 캐시 무효화 버전
* @returns 생성된 URL
*/
export function extensionAsset(
type: string,
identifier: string,
path: string,
version?: number | string | null,
): string {
const normalizedPath = path.replace(/^\/+/, '');
const id = encodeURIComponent(identifier);
if (!isExtensionless()) {
return `/api/${type}/assets/${id}/${normalizedPath}${versionQuery(version)}`;
}
let query = `${FILE_QUERY_PARAM}=${encodeURIComponent(normalizedPath)}`;
if (version !== undefined && version !== null && version !== '') {
query += `&v=${version}`;
}
return `/api/${type}/assets/${id}?${query}`;
}
/**
* 확장 병합 번들 URL 을 생성합니다.
*
* 접미사(js/css)가 번들 종류를 구분하므로 제거할 수 없다.
* 확장자 없는 모드에서는 경로 세그먼트로 내린다 (`bundle.js` → `bundle/js`).
*
* @param type `modules` | `plugins`
* @param kind `js` | `css`
* @param version 캐시 무효화 버전
* @returns 생성된 URL
*/
export function extensionBundle(type: string, kind: string, version?: number | string | null): string {
const base = isExtensionless() ? `/api/${type}/bundle/${kind}` : `/api/${type}/bundle.${kind}`;
return `${base}${versionQuery(version)}`;
}
/**
* 고정 접미사를 갖는 동적 엔드포인트 URL 을 생성합니다.
*
* 확장자 없는 모드에서는 접미사를 제거한다 (`routes.json` → `routes`).
* 추가 쿼리는 `extraQuery` 로 전달한다 (이미 `?` 가 붙은 뒤에 이어붙이지 않도록
* 결합을 이 함수가 책임진다).
*
* @param path 접미사를 제외한 경로 (예: `/api/templates/foo/routes`)
* @param suffix 접미사 (예: `json`)
* @param version 캐시 무효화 버전
* @param extraQuery 추가 쿼리스트링 (`a=1&b=2` 형태, `?` 없이)
* @returns 생성된 URL
*/
export function suffixed(
path: string,
suffix: string,
version?: number | string | null,
extraQuery?: string,
): string {
const base = path.replace(/\/+$/, '');
const normalized = suffix.replace(/^\.+/, '');
const url = isExtensionless() ? base : `${base}.${normalized}`;
// 순서 주의: extraQuery 를 v 보다 **앞**에 둔다. 치환 이전 호출부가
// `?with_source_meta=1&v=...` 순서로 만들고 있었고, 쿼리 순서가 바뀌면
// URL 문자열이 달라져 HTTP 캐시 키가 갈린다(의미는 같아도 캐시 미스).
const parts: string[] = [];
if (extraQuery) {
parts.push(extraQuery.replace(/^[?&]+/, ''));
}
if (version !== undefined && version !== null && version !== '') {
parts.push(`v=${version}`);
}
return parts.length > 0 ? `${url}?${parts.join('&')}` : url;
}
/**
* 레이아웃 서빙 URL 을 생성합니다.
*
* @param templateId 템플릿 식별자
* @param layoutPath 레이아웃 경로 (예: `home`, `board/list`)
* @param version 캐시 무효화 버전
* @param extraQuery 추가 쿼리스트링
* @returns 생성된 URL
*/
export function layoutUrl(
templateId: string,
layoutPath: string,
version?: number | string | null,
extraQuery?: string,
): string {
return suffixed(`/api/layouts/${encodeURIComponent(templateId)}/${layoutPath}`, 'json', version, extraQuery);
}
/**
* 레이아웃 미리보기 서빙 URL 을 생성합니다.
*
* @param token 미리보기 토큰 (UUID)
* @returns 생성된 URL
*/
export function layoutPreviewUrl(token: string): string {
return suffixed(`/api/layouts/preview/${encodeURIComponent(token)}`, 'json');
}
/**
* 서버가 확장자 형태로 만들어 내려준 URL 을 **현재 모드**에 맞게 변환합니다.
*
* `G7Config.bundleUrls` / `moduleAssets` / `pluginAssets` 는 서버 렌더 시점에
* 문자열로 굳어 내려온다. 부트스트랩 자가 복구가 런타임에 모드를 뒤집으면 이 값들이
* 옛 형태로 남으므로, 소비 지점에서 이 함수를 거쳐야 한다.
*
* 확장자 모드이거나 변환 대상이 아닌 URL(외부 origin, `/build/...` 정적 파일 등)은
* 원본을 그대로 돌려준다 — 코어 엔진 번들은 `public/` 의 실물 파일이라 변환하면 깨진다.
*
* @param url 서버가 생성한 URL
* @returns 현재 모드에 맞는 URL
*/
export function convertToCurrentMode(url: string): string {
if (!url || !isExtensionless()) {
return url;
}
// DOM 프로퍼티(`script.src` / `link.href`)는 절대 URL 을 돌려주므로
// same-origin 접두사를 먼저 벗긴다. 외부 origin 은 대상이 아니다.
const origin = (globalThis as any)?.location?.origin;
const relative = origin && url.startsWith(origin) ? url.slice(origin.length) : url;
if (!relative.startsWith('/api/')) {
return url;
}
const [path, query] = splitQuery(relative);
// 1) 병합 번들: /api/{type}/bundle.{js|css} → /api/{type}/bundle/{js|css}
const bundleMatch = path.match(/^\/api\/(modules|plugins)\/bundle\.(js|css)$/);
if (bundleMatch) {
return joinQuery(`/api/${bundleMatch[1]}/bundle/${bundleMatch[2]}`, query);
}
// 2) 자산: /api/{type}/assets/{id}/{path} → /api/{type}/assets/{id}?file={path}
const assetMatch = path.match(/^\/api\/(templates|modules|plugins)\/assets\/([^/]+)\/(.+)$/);
if (assetMatch) {
const [, type, identifier, filePath] = assetMatch;
const fileQuery = `${FILE_QUERY_PARAM}=${encodeURIComponent(decodeURIComponent(filePath))}`;
return `/api/${type}/assets/${identifier}?${fileQuery}${query ? `&${query}` : ''}`;
}
// 3) 고정 접미사: /api/.../x.json → /api/.../x
const suffixMatch = path.match(/^(\/api\/.+)\.(json|js|css)$/);
if (suffixMatch) {
return joinQuery(suffixMatch[1], query);
}
return url;
}
/**
* URL 을 경로와 쿼리로 분리합니다.
*
* @param url 대상 URL
* @returns [경로, 쿼리(`?` 제외)]
*/
function splitQuery(url: string): [string, string] {
const idx = url.indexOf('?');
return idx === -1 ? [url, ''] : [url.slice(0, idx), url.slice(idx + 1)];
}
/**
* 경로와 쿼리를 결합합니다.
*
* @param path 경로
* @param query 쿼리 (`?` 제외)
* @returns 결합된 URL
*/
function joinQuery(path: string, query: string): string {
return query ? `${path}?${query}` : path;
}
/**
* 캐시 무효화 쿼리스트링을 생성합니다.
*
* @param version 버전 값
* @returns `?v=...` 또는 빈 문자열
*/
function versionQuery(version?: number | string | null): string {
if (version === undefined || version === null || version === '') {
return '';
}
return `?v=${version}`;
}
/**
* localStorage 캐시 키를 생성합니다 (cache_version 포함).
*
* @returns 캐시 키
*/
function storageKey(): string {
const cacheVersion = (globalThis as any)?.G7Config?.cache_version ?? 0;
return `${STORAGE_KEY_PREFIX}:${cacheVersion}`;
}
/**
* 판정된 모드를 localStorage 에 저장합니다.
*
* @param mode 저장할 모드
*/
function persistMode(mode: AssetUrlMode): void {
try {
globalThis.localStorage?.setItem(storageKey(), JSON.stringify({ mode, at: Date.now() }));
} catch {
// 저장 실패는 치명적이지 않다 — 다음 방문에 다시 판정하면 된다
}
}
@@ -5,6 +5,25 @@
>
> 형식: [Keep a Changelog](https://keepachangelog.com/ko/1.1.0/)
## [engine-v1.54.0] - 2026-07-20
### Added
#### 자산 URL 이중 모드 — 정적 최적화 서버에서의 동작 보장
- `support/assetUrl.ts`(신규) — 동적 엔드포인트 URL 생성을 한 곳으로 모았다. `getAssetUrlMode()` 가 `window.G7Config.assetUrlMode`(서버가 내려주는 초기값) → `G7Config.settings.general.asset_url_mode` → 기본값 `extension` 순으로 판정하고, `suffixed()` / `templateAsset()` / `moduleAsset()` / `pluginAsset()` / `extensionBundle()` / `layoutUrl()` / `layoutPreviewUrl()` 가 그 모드에 맞는 URL 을 만든다. 서버측 `App\Support\AssetUrl` 와 **동일 규칙**이며, 한쪽만 바꾸면 서버가 만든 URL 과 클라이언트가 만든 URL 이 어긋나 그 자산만 404 가 된다.
- 배경: nginx 의 정규식 location(`location ~* \.(js|css|json)$`)은 프리픽스 location 보다 먼저 매칭되므로, 확장자 붙은 동적 엔드포인트는 `try_files ... /index.php` 폴백이 실행될 기회 없이 nginx 가 직접 파일시스템을 열려 시도해 404 가 된다. aaPanel/CyberPanel/Plesk 기본 템플릿에 들어있는 블록이다.
- 확장자 없는 모드의 변환 규칙 — 고정 접미사는 제거(`routes.json` → `routes`), 번들은 접미사가 종류를 구분하므로 세그먼트로 강등(`bundle.js` → `bundle/js`), 와일드카드 자산은 경로가 곧 파일명이라 쿼리로 이동(`assets/{id}/js/a.js` → `assets/{id}?file=js/a.js`). 마지막 형태가 안전한 이유는 nginx 의 location 정규식이 쿼리스트링을 제외한 경로에만 매칭되기 때문이다.
- `setAssetUrlMode()` 는 **단방향 1회**만 허용한다(`extension → extensionless`). 역방향을 허용하면 양쪽 형태가 모두 실패하는 상황(PHP 다운·WAF 차단)에서 무한 왕복이 된다. 서버 설정은 바꾸지 않는다 — 미인증 클라이언트가 전역 설정을 뒤집을 수 있으면 안 된다.
- `restoreCachedMode()` 의 localStorage 캐시는 키에 `cache_version` 을 포함하고 24시간 TTL 을 둔다. 서버가 정상화된 뒤에도 클라이언트가 옛 모드에 영구 고착되지 않도록 하기 위함이다.
### Changed
#### 동적 엔드포인트 URL 생성부 14지점을 빌더 경유로 전환
- `routing/Router.ts`, `TemplateApp.ts`(4), `ComponentRegistry.ts`, `ErrorPageHandler.ts`, `LayoutLoader.ts`(2), `layout-editor/LayoutEditorChrome.tsx`, `layout-editor/hooks/{useEditorTemplateAssets,useInlineEdit,useLayoutDocument,useExtensionDocument}.ts` — `routes.json`·`config.json`·`components.json`·레이아웃 JSON URL 을 모두 `suffixed()` 로 생성한다.
- 기본 모드(`extension`)에서 생성 결과는 치환 이전과 **문자열까지 동일**하다. `suffixed()` 는 추가 쿼리를 `v` 보다 앞에 놓는데(`?with_source_meta=1&v=...`), 이는 편집기 문서 로드 호출부의 기존 순서를 보존하기 위한 것이다 — 쿼리 순서가 바뀌면 의미는 같아도 URL 문자열이 달라져 HTTP 캐시 키가 갈린다.
## [engine-v1.53.1] - 2026-07-12
### Fixed
@@ -13,6 +13,7 @@
import React, { type ComponentType } from 'react';
import { createLogger } from '../utils/Logger';
import { fetchWithRetry } from './networkResilience';
import { suffixed } from '../support/assetUrl';
const logger = createLogger('ComponentRegistry');
@@ -247,7 +248,7 @@ export class ComponentRegistry {
// 캐시 미스 - API에서 로드
// 네트워크 일시 실패(응답 없음)에만 재시도. HTTP 에러는 아래 !ok 분기가 종전대로 처리.
// @since engine-v1.53.0
const manifestUrl = `/api/templates/${this.templateId}/components.json`;
const manifestUrl = suffixed(`/api/templates/${this.templateId}/components`, 'json');
const response = await fetchWithRetry(manifestUrl, { label: 'components.json' });
if (!response.ok) {
@@ -8,6 +8,7 @@
import type { LayoutLoader } from './LayoutLoader';
import type { DataSourceManager, DataSource } from './DataSourceManager';
import { createLogger } from '../utils/Logger';
import { suffixed } from '../support/assetUrl';
const logger = createLogger('ErrorPageHandler');
@@ -83,7 +84,7 @@ export class ErrorPageHandler {
try {
// template.json fetch
const response = await fetch(`/api/templates/${this.templateId}/config.json`);
const response = await fetch(suffixed(`/api/templates/${this.templateId}/config`, 'json'));
if (!response.ok) {
if (this.debug) {
@@ -17,6 +17,7 @@ import type { ComponentRegistry } from './ComponentRegistry';
import type { ErrorHandlingMap } from '../types/ErrorHandling';
import { createLogger } from '../utils/Logger';
import { fetchWithRetry } from './networkResilience';
import { suffixed } from '../support/assetUrl';
import { G7DevToolsCore } from '../devtools/G7DevToolsCore';
import { getApiClient } from '../api/ApiClient';
@@ -744,14 +745,14 @@ export class LayoutLoader {
try {
// API 엔드포인트 구성 (캐시 버전 쿼리 파라미터 추가)
// 시스템 레이아웃 분기: __preview__ 는 별도 API 엔드포인트 사용
let baseUrl: string;
const version = this.cacheVersion > 0 ? this.cacheVersion : null;
let apiUrl: string;
if (layoutPath.startsWith('__preview__/')) {
const token = layoutPath.replace('__preview__/', '');
baseUrl = `/api/layouts/preview/${token}.json`;
apiUrl = suffixed(`/api/layouts/preview/${token}`, 'json', version);
} else {
baseUrl = `/api/layouts/${templateId}/${layoutPath}.json`;
apiUrl = suffixed(`/api/layouts/${templateId}/${layoutPath}`, 'json', version);
}
const apiUrl = this.cacheVersion > 0 ? `${baseUrl}?v=${this.cacheVersion}` : baseUrl;
logger.log('Fetching layout from API:', apiUrl);
@@ -13,6 +13,7 @@
*/
import { createLogger } from '../utils/Logger';
import { suffixed } from '../support/assetUrl';
const logger = createLogger('TranslationEngine');
@@ -221,20 +222,22 @@ export class TranslationEngine {
try {
// API 호출 (캐시 버전 쿼리 파라미터 추가, bustCache가 true면 타임스탬프도 추가)
let url = `${apiBaseUrl}/templates/${templateId}/lang/${locale}.json`;
// 쿼리 파라미터 구성
const queryParams: string[] = [];
if (this.cacheVersion > 0) {
queryParams.push(`v=${this.cacheVersion}`);
}
// 자산 URL 모드에 따라 `.json` 접미사가 붙거나 빠진다.
// 이 경로는 편집기 전용이 아니라 **모든 페이지가 타는 런타임 공통 경로**라,
// 여기만 확장자를 직접 조립하면 extensionless 환경에서 다국어가 통째로 404 가 되어
// 이슈 #486 의 원래 증상(화면이 온전히 뜨지 않음)이 다국어 계층에서 재현된다.
const extraParams: string[] = [];
if (bustCache) {
queryParams.push(`_=${Date.now()}`);
}
if (queryParams.length > 0) {
url += `?${queryParams.join('&')}`;
extraParams.push(`_=${Date.now()}`);
}
const url = suffixed(
`${apiBaseUrl}/templates/${templateId}/lang/${locale}`,
'json',
this.cacheVersion > 0 ? this.cacheVersion : null,
extraParams.length > 0 ? extraParams.join('&') : undefined,
);
const response = await fetch(url);
if (!response.ok) {
@@ -75,6 +75,7 @@ import { buildCoreActionRecipeSeed } from './spec/coreActionRecipes';
import { registerCoreWidgets } from './spec/registerCoreWidgets';
import { registerCoreEditors } from './spec/registerCoreEditors';
import { exposeLayoutEditorGlobals } from './spec/exposeLayoutEditorGlobals';
import { suffixed } from '../../support/assetUrl';
/**
* 편집기 셸 최소 너비(px) — 이 아래로는 셸을 압착하지 않고 브라우저 가로 스크롤로 흡수한다.
@@ -119,7 +120,7 @@ async function fetchPermissionCandidates(
if (typeof fetch !== 'function') return [];
try {
const response = await fetch(
`/api/admin/templates/${encodeURIComponent(templateIdentifier)}/editor/permission-candidates.json`,
suffixed(`/api/admin/templates/${encodeURIComponent(templateIdentifier)}/editor/permission-candidates`, 'json'),
{ credentials: 'same-origin', headers: buildAuthHeaders() },
);
if (!response.ok) return [];
@@ -223,7 +224,7 @@ function LayoutEditorChromeBody({
(async () => {
try {
const response = await fetch(
`/api/templates/${encodeURIComponent(templateIdentifier)}/components.json`,
suffixed(`/api/templates/${encodeURIComponent(templateIdentifier)}/components`, 'json'),
{ credentials: 'same-origin', headers: { Accept: 'application/json' } }
);
if (!response.ok) return;
@@ -1,3 +1,8 @@
// e2e:allow 이슈 #486 단위 A 는 서버 라우트 이중화 전용. 이 파일 변경은 편집기 CSS
// 엔드포인트 개명(editor/components.css → component-styles.css)을 따라간 기대값 수정뿐이며
// 브라우저 거동은 불변(URL 은 서버가 생성해 내려주고 hook 은 그대로 fetch).
// 자산 URL 모드의 브라우저 시나리오 spec 은 자가 복구를 도입하는 단위 D 에서 추가한다.
/**
* useEditorTemplateAssets 회귀 테스트
*
@@ -6,6 +11,7 @@
* hook 의 동작을 가드.
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { renderHook, waitFor } from '@testing-library/react';
import { useEditorTemplateAssets } from '../../hooks/useEditorTemplateAssets';
@@ -118,7 +124,7 @@ describe('useEditorTemplateAssets', () => {
// 못 실어 500(Route[login])으로 떨어지므로, Bearer fetch → `<style>` 로 주입해야 한다.
it('권한 가드 admin CSS 는 Bearer fetch → <style> 주입 (link 아님)', async () => {
window.localStorage.setItem('auth_token', 'tok-css');
const adminCssUrl = '/api/admin/templates/sirsoft-basic/editor/components.css?v=1';
const adminCssUrl = '/api/admin/templates/sirsoft-basic/editor/component-styles.css?v=1';
fetchSpy.mockImplementation(async (url: string) => {
if (url.includes('/editor-assets')) {
return {
@@ -128,7 +134,7 @@ describe('useEditorTemplateAssets', () => {
}),
};
}
if (url.includes('/editor/components.css')) {
if (url.includes('/editor/component-styles.css')) {
return { ok: true, text: async () => '.g7le-preview-dark .x{color:red}' };
}
if (url.includes('/components.json')) {
@@ -150,7 +156,7 @@ describe('useEditorTemplateAssets', () => {
expect(styleEl?.textContent).toContain('.g7le-preview-dark');
// CSS fetch 에 Bearer 헤더 부착
const cssCall = fetchSpy.mock.calls.find((c) => String(c[0]).includes('/editor/components.css'));
const cssCall = fetchSpy.mock.calls.find((c) => String(c[0]).includes('/editor/component-styles.css'));
expect(cssCall?.[1]?.headers?.Authorization).toBe('Bearer tok-css');
});
@@ -59,6 +59,7 @@ import { ComputedForm } from './ComputedForm';
import { InitialStateForm } from './InitialStateForm';
import { ErrorHandlingForm } from './ErrorHandlingForm';
import { DataSourceTab } from './DataSourceTab';
import { suffixed } from '../../../../support/assetUrl';
/** 8탭 키 — 헤더 와이어프레임 순서 */
export type PageSettingsTabKey =
@@ -124,7 +125,7 @@ async function fetchSeoExtensions(templateIdentifier: string): Promise<SeoExtens
if (typeof fetch !== 'function' || !templateIdentifier) return [];
try {
const response = await fetch(
`/api/admin/templates/${encodeURIComponent(templateIdentifier)}/editor/seo-candidates.json`,
suffixed(`/api/admin/templates/${encodeURIComponent(templateIdentifier)}/editor/seo-candidates`, 'json'),
{ credentials: 'same-origin', headers: buildAuthHeaders() },
);
if (!response.ok) return [];
@@ -31,6 +31,7 @@ import { SeoBotPreviewPanel } from './SeoBotPreviewPanel';
import type { BindingCandidate } from '../../spec/bindingCandidates';
import type { DataSourceOption } from '../../spec/candidatePools';
import { DataSourceChipLabel } from './DataSourceChipLabel';
import { suffixed } from '../../../../support/assetUrl';
/** seo.extensions 칩 — `{type,id}` */
export interface SeoExtensionRef {
@@ -171,7 +172,7 @@ export function SeoForm({
}
const qs = params.toString() ? `?${params.toString()}` : '';
const res = await fetch(
`/api/admin/templates/${encodeURIComponent(templateIdentifier)}/editor/seo-candidates.json${qs}`,
suffixed(`/api/admin/templates/${encodeURIComponent(templateIdentifier)}/editor/seo-candidates`, 'json', null, qs.replace(/^[?&]+/, '')),
{ credentials: 'same-origin', headers: buildAuthHeaders() },
);
const body = await res.json().catch(() => null);
@@ -30,6 +30,7 @@ import {
type EditorAccessError,
} from '../types/editorErrors';
import { buildAuthHeaders } from '../utils/authToken';
import { suffixed } from '../../../support/assetUrl';
const logger = createLogger('useEditorRoutes');
@@ -246,7 +247,7 @@ export function useEditorRoutes(options: UseEditorRoutesOptions): void {
// 먼저 실행되는 진입 fetch 이므로, 이를 가드 엔드포인트 + Bearer 토큰으로 전환하면
// 미인증/권한부족이 진입 시점에 즉시 401/403 으로 감지되어 chrome(트리/캔버스)이
// 렌더되기 전 AccessErrorPanel → 로그인 리다이렉트로 분기된다.
const url = `/api/admin/templates/${encodeURIComponent(templateIdentifier)}/editor/routes.json${versionQuery}`;
const url = suffixed(`/api/admin/templates/${encodeURIComponent(templateIdentifier)}/editor/routes`, 'json', null, versionQuery.replace(/^[?&]+/, ''));
// 편집 대상 템플릿의 lang dictionary 도 함께 적재 — 라우트 meta.title 에 있는
// `$t:user.*` 키가 부팅 템플릿(admin) lang 에는 없으므로 별도 로드 필요.
@@ -31,6 +31,7 @@ import {
type EditorAccessError,
} from '../types/editorErrors';
import { reseedPendingIntoEngine } from './pendingCustomTranslations';
import { suffixed } from '../../../support/assetUrl';
export interface EditorTemplateAssetsState {
componentRegistry: ComponentRegistry | null;
@@ -98,7 +99,7 @@ async function fetchLatestCacheVersion(identifier: string): Promise<number> {
try {
if (typeof fetch !== 'function') return 0;
const res = await fetch(
`/api/templates/${encodeURIComponent(identifier)}/config.json`,
suffixed(`/api/templates/${encodeURIComponent(identifier)}/config`, 'json'),
{ credentials: 'same-origin', headers: { Accept: 'application/json' } },
);
if (!res.ok) return 0;
@@ -46,6 +46,7 @@ import { trackEditorDocument } from '../devtools/editorTrackers';
import { readSanctumToken } from '../utils/authToken';
import { getCacheBustNonce, bumpCacheBustNonce } from '../utils/editorCacheBust';
import type { SaveResult } from './useLayoutDocument';
import { suffixed } from '../../../support/assetUrl';
/**
* 확장 편집 모드의 가상 path(`__extension__/{extensionId}`)에서 extensionId 를 추출한다.
@@ -420,9 +421,7 @@ export function useExtensionDocument(): UseExtensionDocumentResult {
const cacheVersion = (window as any).G7Config?.cache_version ?? 0;
// 클라이언트 캐시-버스트 nonce 합성 — useLayoutDocument 와 공용 카운터.
// 버전 복원/저장 후 reload 시 HTTP 캐시 stale 호스트 응답을 우회한다(확장 캔버스 미갱신 결함).
const url = `/api/layouts/${encodeURIComponent(
templateIdentifier,
)}/${hostLayoutName}.json?with_source_meta=1&v=${cacheVersion}.${getCacheBustNonce()}`;
const url = suffixed(`/api/layouts/${encodeURIComponent(templateIdentifier)}/${hostLayoutName}`, 'json', `${cacheVersion}.${getCacheBustNonce()}`, 'with_source_meta=1');
const token = readSanctumToken();
const headers: Record<string, string> = { Accept: 'application/json' };
if (token) headers.Authorization = `Bearer ${token}`;
@@ -35,6 +35,7 @@ import {
} from '../devtools/editorTrackers';
import { setPendingValue, setPendingValues } from './pendingCustomTranslations';
import { TranslationEngine } from '../../TranslationEngine';
import { suffixed } from '../../../support/assetUrl';
import {
stripBindingTokens,
buildParamizedKeyText,
@@ -739,7 +740,7 @@ export async function bustTranslationCache(
// 최신 cache_version 을 노출하므로 그것을 읽어 엔진 버전을 갱신한 뒤 재로드한다.
try {
const cfg = await fetch(
`/api/templates/${encodeURIComponent(templateIdentifier)}/config.json`,
suffixed(`/api/templates/${encodeURIComponent(templateIdentifier)}/config`, 'json'),
{ headers: { Accept: 'application/json' }, credentials: 'same-origin' },
).then((r) => (r.ok ? r.json() : null));
const v = cfg?.data?.cache_version ?? cfg?.cache_version;
@@ -32,6 +32,7 @@ import { parseEditorPath } from './useElementSelection';
import { readSanctumToken } from '../utils/authToken';
import { getCacheBustNonce, bumpCacheBustNonce } from '../utils/editorCacheBust';
import { hasPending, flushPending } from './pendingCustomTranslations';
import { suffixed } from '../../../support/assetUrl';
/**
* 로드된 레이아웃 문서 — 백엔드 응답의 data 부분 (병합 + 확장 + 메타 포함)
@@ -440,7 +441,7 @@ export function useLayoutDocument(): UseLayoutDocumentResult {
const cacheVersion = (window as any).G7Config?.cache_version ?? 0;
// 저장 후 클라이언트 캐시-버스트 nonce 합성 — 같은 세션 저장→재로드가
// 옛 cache_version 으로 stale 응답을 받지 않도록 단조 증가 nonce 를 함께 붙인다.
const url = `/api/layouts/${encodeURIComponent(templateIdentifier)}/${layoutName}.json?with_source_meta=1&v=${cacheVersion}.${getCacheBustNonce()}`;
const url = suffixed(`/api/layouts/${encodeURIComponent(templateIdentifier)}/${layoutName}`, 'json', `${cacheVersion}.${getCacheBustNonce()}`, 'with_source_meta=1');
const token = readSanctumToken();
const headers: Record<string, string> = { Accept: 'application/json' };
if (token) {
+21 -4
View File
@@ -16,9 +16,16 @@
@include('partials.error-fallback-styles')
@endif
{{-- 자산 URL 자가 복구 헬퍼 — CSS <link> 의 onerror 보다 먼저 정의되어야 한다 --}}
@include('partials.asset-url-recovery')
<!-- 템플릿 컴포넌트 스타일 -->
@if(!empty($activeAdminTemplate))
<link rel="stylesheet" href="/api/templates/assets/{{ $activeAdminTemplate }}/css/components.css?v={{ $extensionCacheVersion }}">
{{-- onerror: 정적 최적화 서버에서 확장자 붙은 CSS 가 가로채였을 때
확장자 없는 형태로 1회 교체한다(무스타일 화면 방지). 링크당 1회. --}}
<link rel="stylesheet"
href="{{ \App\Support\AssetUrl::templateAsset($activeAdminTemplate, 'css/components.css', $extensionCacheVersion) }}"
onerror="window.__g7AssetUrl && window.__g7AssetUrl.recoverStylesheet(this);">
@endif
</head>
<body>
@@ -54,7 +61,14 @@
// 키가 새 버전으로 전환되어 routes.json/lang 변경이 즉시 가시화된다.
// 미주입 시 클라이언트가 항상 `v0` 으로 호출 → `template:cache-clear` 가 v 와일드카드를
// 처리하지 못해 캐시가 영구 stale 되는 결함이 발생.
cache_version: {{ (int) ($extensionCacheVersion ?? 0) }}
cache_version: {{ (int) ($extensionCacheVersion ?? 0) }},
// 자산 URL 모드 — 'extension'(기본) | 'extensionless'.
// 정적 최적화 블록이 동적 응답을 가로채는 서버에서 확장자 없는 형태로 전환.
// 부트스트랩 자가 복구가 런타임에 뒤집으므로 최상위 키로 노출한다.
// 자가 복구가 <head> 에서 이미 전환을 확정했다면 그 값을 잇는다.
// 이 대입은 G7Config 객체를 통째로 교체하므로, 독립 전역을 읽지 않으면
// 복원/전환 결과가 여기서 덮여 사라진다.
assetUrlMode: window.__g7AssetUrlMode || '{{ \App\Support\AssetUrl::mode() }}'
};
@if(isset($errorCode) && isset($errorLayout))
// 에러 상태 정보 (503 의존성 미충족 등)
@@ -71,8 +85,11 @@
{{-- 코어 엔진 + 템플릿 컴포넌트 번들 로드 → 초기화 (재시도 + 폴백 UI) --}}
@include('partials.bootstrap-scripts', [
'templateType' => 'admin',
'coreEngineSrc' => asset('build/core/template-engine.min.js') . '?v=' . filemtime(public_path('build/core/template-engine.min.js')),
'componentsSrc' => '/api/templates/assets/' . $activeAdminTemplate . '/js/components.iife.js?v=' . $extensionCacheVersion,
{{-- 코어 엔진 번들은 public/ 의 실물 정적 파일이라 자산 URL 이중 모드 대상이 아니다.
미빌드 상태에서 filemtime() 이 warning 을 내지 않도록 file_exists 가드
(coreEditorAsset/coreDevToolsAsset 와 동일 패턴). --}}
'coreEngineSrc' => asset('build/core/template-engine.min.js') . '?v=' . (file_exists(public_path('build/core/template-engine.min.js')) ? filemtime(public_path('build/core/template-engine.min.js')) : 0),
'componentsSrc' => \App\Support\AssetUrl::templateAsset($activeAdminTemplate, 'js/components.iife.js', $extensionCacheVersion),
'initConfig' => array_filter([
'templateId' => $activeAdminTemplate,
'templateType' => 'admin',
+23 -4
View File
@@ -16,9 +16,16 @@
@include('partials.error-fallback-styles')
@endif
{{-- 자산 URL 자가 복구 헬퍼 — CSS <link> 의 onerror 보다 먼저 정의되어야 한다 --}}
@include('partials.asset-url-recovery')
<!-- 템플릿 컴포넌트 스타일 -->
@if(!empty($activeUserTemplate))
<link rel="stylesheet" href="/api/templates/assets/{{ $activeUserTemplate }}/css/components.css?v={{ $extensionCacheVersion }}">
{{-- onerror: 정적 최적화 서버에서 확장자 붙은 CSS 가 가로채였을 때
확장자 없는 형태로 1회 교체한다(무스타일 화면 방지). 링크당 1회. --}}
<link rel="stylesheet"
href="{{ \App\Support\AssetUrl::templateAsset($activeUserTemplate, 'css/components.css', $extensionCacheVersion) }}"
onerror="window.__g7AssetUrl && window.__g7AssetUrl.recoverStylesheet(this);">
@endif
</head>
<body>
@@ -51,7 +58,16 @@
coreDevToolsAsset: '{{ asset('build/core/devtools.min.js') }}?v={{ file_exists(public_path('build/core/devtools.min.js')) ? filemtime(public_path('build/core/devtools.min.js')) : 0 }}',
// 확장 캐시 버전 SSoT — 클라이언트 fetch (`?v=`) 동반 필수.
// 자세한 설명은 admin.blade.php 참조.
cache_version: {{ (int) ($extensionCacheVersion ?? 0) }}
cache_version: {{ (int) ($extensionCacheVersion ?? 0) }},
// 자산 URL 모드 — 'extension'(기본) | 'extensionless'.
// 정적 최적화 블록(location ~* \.(js|css|json)$)이 동적 응답을 가로채는
// 서버에서 확장자 없는 형태로 전환한다. 부트스트랩 자가 복구가 실패 시
// 이 값을 런타임에 뒤집으므로 최상위 키로 노출한다(설정값 SSoT 는
// G7Config.settings.general.asset_url_mode).
// 자가 복구가 <head> 에서 이미 전환을 확정했다면 그 값을 잇는다.
// 이 대입은 G7Config 객체를 통째로 교체하므로, 독립 전역을 읽지 않으면
// 복원/전환 결과가 여기서 덮여 사라진다.
assetUrlMode: window.__g7AssetUrlMode || '{{ \App\Support\AssetUrl::mode() }}'
};
@if(isset($errorCode) && isset($errorLayout))
// 에러 상태 정보 (503 의존성 미충족 등)
@@ -68,8 +84,11 @@
{{-- 코어 엔진 + 템플릿 컴포넌트 번들 로드 → 초기화 (재시도 + 폴백 UI) --}}
@include('partials.bootstrap-scripts', [
'templateType' => 'user',
'coreEngineSrc' => asset('build/core/template-engine.min.js') . '?v=' . filemtime(public_path('build/core/template-engine.min.js')),
'componentsSrc' => '/api/templates/assets/' . $activeUserTemplate . '/js/components.iife.js?v=' . $extensionCacheVersion,
{{-- 코어 엔진 번들은 public/ 의 실물 정적 파일이라 자산 URL 이중 모드 대상이 아니다.
미빌드 상태에서 filemtime() 이 warning 을 내지 않도록 file_exists 가드
(coreEditorAsset/coreDevToolsAsset 와 동일 패턴). --}}
'coreEngineSrc' => asset('build/core/template-engine.min.js') . '?v=' . (file_exists(public_path('build/core/template-engine.min.js')) ? filemtime(public_path('build/core/template-engine.min.js')) : 0),
'componentsSrc' => \App\Support\AssetUrl::templateAsset($activeUserTemplate, 'js/components.iife.js', $extensionCacheVersion),
'initConfig' => array_filter([
'templateId' => $activeUserTemplate,
'templateType' => 'user',
+4
View File
@@ -844,6 +844,10 @@ if (isset($_GET['ajax_action'])) {
<span>SEO 캐시 삭제</span>
<span class="text-[10px] opacity-60">(seo:clear)</span>
</button>
<button onclick="runCommand('g7:asset-url-mode')" class="inline-flex items-center gap-1.5 px-3 py-2 bg-slate-600 hover:bg-slate-700 text-white text-xs font-medium rounded transition-colors">
<span>자산 URL 방식 확인</span>
<span class="text-[10px] opacity-60">(g7:asset-url-mode)</span>
</button>
<button onclick="runCommand('seo:stats')" 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>SEO 통계</span>
<span class="text-[10px] opacity-60">(seo:stats)</span>
@@ -0,0 +1,177 @@
{{--
자산 URL 모드 자가 복구 — 공용 헬퍼 (이슈 #486 §5)
`<head>` 의 CSS `<link>` 보다 **먼저** 로드되어야 한다. CSS 링크의 onerror 가
이 헬퍼를 호출하기 때문이며, 부트스트랩 스크립트(`<body>`)도 같은 헬퍼를 재사용한다.
코어 번들 로드 전에 실행되므로 외부 의존성 없는 순수 인라인 JS 여야 한다
(닭-달걀: 코어가 없으면 코어를 받아올 코드도 없다).
## 배경
nginx 의 정적 최적화 블록은 정규식 location 이라 프리픽스 location 보다 먼저
매칭된다. 그 안에 PHP 핸들러가 없으면 확장자 붙은 동적 엔드포인트가 PHP 에
도달하지 못한 채 404 가 된다. 관리자 화면조차 뜨지 않으므로 "설정을 바꾸세요"
안내는 순환 참조 — 브라우저가 스스로 복구해야 한다.
## 불변식 (계획서 §12)
L1 전환은 단방향(extension → extensionless) 1회. 역방향 폴백을 만들지 않는다.
L3 자동 location.reload() 금지.
L5 서버 설정은 건드리지 않는다 (미인증 클라이언트의 전역 설정 변경 금지).
L7 localStorage 캐시는 cache_version 을 키에 포함하고 TTL 을 둔다.
--}}
<script>
(function () {
'use strict';
var MODE_EXTENSIONLESS = 'extensionless';
var FILE_QUERY_PARAM = 'file';
var STORAGE_TTL_MS = 24 * 60 * 60 * 1000;
// cache_version 은 blade 에서 직접 주입한다. 이 파샬은 <head> 에서 실행되어
// window.G7Config(<body> 에서 정의) 가 아직 없기 때문 — 참조하면 항상 0 이 되어
// 캐시 키가 어긋난다.
var CACHE_VERSION = {{ (int) ($extensionCacheVersion ?? 0) }};
function storageKey() {
return 'g7_asset_url_mode:' + CACHE_VERSION;
}
/**
* 확장자 형태 API URL 을 확장자 없는 형태로 변환한다.
*
* `resources/js/core/support/assetUrl.ts::convertToCurrentMode` 와 **동일 규칙**이어야
* 한다. 여기는 코어 번들 로드 전이라 import 가 불가능해 인라인으로 둔다 — 드리프트는
* `assetUrl.test.ts` 의 대조 케이스가 잡는다.
*
* 변환 대상이 아니면 null. 코어 엔진 번들(`/build/...`)은 public/ 의 실물 정적
* 파일이라 변환하면 오히려 깨지므로 대상에서 제외된다.
*
* @param url 원본 URL
* @returns 변환된 URL 또는 null
*/
function toExtensionless(url) {
if (!url) return null;
// `<script>.src` / `<link>.href` 는 **절대 URL** 을 돌려준다
// (`https://host/api/...`). same-origin 이면 경로만 남긴다 — 이 정규화를
// 빠뜨리면 부트스트랩 재시도 경로에서 변환이 항상 null 이 되어 자가 복구가
// 통째로 죽는다(외형은 "3회 재시도 후 폴백 UI" 라 원인이 드러나지 않는다).
var origin = window.location && window.location.origin;
if (origin && url.indexOf(origin) === 0) {
url = url.slice(origin.length);
}
if (url.indexOf('/api/') !== 0) return null;
var qi = url.indexOf('?');
var path = qi === -1 ? url : url.slice(0, qi);
var query = qi === -1 ? '' : url.slice(qi + 1);
var bundle = path.match(/^\/api\/(modules|plugins)\/bundle\.(js|css)$/);
if (bundle) {
return '/api/' + bundle[1] + '/bundle/' + bundle[2] + (query ? '?' + query : '');
}
var asset = path.match(/^\/api\/(templates|modules|plugins)\/assets\/([^/]+)\/(.+)$/);
if (asset) {
return '/api/' + asset[1] + '/assets/' + asset[2] +
'?' + FILE_QUERY_PARAM + '=' + encodeURIComponent(decodeURIComponent(asset[3])) +
(query ? '&' + query : '');
}
var suffixed = path.match(/^(\/api\/.+)\.(json|js|css)$/);
if (suffixed) {
return suffixed[1] + (query ? '?' + query : '');
}
return null;
}
/**
* 모드 전환을 1회 확정한다 (L1 — 단방향 1회).
*
* 서버 설정은 바꾸지 않는다(L5). 전역 플래그와 localStorage 캐시만 갱신하며,
* 이후 엔진의 모든 fetch 가 이 값을 읽어 올바른 형태를 쓴다.
*
* @returns 이번 호출로 전환되었으면 true
*/
function switchToExtensionless() {
if (window.__g7AssetUrlMode === MODE_EXTENSIONLESS) return false;
// 독립 전역에 기록한다. <body> 의 `window.G7Config = {...}` 대입이 이 파샬보다
// 나중에 실행되어 객체를 통째로 교체하므로, G7Config 에만 쓰면 덮여 사라진다.
// G7Config 는 이 값을 초기값으로 읽어간다(app/admin blade 참조).
window.__g7AssetUrlMode = MODE_EXTENSIONLESS;
if (window.G7Config) window.G7Config.assetUrlMode = MODE_EXTENSIONLESS;
try {
window.localStorage.setItem(storageKey(), JSON.stringify({
mode: MODE_EXTENSIONLESS,
at: Date.now()
}));
} catch (e) { /* 저장 실패는 치명적이지 않다 */ }
return true;
}
/**
* 이전 방문에서 확정된 모드를 복원한다 (L7).
*
* cache_version 을 키에 포함하고 TTL 을 둬서 서버가 정상화된 뒤에도
* 클라이언트가 옛 모드에 영구 고착되지 않도록 한다.
*/
function restoreCachedMode() {
try {
var raw = window.localStorage.getItem(storageKey());
if (!raw) return false;
var parsed = JSON.parse(raw);
if (!parsed || parsed.mode !== MODE_EXTENSIONLESS) return false;
if (typeof parsed.at !== 'number' || Date.now() - parsed.at > STORAGE_TTL_MS) {
window.localStorage.removeItem(storageKey());
return false;
}
window.__g7AssetUrlMode = MODE_EXTENSIONLESS;
if (window.G7Config) window.G7Config.assetUrlMode = MODE_EXTENSIONLESS;
return true;
} catch (e) {
return false;
}
}
/**
* CSS `<link>` 로드 실패 시 확장자 없는 형태로 1회 교체한다.
*
* 스타일 부재는 앱을 죽이지 않으므로(엔진의 CSS 로더도 실패를 resolve 로 처리)
* 재교체가 실패해도 조용히 끝낸다 — 폴백 UI 를 띄우지 않는다(과잉 적용 경계).
* 교체는 링크당 1회만 (`data-g7-recovered` 마킹).
*
* @param link 실패한 <link> 요소
*/
function recoverStylesheet(link) {
if (!link || link.getAttribute('data-g7-recovered') === '1') return;
link.setAttribute('data-g7-recovered', '1');
var converted = toExtensionless(link.getAttribute('href') || '');
if (!converted) return;
switchToExtensionless();
link.href = converted;
}
restoreCachedMode();
window.__g7AssetUrl = {
MODE_EXTENSIONLESS: MODE_EXTENSIONLESS,
toExtensionless: toExtensionless,
switchToExtensionless: switchToExtensionless,
restoreCachedMode: restoreCachedMode,
recoverStylesheet: recoverStylesheet
};
})();
</script>
@@ -38,11 +38,37 @@
window.addEventListener('pagehide', function () { window.__g7Unloading = true; });
window.addEventListener('pageshow', function (e) { if (e.persisted) window.__g7Unloading = false; });
// ─────────────────────────────────────────────────────────────────────────
// 자산 URL 모드 자가 복구 (이슈 #486)
//
// nginx 의 정적 최적화 블록(`location ~* \.(js|css|json)$`)은 정규식 location 이라
// 프리픽스 location 보다 먼저 매칭되고, 그 안에 PHP 핸들러가 없으면 확장자 붙은
// 동적 엔드포인트가 PHP 에 도달하지 못한 채 404 가 된다. 이 경우 관리자 화면조차
// 뜨지 않으므로 "설정을 바꾸세요" 안내는 순환 참조다 — 브라우저가 스스로 복구한다.
//
// 불변식 (계획서 §12):
// L1 전환은 단방향(extension → extensionless) 1회. 역방향 폴백을 만들지 않는다.
// 양쪽 다 실패하는 상황(PHP 다운·WAF)에서 무한 왕복이 되기 때문.
// L2 전환 시도는 기존 MAX_ATTEMPTS 예산 안에서 소비한다(별도 예산 신설 금지).
// L3 자동 location.reload() 금지. 새로고침은 폴백 UI 의 사용자 클릭만.
// L4 모든 실패 경로는 renderFallback() 으로 수렴하고 종료한다.
// L5 서버 설정은 건드리지 않는다(미인증 클라이언트의 전역 설정 변경 금지).
// L8 pending 카운터 — 실패 element 제거 후 교체, onload 는 정확히 1회만 감소.
// ─────────────────────────────────────────────────────────────────────────
// 자산 URL 모드 자가 복구 헬퍼 — `partials/asset-url-recovery` 가 <head> 에서
// 미리 정의한다(CSS <link> 의 onerror 가 그것을 먼저 쓰기 때문). 여기서는 재사용만 한다.
// 헬퍼가 없으면(부분 include 등) 자가 복구 없이 기존 재시도 로직으로만 동작한다.
var assetUrl = window.__g7AssetUrl || null;
// 부트스트랩 상태 — 정적 <script> 의 onerror/onload 가 여기에 기록한다
var bootstrap = window.__g7Bootstrap = {
failed: false,
pending: 0,
/** 모드 전환을 이미 시도했는지 (L1 — 페이지 수명당 1회) */
modeSwitched: false,
/**
* 정적 <script> 로드 실패 시 동적 재시도를 시작한다.
*
@@ -64,6 +90,19 @@
return;
}
// 자산 URL 모드 전환 (L1·L2) — 확장자 형태가 실패했고 아직 전환 전이라면,
// 지연 재시도 대신 확장자 없는 형태로 **즉시 1회** 시도한다.
// 이 시도는 기존 예산(attempt)을 그대로 소비하므로 총 시도 횟수는 불변이다.
var converted = (bootstrap.modeSwitched || !assetUrl) ? null : assetUrl.toExtensionless(src);
if (converted && converted !== src) {
bootstrap.modeSwitched = true;
assetUrl.switchToExtensionless();
console.warn(LABEL + ' Retrying with extensionless URL: ' + converted);
bootstrap.replaceScript(converted, attempt);
return;
}
var delay = BASE_DELAY_MS * Math.pow(2, attempt - 1);
console.warn(LABEL + ' Script load failed (attempt ' + attempt + '/' + MAX_ATTEMPTS + '), retrying in ' + delay + 'ms: ' + src);
@@ -83,6 +122,33 @@
}, delay);
},
/**
* 스크립트를 지연 없이 즉시 교체 삽입한다 (모드 전환 재시도용).
*
* L8 — onload 는 pending 을 정확히 1회만 감소시키고, 실패한 element 는
* 제거한 뒤 다음 경로로 넘어간다. 실패 시에도 attempt 를 증가시켜
* MAX_ATTEMPTS 예산을 공유하므로 총 네트워크 시도 횟수가 늘지 않는다(L2).
*
* @param src 삽입할 스크립트 URL
* @param attempt 현재 시도 번호
*/
replaceScript: function (src, attempt) {
if (window.__g7Unloading) return;
var script = document.createElement('script');
script.src = src;
script.async = false; // 삽입 순서대로 실행 (코어 → 컴포넌트 순서 보장)
script.onload = function () {
bootstrap.pending -= 1;
bootstrap.tryInit();
};
script.onerror = function () {
if (script.parentNode) script.parentNode.removeChild(script);
bootstrap.retry(src, attempt + 1);
};
document.head.appendChild(script);
},
/**
* 부트스트랩 최종 실패 시 사용자에게 보이는 정적 폴백을 심는다.
*