fix(core,extensions): 보안 결함 3건과 이중저장소·레이아웃 중복키 결함군 폐쇄

KISA 제보 3건(KVE-2026-2010/2011/2018)과 그 동일 계열 형제 결함을 전수 조치하고,
그 과정에서 드러난 두 결함군을 함께 닫는다.

- 검증 시점과 연결 시점이 host 를 다르게 읽던 SSRF 통로를 정규화 SSoT 한 곳으로 모았다
- 세션을 여는 지점(2FA 완료·토큰 재발급)이 잠금 검사를 거치지 않아 계정 잠금이 우회됐다
- 인증도 서명도 없는 브라우저 리턴 콜백이 주문 상태를 바꾸던 통로를 4 PG 전부에서 닫고,
 소유권을 대조하는 close-report 를 토스에도 신설했다. 그 결과 정리 주체를 잃는
 결제창 미완료 주문은 만료 자동취소가 거둔다
- 저장소 A(_local)에만 쓰는 경로가 B 의 값을 조용히 덮던 회귀를 정본 writer 로 닫았다
 (engine-v1.63.5). 한 방향만 보던 정적 검사에 반대 방향 축과 양방향 계약 테스트를 더했다
- 레이아웃 JSON 의 같은 객체 중복 키가 앞선 선언을 오류 없이 삼키던 결함군을 닫았다
This commit is contained in:
HeuJung committed 2026-09-02 17:36:11 +09:00
1 parent d4439ea30a
commit 21fc114f37
137 files changed
+6470 -829

No files matched your search

@@ -640,6 +640,17 @@ export class ActionDispatcher {
*/
private previewMode: boolean = false;
/**
* `writeLocalState` 재진입 깊이.
*
* 미러 쓰기(`G7Core.state.setLocal`)가 다시 저장소 A writer 를 호출하는 구조라,
* 그 안에서 같은 헬퍼로 되돌아오면 무한 재귀가 된다. 0 보다 크면 미러를 붙이지 않고
* 원본 writer 만 호출한다.
*
* @since engine-v1.63.5
*/
private localMirrorDepth = 0;
/**
* startInterval 핸들러로 등록된 타이머 맵.
*
@@ -2350,6 +2361,12 @@ export class ActionDispatcher {
// 기존 loadingActions 상태 유지하면서 새 액션 추가
const currentLoadingActions = context.state?.loadingActions || {};
// loadingActions 는 apiCall 을 발화한 컴포넌트 자신의 일시적 표시 플래그다.
// 저장소 B 는 페이지 단위 공유 슬롯이라 미러하면 ① 한 컴포넌트의 로딩 플래그가
// 다른 컴포넌트로 새고 ② __g7ForcedLocalFields 가 그 값을 모든 컴포넌트에 강제하는데,
// 해제는 키 생략으로 하므로 깊은 병합에서 지워지지 않아 스피너가 영구히 남는다.
// 소비자는 자기 렌더 컨텍스트로만 읽는다.
// audit:allow local-store-write-must-mirror 컴포넌트별 일시 표시 플래그 (위 사유)
context.setState({
loadingActions: {
...currentLoadingActions,
@@ -2565,7 +2582,7 @@ export class ActionDispatcher {
const updateWithMode = resultToMergeMode !== 'deep'
? { ...update, __mergeMode: resultToMergeMode }
: update;
context.setState(updateWithMode);
this.writeLocalState(context, updateWithMode);
logger.log(`[resultTo] Saved to _local.${resolvedKey} (merge=${resultToMergeMode}):`, result);
} else if (target === '_local' && this.globalStateUpdater) {
// init_actions 등에서 componentContext가 없는 경우 globalStateUpdater를 통해 _local 업데이트
@@ -2807,6 +2824,12 @@ export class ActionDispatcher {
const currentLoadingActions = context.state?.loadingActions || {};
const { [actionId]: _, ...remainingLoadingActions } = currentLoadingActions;
// loadingActions 는 apiCall 을 발화한 컴포넌트 자신의 일시적 표시 플래그다.
// 저장소 B 는 페이지 단위 공유 슬롯이라 미러하면 ① 한 컴포넌트의 로딩 플래그가
// 다른 컴포넌트로 새고 ② __g7ForcedLocalFields 가 그 값을 모든 컴포넌트에 강제하는데,
// 해제는 키 생략으로 하므로 깊은 병합에서 지워지지 않아 스피너가 영구히 남는다.
// 소비자는 자기 렌더 컨텍스트로만 읽는다.
// audit:allow local-store-write-must-mirror 컴포넌트별 일시 표시 플래그 (위 사유)
context.setState({
loadingActions: remainingLoadingActions
});
@@ -4025,7 +4048,7 @@ export class ActionDispatcher {
const finalPayload = mergeMode === 'deep'
? this.deepMergeWithState(resolvedPayload, currentState)
: resolvedPayload; // replace, shallow: DynamicRenderer에서 처리
context.setState(finalPayload);
this.writeLocalState(context, finalPayload);
if (setStateId && devTools) setTimeout(() => devTools.completeStateChange(setStateId), 0);
return finalPayload;
} else {
@@ -4060,6 +4083,10 @@ export class ActionDispatcher {
: cleanPayload; // replace, shallow: 병합 없이 payload 그대로
logger.log(`[handleSetState] scope=${scope}: 타겟 컨텍스트에 상태 업데이트`, finalPayload);
// scope:'parent'|'root' 은 `_local` 정본이 아니라 레이아웃 컨텍스트 스택의
// 부모/루트 슬롯을 노린다. 여기서 저장소 B 를 함께 쓰면 모달의 setState 가
// 페이지 _local 을 오염시킨다(사례 29).
// audit:allow local-store-write-must-mirror 부모/루트 슬롯 전용 (위 사유)
targetContext.setState(finalPayload);
if (setStateId && devTools) setTimeout(() => devTools.completeStateChange(setStateId), 0);
@@ -4358,7 +4385,7 @@ export class ActionDispatcher {
const finalPayload = mergeMode === 'deep'
? this.deepMergeWithState(resolvedPayload, currentState)
: resolvedPayload; // replace, shallow: DynamicRenderer에서 처리
context.setState(finalPayload);
this.writeLocalState(context, finalPayload, undefined, { scope });
// DevTools: 상태 변경 완료
if (setStateId && devTools) setTimeout(() => devTools.completeStateChange(setStateId), 0);
return finalPayload;
@@ -4510,6 +4537,10 @@ export class ActionDispatcher {
const update = this.createNestedUpdate(nestedPath, value, currentLocal);
const mergedState = { ...currentLocal, ...update };
logger.log(`[handleParentScopeSetState] ${target}: 로컬 상태 중첩 경로 업데이트`, update);
// $parent/$root 스코프는 `_local` 정본이 아니라 레이아웃 컨텍스트 스택의 부모/루트
// 슬롯을 대상으로 한다. 저장소 B 를 함께 쓰면 모달의 setState 가 페이지 _local 을
// 오염시킨다(사례 29). 스택 state·dataContext 동기화는 바로 아래에서 직접 수행한다.
// audit:allow local-store-write-must-mirror 부모/루트 슬롯 전용 (위 사유)
targetContext.setState(update);
// 스택의 state와 dataContext._local 모두 업데이트하여
// 다음 setState 호출 시 currentLocal이 최신 값을 읽고,
@@ -4536,6 +4567,10 @@ export class ActionDispatcher {
? { ...currentLocal, ...cleanPayload }
: this.deepMergeWithState(cleanPayload, currentLocal);
logger.log(`[handleParentScopeSetState] ${target}: 로컬 상태 업데이트 (mergeMode=${mergeMode})`, expectedState);
// $parent/$root 스코프는 `_local` 정본이 아니라 레이아웃 컨텍스트 스택의 부모/루트
// 슬롯을 대상으로 한다. 저장소 B 를 함께 쓰면 모달의 setState 가 페이지 _local 을
// 오염시킨다(사례 29). 스택 state·dataContext 동기화는 바로 아래에서 직접 수행한다.
// audit:allow local-store-write-must-mirror 부모/루트 슬롯 전용 (위 사유)
targetContext.setState(setStatePayload);
// 스택의 state와 dataContext._local 모두 업데이트하여
// 다음 setState 호출 시 currentLocal이 최신 값을 읽고,
@@ -4850,7 +4885,7 @@ export class ActionDispatcher {
logger.log('[handleSetError] Error set to global state:', errorMessage);
} else if (context.setState) {
// 로컬 상태에 저장 (기본값)
context.setState({ apiError: errorMessage });
this.writeLocalState(context, { apiError: errorMessage });
logger.log('[handleSetError] Error set to local state:', errorMessage);
} else {
logger.warn('[handleSetError] Cannot set error: no state updater available');
@@ -5981,10 +6016,10 @@ export class ActionDispatcher {
// 깊은 병합 수행: 기존 상태의 다른 필드 유지
const mergedValues = this.deepMergeWithState(mappedValues, context.state || {});
logger.log(`callExternal: merged with existing state`, mergedValues);
context.setState(mergedValues);
this.writeLocalState(context, mergedValues);
} else if (callbackEvent && context.setState) {
// callbackSetState가 없으면 기존 방식으로 이벤트 결과 저장
context.setState({ [`${callbackEvent.replace(/:/g, '_')}_result`]: data });
this.writeLocalState(context, { [`${callbackEvent.replace(/:/g, '_')}_result`]: data });
}
// callbackAction 처리: 콜백 데이터를 $event로 전달하여 액션 실행 (engine-v1.9.0+)
@@ -6134,7 +6169,7 @@ export class ActionDispatcher {
// 깊은 병합 수행: 기존 상태의 다른 필드 유지
const mergedValues = this.deepMergeWithState(mappedValues, context.state || {});
logger.log(`callExternalEmbed: merged with existing state`, mergedValues);
context.setState(mergedValues);
this.writeLocalState(context, mergedValues);
}
// callbackAction 처리: 콜백 데이터를 $event로 전달하여 액션 실행 (engine-v1.9.0+)
@@ -6381,7 +6416,7 @@ export class ActionDispatcher {
// 기본값이 있고 상태에 설정해야 하는 경우
if (stateKey && context.setState) {
context.setState({ [stateKey]: defaultValue });
this.writeLocalState(context, { [stateKey]: defaultValue });
}
return defaultValue;
@@ -6400,7 +6435,7 @@ export class ActionDispatcher {
// 상태에 설정
if (stateKey && context.setState) {
context.setState({ [stateKey]: parsedValue });
this.writeLocalState(context, { [stateKey]: parsedValue });
}
return parsedValue;
@@ -6410,6 +6445,180 @@ export class ActionDispatcher {
}
}
/**
* 저장소 A 전용 `_local` 쓰기를 저장소 B(canonical `_global._local`)에도 함께 반영한다.
*
* 엔진이 선언한 이중 저장소 불변조건(DynamicRenderer `performStateUpdate` 상단 주석)은
* "B 가 플러그인/핸들러가 읽는 정본이고, A 는 쓰는 시점에 강제로 일치시키는 미러" 다.
* 그런데 커스텀 핸들러·resultTo·외부 콜백 등 여러 쓰기 경로가 `context.setState`
* (= 저장소 A) 만 갱신해 왔다. engine-v1.63.3 이 sequence 후속 액션의 `_local` 을
* live B 기준으로 바꾼 뒤로, B 에 이미 키가 있으면 `addMissingLeafKeys` 보충 대상에서
* 빠져 A 의 값이 조용히 유실된다 (상품상세 「바로 구매」·「장바구니 담기」가 빈 배열을
* 전송해 422 — 예외도 콘솔 에러도 남지 않는다).
*
* 이 헬퍼는 그 쓰기를 `G7Core.state.setLocal({ render: false })` 로 승격해
* B · `__g7PendingLocalState` · `__g7ForcedLocalFields` · `__g7SetLocalOverrideKeys` ·
* `__g7SequenceLocalSync` 를 함께 갱신한다. 마지막 것이 핵심이다 — `handleSequence` 는
* 커스텀 핸들러 뒤에 **오직 그 변수로만** currentState 를 갱신하는데, `context.setState`
* 경로는 그 변수를 전혀 건드리지 않아 엔진이 마련한 전파 장치가 사문화돼 있었다.
*
* 아래 조건에서는 미러를 붙이지 않고 원본 writer 만 호출한다(종전 동작 유지):
*
* 1. writer 부재 — 갱신할 대상이 없다
* 2. 함수형 업데이터 — payload 를 추출할 수 없다 (`handleLocalSetState` 는 지원한다)
* 3. `scope: 'parent' | 'root'` — 대상 슬롯이 `_local` 정본이 아니다
* 4. 모달 컨텍스트 스택 > 0 — 모달의 쓰기가 페이지 B 를 흡수하는 것 방지(사례 29).
* `setLocal` 의 모달 가드는 base 에서 A 를 뺄 뿐 **B 쓰기를 막지 않으므로** 여기서 막는다
* 5. 재진입 — 미러가 다시 이 헬퍼를 타는 것 방지
* 6. `merge: 'replace'` — `setLocal` 의 replace 는 forced·override 까지 리셋하므로(사례 17)
* 부분 replace 가 **B 전체 손실**로 확대된다. `handleSetState` 의 replace 제외와 동형
* 7. payload 에 `errors` 키 또는 non-plain 객체(File/Blob/Date/Map …) —
* `deepMergeState` 는 `errors` 를 교체하는데 `deepMerge` 는 병합하고,
* File 은 `{...file}` 전개로 손상된다
* 8. `__templateApp` 또는 `setLocal` 부재 — 테스트·프리뷰 폴백 (v1.50.4 정책 동형)
*
* @param context 액션 컨텍스트
* @param updates 상태 갱신 payload (`__mergeMode` / `__setStateId` 메타 포함 가능)
* @param originalSetState 원본 저장소 A writer (프록시에서 클로저로 잡은 원본). 미지정 시 `context.setState`
* @param opts 추가 옵션 — `scope` 는 게이트 3 판정에만 쓰인다
* @return 없음
* @since engine-v1.63.5
*/
private writeLocalState(
context: ActionContext,
updates: any,
originalSetState?: (updates: any) => void,
opts?: { scope?: string }
): void {
const setState = originalSetState || context.setState;
if (!setState) return;
// 게이트 2 — 함수형 업데이터는 payload 를 꺼낼 수 없다
if (typeof updates === 'function') {
logger.warn(
'[writeLocalState] 함수형 업데이터는 저장소 B 미러 대상이 아닙니다 (payload 추출 불가). 저장소 A 만 갱신합니다.'
);
setState(updates);
return;
}
// 게이트 3 — 부모/루트 스코프는 `_local` 정본이 아닌 다른 슬롯을 노린다
if (opts?.scope === 'parent' || opts?.scope === 'root') {
setState(updates);
return;
}
// 게이트 5 — 재진입 차단 (미러가 다시 이 경로를 타는 것 방지)
if (this.localMirrorDepth > 0 || (setState as any)?.__g7CanonicalWriter) {
setState(updates);
return;
}
const raw = (updates && typeof updates === 'object' ? updates : {}) as Record<string, any>;
const mergeMode = raw.__mergeMode as ('replace' | 'shallow' | 'deep' | undefined);
// 게이트 6 — replace 는 forced·override 까지 리셋하므로 부분 replace 가 B 전체 손실이 된다
if (mergeMode === 'replace') {
setState(updates);
return;
}
const { __mergeMode: _mm, __setStateId: _ssid, ...cleanPayload } = raw;
// 게이트 7 — 병합 의미가 다르거나 전개로 손상되는 payload
if ('errors' in cleanPayload || !ActionDispatcher.isMirrorSafePayload(cleanPayload)) {
setState(updates);
return;
}
const w = window as any;
// 게이트 4 — 모달 컨텍스트 스택
if (((w.__g7LayoutContextStack || []) as any[]).length > 0) {
setState(updates);
return;
}
// 게이트 8 — 저장소 B writer 부재 (테스트·프리뷰)
const setLocal = w.G7Core?.state?.setLocal;
if (!w.__templateApp || typeof setLocal !== 'function') {
setState(updates);
return;
}
// dot-notation 을 중첩으로 통일한다 (`handleSetState` COMPONENT path 선례).
// A 쪽은 원본 payload 를 그대로 넘기므로, 양쪽이 같은 leaf 를 가리키게 맞추는 단계다.
const payload = this.deepMergeWithState(cleanPayload, {});
this.localMirrorDepth++;
try {
setLocal(payload, { render: false, merge: mergeMode ?? 'deep' });
// `setLocal` 4단계는 `__g7ActionContext.setState` 로 저장소 A 를 갱신한다.
// 그 writer 가 지금의 원본과 **같은 참조**면 A 는 이미 갱신됐으므로 중복 호출하지 않는다.
// (`!__g7ActionContext` 조건으로 판정하면 컨텍스트가 다른 경우를 놓친다)
if (w.__g7ActionContext?.setState !== setState) {
setState(updates);
}
// `__mergeMode` 를 명시한 호출은 forced 필드를 **얕은 스프레드**로 재보정한다.
// `setLocal` 은 forced 를 깊게 병합하는데(:1932) 저장소 A 경로는 얕은 스프레드라(:1653),
// 사례 19 의 2차 수정(`currentSelection: {}` 리셋)이 깊은 병합에서는 무효화된다.
if (mergeMode) {
w.__g7ForcedLocalFields = { ...(w.__g7ForcedLocalFields || {}), ...payload };
}
} finally {
this.localMirrorDepth--;
}
}
/**
* 저장소 B 미러에 안전한 payload 인지 판정한다.
*
* `setLocal` 의 `deepMerge` 는 객체를 `{...obj}` 로 전개하므로 File/Blob/Date/Map 등
* 자체 내부 슬롯을 가진 값은 전개 시 손상된다. 순수 객체와 배열만 통과시킨다.
*
* @param value 검사 대상
* @param depth 재귀 깊이
* @return 미러해도 안전하면 true
* @since engine-v1.63.5
*/
private static isMirrorSafePayload(value: any, depth = 0): boolean {
if (value === null || typeof value !== 'object') return true;
if (depth >= 8) return true;
if (Array.isArray(value)) {
return value.every((v) => ActionDispatcher.isMirrorSafePayload(v, depth + 1));
}
const proto = Object.getPrototypeOf(value);
if (proto !== Object.prototype && proto !== null) return false;
return Object.values(value).every((v) => ActionDispatcher.isMirrorSafePayload(v, depth + 1));
}
/**
* 커스텀 핸들러에게 넘길 `setState` 미러 프록시를 만든다.
*
* 래퍼를 `handleCustomAction` 한 곳에만 싣는 이유: 컨텍스트 생성 지점(`executeActions`)에서
* 감싸면 그 컨텍스트가 `handleOpenModal` 을 통해 `__g7LayoutContextStack` 으로 새고,
* 그 스택을 읽는 `setLocal({scope:'parent'})` · `handleSetState scope:'parent'` ·
* `handleParentScopeSetState` 가 래퍼를 호출해 **제외하기로 한 부모 스코프 경로가 오염된다.**
* onError 커스텀 핸들러도 `executeAction` 을 거쳐 같은 seam 을 지나므로 누락이 없다.
*
* @param context 액션 컨텍스트
* @return 미러 프록시 (원본 writer 가 없으면 undefined)
* @since engine-v1.63.5
*/
private makeLocalSetStateProxy(context: ActionContext): ((updates: any) => void) | undefined {
const original = context.setState;
if (!original) return undefined;
if ((original as any).__g7CanonicalWriter) return original;
const proxy = (updates: any) => {
this.writeLocalState(context, updates, original);
};
(proxy as any).__g7CanonicalWriter = true;
return proxy;
}
/**
* 커스텀 액션을 처리합니다.
*
@@ -6448,7 +6657,16 @@ export class ActionDispatcher {
throw unknownHandlerError;
}
return await handler(action, context);
// engine-v1.63.5: 커스텀 핸들러에게는 저장소 A/B 를 함께 갱신하는 setState 를 넘긴다.
// 확장의 올바른 API 는 `G7Core.state.setLocal()` 이지만, 실제 확장 핸들러 다수가
// `context.setState` 를 쓰고 있고 그 경로는 저장소 B 를 갱신하지 않아 후속 액션의
// 요청 body 가 비어 나갔다. 래퍼를 이 한 곳(seam)에만 싣는 이유는 헬퍼 주석 참조.
const mirroredSetState = this.makeLocalSetStateProxy(context);
const handlerContext = mirroredSetState && mirroredSetState !== context.setState
? { ...context, setState: mirroredSetState }
: context;
return await handler(action, handlerContext);
}
/**
@@ -5,6 +5,28 @@
>
> 형식: [Keep a Changelog](https://keepachangelog.com/ko/1.1.0/)
## [engine-v1.63.5] - 2026-09-02
### Fixed
#### 커스텀 핸들러가 기록한 값이 요청 body 에 실리지 않던 문제
- 커스텀 핸들러가 받는 `context.setState` 는 **저장소 A**(React `localDynamicState`)만 갱신했다. engine-v1.63.3 이 sequence 후속 액션의 `_local` 을 live B 기준으로 바꾼 뒤로, 저장소 B 에 이미 그 키가 있으면 `addMissingLeafKeys` 보충 대상에서 빠져 **A 의 값이 조용히 유실**된다. 상품상세에서 옵션을 고르면 화면에는 담긴 항목이 그대로 보이는데 `POST …/checkout` body 가 `{"direct_items":[]}` 로 나가 422 가 났고, 「장바구니 담기」는 클라 가드에 걸려 요청조차 나가지 않았다. 예외도 콘솔 에러도 없었다.
- 엔진이 스스로 선언한 이중 저장소 불변조건(`performStateUpdate` 상단 주석)은 "B 가 정본, A 는 쓰는 시점에 강제로 일치시키는 미러" 다. engine-v1.63.3 의 중재 규칙은 그 선언과 일치하므로 **그대로 두고**, 그 규칙을 어기던 쓰기 경로를 규칙에 맞췄다.
- 커스텀 핸들러에게 넘기는 `setState` 를 A/B 양쪽에 쓰는 writer 로 승격한다. 래퍼는 `handleCustomAction` **한 곳**에만 싣는다 — 컨텍스트 생성 지점에서 감싸면 그 컨텍스트가 `handleOpenModal` 을 통해 `__g7LayoutContextStack` 으로 새고, 그 스택을 읽는 부모 스코프 경로 4곳이 오염된다.
- 미러는 `G7Core.state.setLocal({ render:false })` 로 수행해 `__g7PendingLocalState` · `__g7ForcedLocalFields` · `__g7SetLocalOverrideKeys` · **`__g7SequenceLocalSync`** 를 함께 갱신한다. 마지막 것이 핵심이다 — `handleSequence` 는 커스텀 핸들러 뒤에 오직 그 변수로만 `currentState` 를 갱신하는데, `context.setState` 경로는 그 변수를 전혀 건드리지 않아 엔진이 마련한 전파 장치가 사문화돼 있었다.
- 종전 동작을 유지하는 제외 조건: 함수형 업데이터, `scope: 'parent' | 'root'`, 모달 컨텍스트 스택이 있는 경우(사례 29), `merge: 'replace'`(사례 17), payload 에 `errors` 키 또는 `File`·`Blob`·`Date` 같은 non-plain 객체, `__templateApp`/`setLocal` 부재(테스트·프리뷰 폴백).
- `__mergeMode` 를 명시한 호출은 `__g7ForcedLocalFields` 를 **얕은 스프레드**로 재보정한다. `setLocal` 은 깊게 병합하는데 저장소 A 경로는 얕은 스프레드여서, 사례 19 의 2차 수정(`currentSelection: {}` 리셋)이 깊은 병합에서는 무효화된다.
#### 저장소 A 에만 쓰던 나머지 경로 정리
- `resultTo: { target: '_local' }` · isolated 폴백 · `setState` 기본 분기 · `handleSetError` · `callExternal`/`callExternalEmbed` 콜백 · `loadFromLocalStorage` · `FormContext.updateByScope` 가 저장소 B 도 함께 갱신한다.
- `loadingActions`(apiCall 로딩 플래그)와 `$parent`/`$root` 스코프 쓰기는 대상에서 제외한다. 전자는 apiCall 을 발화한 컴포넌트 자신의 일시적 표시 플래그라 페이지 단위 슬롯에 실으면 다른 컴포넌트로 새고 해제가 되지 않으며, 후자는 `_local` 정본이 아닌 다른 슬롯을 노린다.
### Changed
- 이중 저장소 계약을 경로별 **양방향 쌍**(`[이중저장소 A→B]` / `[이중저장소 B→A]`)으로 고정하는 테스트를 추가했다. 한 방향만 시험하면 반대 방향 회귀가 초록으로 통과한다 — 사례 41 은 B→A 축, 사례 42 는 A→B 축으로 각각 그렇게 새어 나갔다.
## [engine-v1.63.4] - 2026-09-01
### Fixed
@@ -343,9 +343,29 @@ export const updateByScope = (
(window as any).G7Core.state.set(update);
}
} else if (context.setState) {
// 로컬 상태 업데이트
// 로컬 상태 업데이트 — 저장소 A(React localDynamicState)와 B(_global._local) 양쪽에 쓴다.
//
// engine-v1.63.5: 엔진의 이중 저장소 불변조건은 "B 가 정본, A 는 쓰는 시점에 강제로
// 일치시키는 미러" 다(DynamicRenderer performStateUpdate 상단 주석). A 에만 쓰면
// 커스텀 핸들러가 읽는 유일한 공개 통로인 G7Core.state.getLocal() 이 stale 값을 보고,
// sequence 후속 액션의 요청 body 가 비어 나간다. 예외도 콘솔 에러도 남지 않는다.
//
// setLocal 은 4단계에서 __g7ActionContext.setState 로 저장소 A 도 갱신하므로,
// 그 writer 가 지금의 context.setState 와 다른 참조일 때만 A 를 추가로 쓴다.
const update = setNestedValue({}, fullPath, value);
context.setState(update);
const w = window as any;
const setLocal = w.G7Core?.state?.setLocal;
const canMirror =
typeof setLocal === 'function' &&
!!w.__templateApp &&
((w.__g7LayoutContextStack || []) as any[]).length === 0;
// 저장소 B 쓰기와 저장소 A 쓰기를 같은 높이에 나란히 둔다 — 한쪽을 분기 안으로 넣으면
// "이 쓰기에 미러가 동반되는가" 를 읽는 쪽(사람도 정적 검사도)이 판정할 수 없다.
if (canMirror) setLocal(update, { render: false });
const mirrorAlreadyWroteA = canMirror && w.__g7ActionContext?.setState === context.setState;
if (!mirrorAlreadyWroteA) context.setState(update);
}
};
@@ -1847,6 +1847,11 @@ function initStateAPI(G7Core: any): void {
if (targetContext?.setState) {
// 함수형 업데이트를 사용하여 항상 최신 상태와 병합
// React setState는 비동기이므로 스냅샷 대신 함수형 업데이트 필수
//
// scope:'parent'|'root' 은 `_local` 정본이 아니라 레이아웃 컨텍스트 스택의
// 부모/루트 슬롯을 대상으로 한다. 여기서 저장소 B 를 함께 쓰면 모달의 쓰기가
// 페이지 _local 을 오염시킨다(사례 29).
// audit:allow local-store-write-must-mirror 부모/루트 슬롯 전용 (위 사유)
targetContext.setState((currentLocal: Record<string, any>) => {
if (mergeMode === 'replace') return converted;
if (mergeMode === 'shallow') return { ...(currentLocal || {}), ...converted };
@@ -0,0 +1,356 @@
/**
* ActionDispatcher.canonicalLocalWrite.test.ts
*
* 커스텀 핸들러가 `context.setState`(저장소 A) 로만 쓰던 경로를 저장소 B(`_global._local`)에도
* 함께 쓰도록 만든 미러 계약을 잠근다 (engine-v1.63.5).
*
* ## 무엇이 깨져 있었나 (브라우저 실측 2026-09-02, `https://g7_2.dev/shop/products/{code}`)
*
* 1) `show.json` 의 `init_actions` 가 B 에 `selectedOptionItems: []` 를 심는다
* 2) 옵션을 고르면 템플릿 커스텀 핸들러가 `context.setState({ selectedOptionItems: [item] })`
* 로 **저장소 A 에만** 쓴다 — 화면에는 담긴 항목이 그대로 보인다
* 3) 이어지는 `apiCall` 의 body 는 sequence 의 `currentState`(= `_local`)를 읽는데,
* engine-v1.63.3 이 그 값을 live B 기준으로 바꾼 뒤로 `addMissingLeafKeys` 는
* **B 에 키가 없을 때만** 보충하므로 `[]` 가 그대로 남는다
* 4) `POST …/checkout` body 가 `{"direct_items":[]}` 로 나가 422
*
* 예외도 콘솔 에러도 없다. 화면과 요청이 서로 다른 값을 보는 것이 유일한 증상이다.
*
* ## 이 파일이 잠그는 것
*
* 게이트 1:1 대응 — 미러가 붙는 조건과 **붙지 않아야 하는 조건**을 모두 고정한다.
* 미러를 무조건 붙이면 사례 17(replace 확대 손실) · 사례 29(모달 → 페이지 오염) ·
* File 손상이 재발하므로, 제외 게이트도 결함 재현 핀과 같은 급으로 잠근다.
*
* 저장소 B 는 **손으로 채우지 않는다** — 실제 `G7Core.state.setLocal` 을 거쳐 심는다.
* 손으로 채우면 "A 에만 쓰는 경로" 자체가 시험에 등장하지 않아 결함을 통과시킨다
* (그것이 engine-v1.63.3 이 이 결함을 놓친 이유다).
*
* @see 트러블슈팅 사례 42
* @see docs/frontend/state-management.md "이중 저장소 구조"
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { ActionDispatcher } from '../ActionDispatcher';
import { initializeG7CoreGlobals } from '../G7CoreGlobals';
import { DataBindingEngine } from '../DataBindingEngine';
import { TranslationEngine } from '../TranslationEngine';
describe('[case:state-setstate-42] 커스텀 핸들러 setState 미러 — 저장소 A 전용 쓰기 (engine-v1.63.5)', () => {
let dispatcher: ActionDispatcher;
let globalState: Record<string, any>;
/** 저장소 A — React localDynamicState 를 모사한다 */
let storeA: Record<string, any>;
/** 저장소 A writer 호출 횟수 (중복 쓰기 판정용) */
let aWrites: number;
/** `globalStateUpdater` 가 받은 payload 이력 */
let updaterCalls: Array<{ updates: any; options?: any }>;
let originalG7Core: any;
/** 저장소 A writer — 함수형 업데이터도 받는다(엔진 `handleLocalSetState` 계약) */
const setStateA = (updates: any): void => {
aWrites++;
const next = typeof updates === 'function' ? updates(storeA) : updates;
const { __mergeMode: _m, __setStateId: _s, ...clean } = next || {};
storeA = { ...storeA, ...clean };
};
/** 저장소 B 의 현재 `_local` */
const liveB = (): Record<string, any> => globalState._local;
/**
* `createHandler` 로 액션 하나를 실행한다.
*
* @param action 액션 정의
* @param dataContext 데이터 컨텍스트 (미지정 시 live B 를 `_local` 로 싣는다)
* @return 없음
*/
const run = async (action: any, dataContext?: any): Promise<void> => {
const handler = dispatcher.createHandler(
action,
dataContext ?? { _local: liveB(), _global: globalState },
{ state: storeA, setState: setStateA }
);
await handler(new Event('click'));
// createHandler 내부의 await 사슬이 풀리도록 한 tick 양보한다
await Promise.resolve();
};
beforeEach(() => {
globalState = { _local: {} };
storeA = {};
aWrites = 0;
updaterCalls = [];
originalG7Core = (window as any).G7Core;
delete (window as any).G7Core;
(window as any).__templateApp = {
getGlobalState: () => globalState,
// TemplateApp 계약: 최상위 키 **얕은** 병합
setGlobalState: (updates: any) => {
globalState = { ...globalState, ...updates };
},
};
(window as any).__g7PendingLocalState = null;
(window as any).__g7ForcedLocalFields = undefined;
(window as any).__g7SetLocalOverrideKeys = undefined;
(window as any).__g7SequenceLocalSync = undefined;
(window as any).__g7LayoutContextStack = [];
delete (window as any).__g7ActionContext;
delete (window as any).__g7AutoBindingPaths;
initializeG7CoreGlobals({
getState: vi.fn(() => ({
translationEngine: new TranslationEngine(),
translationContext: { templateId: 't', locale: 'ko' },
bindingEngine: new DataBindingEngine(),
templateMetadata: { locales: ['ko'] },
})) as any,
transitionManager: { getIsPending: vi.fn(() => false), subscribe: vi.fn(() => () => {}) },
responsiveManager: {},
webSocketManager: {
subscribe: vi.fn(() => 's'),
unsubscribe: vi.fn(),
leaveChannel: vi.fn(),
disconnect: vi.fn(),
isInitialized: vi.fn(() => true),
getSubscriptionCount: vi.fn(() => 0),
},
} as any);
dispatcher = new ActionDispatcher({ navigate: vi.fn() });
dispatcher.setGlobalStateUpdater((updates: any, options?: any) => {
updaterCalls.push({ updates, options });
(window as any).__templateApp.setGlobalState(updates);
});
});
afterEach(() => {
vi.restoreAllMocks();
delete (window as any).__templateApp;
delete (window as any).__g7PendingLocalState;
delete (window as any).__g7ForcedLocalFields;
delete (window as any).__g7SetLocalOverrideKeys;
delete (window as any).__g7SequenceLocalSync;
(window as any).__g7LayoutContextStack = [];
delete (window as any).__g7ActionContext;
if (originalG7Core === undefined) delete (window as any).G7Core;
else (window as any).G7Core = originalG7Core;
});
/**
* `init_actions` 가 B 에 기본값을 심은 상태를 **실제 쓰기 경로**로 만든다.
*
* @param seed 심을 값
* @return 없음
*/
const seedB = (seed: Record<string, any>): void => {
(window as any).G7Core.state.setLocal(seed, { render: false });
// 렌더 컨텍스트(저장소 A)도 같은 기본값을 갖는 상태가 실제 화면이다 —
// 그래야 결함이 "undefined" 가 아니라 브라우저 실측과 같은 "[] 가 그대로 나감" 으로 드러난다.
storeA = { ...storeA, ...JSON.parse(JSON.stringify(seed)) };
(window as any).__g7PendingLocalState = null;
(window as any).__g7SequenceLocalSync = undefined;
(window as any).__g7ForcedLocalFields = undefined;
(window as any).__g7SetLocalOverrideKeys = undefined;
};
const ITEM = { id: '화이트', optionId: 11, quantity: 1, unitPrice: 19000 };
it('T1 — 핸들러 쓰기 후 후속 액션이 보는 _local 에 실제 값이 담긴다 (주 회귀 핀)', async () => {
seedB({ selectedOptionItems: [], currentSelection: {} });
let seenByNext: any;
dispatcher.registerHandler('addItem', (_a: any, ctx: any) => {
ctx.setState({
selectedOptionItems: [ITEM],
currentSelection: {},
__mergeMode: 'shallow',
});
});
dispatcher.registerHandler('recordLocal', (_a: any, ctx: any) => {
seenByNext = ctx.data?._local;
});
await run({
handler: 'sequence',
params: { actions: [{ handler: 'addItem' }, { handler: 'recordLocal' }] },
});
expect(
seenByNext?.selectedOptionItems,
'후속 액션(= 요청 body 가 읽는 자리)이 빈 배열을 보면 안 된다'
).toEqual([ITEM]);
});
it('T2 — globalStateUpdater 가 받은 마지막 _local 에 값이 도달한다', async () => {
seedB({ selectedOptionItems: [] });
dispatcher.registerHandler('addItem', (_a: any, ctx: any) => {
ctx.setState({ selectedOptionItems: [ITEM], __mergeMode: 'shallow' });
});
await run({ handler: 'addItem' });
expect(liveB().selectedOptionItems).toEqual([ITEM]);
});
it('T3 — __g7SequenceLocalSync 가 갱신되어 sequence 전파 장치가 살아난다', async () => {
seedB({ selectedOptionItems: [] });
dispatcher.registerHandler('addItem', (_a: any, ctx: any) => {
ctx.setState({ selectedOptionItems: [ITEM], __mergeMode: 'shallow' });
});
await run({ handler: 'addItem' });
expect((window as any).__g7SequenceLocalSync?.selectedOptionItems).toEqual([ITEM]);
});
it('T4 — __g7ActionContext.setState 와 참조가 같으면 저장소 A 를 한 번만 쓴다', async () => {
seedB({ n: 0 });
dispatcher.registerHandler('bump', (_a: any, ctx: any) => {
aWrites = 0;
ctx.setState({ n: 1 });
});
await run({ handler: 'bump' });
expect(aWrites, '중복 A 쓰기가 있으면 안 된다').toBe(1);
expect(storeA.n).toBe(1);
expect(liveB().n).toBe(1);
});
it('T5 — __g7ActionContext 가 없으면 원본 writer 와 setLocal 이 각각 한 번씩 동작한다', () => {
seedB({ n: 0 });
const ctx: any = { state: storeA, setState: setStateA, data: { _local: liveB() } };
aWrites = 0;
(dispatcher as any).writeLocalState(ctx, { n: 7 });
expect(aWrites).toBe(1);
expect(liveB().n).toBe(7);
});
it('T6 — 미러 writer 로 재진입해도 무한 재귀가 없다', () => {
seedB({ n: 0 });
const ctx: any = { state: storeA, setState: setStateA };
const proxy = (dispatcher as any).makeLocalSetStateProxy(ctx);
const ctx2: any = { state: storeA, setState: proxy };
expect(() => (dispatcher as any).writeLocalState(ctx2, { n: 1 })).not.toThrow();
expect(storeA.n).toBe(1);
});
it('T7 — 모달 컨텍스트 스택이 있으면 미러하지 않는다 (사례 29)', () => {
seedB({ pageKey: 'page' });
(window as any).__g7LayoutContextStack = [{ state: {}, setState: () => {} }];
const ctx: any = { state: storeA, setState: setStateA };
(dispatcher as any).writeLocalState(ctx, { pageKey: 'modal' });
expect(liveB().pageKey, '모달의 쓰기가 페이지 저장소를 덮으면 안 된다').toBe('page');
expect(storeA.pageKey).toBe('modal');
});
it('T8 — merge:"replace" 는 미러하지 않는다 (사례 17)', () => {
seedB({ a: 1, b: 2 });
const ctx: any = { state: storeA, setState: setStateA };
(dispatcher as any).writeLocalState(ctx, { a: 9, __mergeMode: 'replace' });
expect(liveB(), '부분 replace 가 B 전체 손실로 확대되면 안 된다').toEqual({ a: 1, b: 2 });
expect(storeA.a).toBe(9);
});
it('T9 — dot-notation 키는 양쪽 모두 중첩으로 기록되고 리터럴 키가 남지 않는다', () => {
seedB({ form: { general: { asset_url_mode: 'extension' } } });
const ctx: any = { state: storeA, setState: setStateA };
(dispatcher as any).writeLocalState(ctx, { 'form.general.asset_url_mode': 'extensionless' });
expect(liveB().form.general.asset_url_mode).toBe('extensionless');
expect(Object.keys(liveB())).not.toContain('form.general.asset_url_mode');
});
it('T10 — 배열을 비우는 쓰기가 양쪽 모두 빈 배열이 된다', () => {
seedB({ selectedOptionItems: [ITEM] });
const ctx: any = { state: storeA, setState: setStateA };
(dispatcher as any).writeLocalState(ctx, { selectedOptionItems: [], __mergeMode: 'shallow' });
expect(liveB().selectedOptionItems).toEqual([]);
});
it('T11 — __mergeMode 명시 시 forcedFields 가 얕게 재보정된다 (사례 19 2차)', () => {
seedB({ currentSelection: { 색상: '화이트' } });
(window as any).__g7ForcedLocalFields = { currentSelection: { 색상: '화이트' } };
const ctx: any = { state: storeA, setState: setStateA };
(dispatcher as any).writeLocalState(ctx, { currentSelection: {}, __mergeMode: 'shallow' });
expect(
(window as any).__g7ForcedLocalFields.currentSelection,
'깊은 병합이면 리셋이 무효화된다'
).toEqual({});
});
it('T12 — payload 에 errors 키가 있으면 미러하지 않는다', () => {
seedB({ errors: { title: ['필수'] } });
const ctx: any = { state: storeA, setState: setStateA };
(dispatcher as any).writeLocalState(ctx, { errors: {} });
expect(liveB().errors, 'errors 는 병합 의미가 달라 미러 대상이 아니다').toEqual({ title: ['필수'] });
expect(storeA.errors).toEqual({});
});
it('T13 — payload 에 File 등 non-plain 객체가 있으면 미러하지 않는다', () => {
seedB({ upload: null });
const ctx: any = { state: storeA, setState: setStateA };
const file = new File(['x'], 'a.txt', { type: 'text/plain' });
(dispatcher as any).writeLocalState(ctx, { upload: file });
expect(liveB().upload, '전개로 손상되는 값은 B 에 싣지 않는다').toBeNull();
expect(storeA.upload).toBe(file);
});
it('T14 — 함수형 업데이터는 원본 writer 로 폴백한다', () => {
seedB({ n: 1 });
const ctx: any = { state: storeA, setState: setStateA };
(dispatcher as any).writeLocalState(ctx, (prev: any) => ({ n: (prev.n ?? 0) + 1 }));
expect(storeA.n).toBe(2);
expect(liveB().n, '함수형은 payload 를 꺼낼 수 없어 미러하지 않는다').toBe(1);
});
it('T15 — 커스텀 핸들러는 미러 프록시를 받고, 그 프록시가 부모 스코프 스택으로 새지 않는다', async () => {
seedB({ n: 0 });
let sawProxy = false;
dispatcher.registerHandler('inspect', (_a: any, ctx: any) => {
sawProxy = ctx.setState?.__g7CanonicalWriter === true;
});
await run({ handler: 'inspect' });
expect(sawProxy, '커스텀 핸들러는 A/B 를 함께 쓰는 writer 를 받아야 한다').toBe(true);
const stack = (window as any).__g7LayoutContextStack || [];
for (const entry of stack) {
expect(
(entry?.setState as any)?.__g7CanonicalWriter,
'부모 스코프 경로가 미러 프록시를 잡으면 안 된다'
).toBeUndefined();
}
});
it('T16 — scope:"parent" 로 넘긴 쓰기는 미러하지 않는다', () => {
seedB({ pageKey: 'page' });
const ctx: any = { state: storeA, setState: setStateA };
(dispatcher as any).writeLocalState(ctx, { pageKey: 'x' }, undefined, { scope: 'parent' });
expect(liveB().pageKey).toBe('page');
expect(storeA.pageKey).toBe('x');
});
});
@@ -0,0 +1,502 @@
/**
* dual-store-mirror-contract.test.tsx
*
* 이중 저장소(A = React `localDynamicState`, B = `globalState._local`)의 **양방향** 계약을
* 경로별로 잠근다 (engine-v1.63.5).
*
* ## 왜 양방향이어야 하는가
*
* 엔진이 스스로 선언한 불변조건(DynamicRenderer `performStateUpdate` 상단 주석)은 두 문장이다:
*
* - 자동바인딩 쓰기는 **A + B 양쪽에 동시에 쓴다**
* - **B 가 정본**이고 A 는 "쓰는 시점에 강제로 일치시키는 미러" 다
*
* 한 방향만 시험하면 반대 방향의 회귀가 초록으로 통과한다. 실제로 그렇게 두 번 새어 나갔다:
*
* - 사례 41 (engine-v1.63.4) — B→A 축. 자동바인딩 키입력이 B 의 편집분을 서버 원본으로 되돌렸다
* - 사례 42 (engine-v1.63.5) — A→B 축. 커스텀 핸들러 쓰기가 B 에 닿지 않아 요청 body 가 비었다
*
* ## 규약
*
* 경로마다 `[이중저장소 A→B] <경로키>` 와 `[이중저장소 B→A] <경로키>` 를 **짝으로** 둔다.
* 짝이 빠지면 정적 검사가 위반으로 잡는다 — 자기검증 `it` 방식은 그 `it` 을 지우면 무력해서
* "규정만 있는 상태" 와 실질이 같아지기 때문이다.
*
* 저장소 B 는 **손으로 채우지 않는다.** 실제 writer(`G7Core.state.setLocal` ·
* `setParentLocal` · `ActionDispatcher` · 자동바인딩)를 거친다. 손으로 채운 하네스는
* 발산 상황을 위조할 뿐이라 "A 에만 쓰는 경로" 자체가 시험에 등장하지 않는다.
*
* @see 트러블슈팅 사례 41 · 42
* @see docs/frontend/state-management.md "이중 저장소 구조"
*/
import React from 'react';
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { render, cleanup, fireEvent, screen } from '@testing-library/react';
import DynamicRenderer, { ComponentDefinition } from '../DynamicRenderer';
import { ComponentRegistry } from '../ComponentRegistry';
import { DataBindingEngine } from '../DataBindingEngine';
import { TranslationEngine, TranslationContext } from '../TranslationEngine';
import { ActionDispatcher } from '../ActionDispatcher';
import { initializeG7CoreGlobals } from '../G7CoreGlobals';
vi.mock('../ResponsiveManager', async (importOriginal) => {
const actual = await importOriginal<typeof import('../ResponsiveManager')>();
return {
...actual,
responsiveManager: {
getWidth: vi.fn(() => 1440),
subscribe: vi.fn(() => () => {}),
getMatchingKey: vi.fn(() => null),
parseRange: vi.fn(() => null),
},
};
});
/** 자동바인딩 대상 — name/value/onChange 를 그대로 DOM 에 넘긴다 */
const TestInput: React.FC<any> = ({ name, value, onChange }) => (
<input data-testid={`input-${name}`} name={name} value={value ?? ''} onChange={onChange} />
);
let globalState: Record<string, any>;
let storeA: Record<string, any>;
let dispatcher: ActionDispatcher;
let registry: ComponentRegistry;
let bindingEngine: DataBindingEngine;
let translationEngine: TranslationEngine;
let translationContext: TranslationContext;
let originalG7Core: any;
/** 저장소 B 의 현재 `_local` */
const liveB = (): Record<string, any> => globalState._local;
/** 저장소 A writer — 함수형 업데이터도 받는다 */
const setStateA = (updates: any): void => {
const next = typeof updates === 'function' ? updates(storeA) : updates;
const { __mergeMode: _m, __setStateId: _s, ...clean } = next || {};
storeA = { ...storeA, ...clean };
};
/**
* `init_actions` 가 심은 초기 상태를 **실제 쓰기 경로**로 만든다.
*
* @param seed 심을 값
* @return 없음
*/
const seed = (seedValue: Record<string, any>): void => {
(window as any).G7Core.state.setLocal(seedValue, { render: false });
storeA = { ...storeA, ...JSON.parse(JSON.stringify(seedValue)) };
(window as any).__g7PendingLocalState = null;
(window as any).__g7SequenceLocalSync = undefined;
(window as any).__g7ForcedLocalFields = undefined;
(window as any).__g7SetLocalOverrideKeys = undefined;
};
/**
* `createHandler` 로 액션 하나를 실행한다.
*
* @param action 액션 정의
* @return 없음
*/
const run = async (action: any): Promise<void> => {
const handler = dispatcher.createHandler(
action,
{ _local: liveB(), _global: globalState },
{ state: storeA, setState: setStateA }
);
await handler(new Event('click'));
await Promise.resolve();
};
beforeEach(() => {
globalState = { _local: {} };
storeA = {};
originalG7Core = (window as any).G7Core;
delete (window as any).G7Core;
registry = ComponentRegistry.getInstance();
(registry as any).registry = {
Input: { component: TestInput, metadata: { name: 'Input', type: 'basic' } },
};
bindingEngine = new DataBindingEngine();
translationEngine = new TranslationEngine();
translationContext = { templateId: 'test-template', locale: 'ko' };
(window as any).__templateApp = {
getGlobalState: () => globalState,
setGlobalState: (updates: any) => {
globalState = { ...globalState, ...updates };
},
};
(window as any).__g7PendingLocalState = null;
(window as any).__g7ForcedLocalFields = undefined;
(window as any).__g7SetLocalOverrideKeys = undefined;
(window as any).__g7SequenceLocalSync = undefined;
(window as any).__g7LayoutContextStack = [];
delete (window as any).__g7ActionContext;
delete (window as any).__g7AutoBindingPaths;
initializeG7CoreGlobals({
getState: vi.fn(() => ({
translationEngine,
translationContext,
bindingEngine,
templateMetadata: { locales: ['ko'] },
})) as any,
transitionManager: { getIsPending: vi.fn(() => false), subscribe: vi.fn(() => () => {}) },
responsiveManager: {},
webSocketManager: {
subscribe: vi.fn(() => 's'),
unsubscribe: vi.fn(),
leaveChannel: vi.fn(),
disconnect: vi.fn(),
isInitialized: vi.fn(() => true),
getSubscriptionCount: vi.fn(() => 0),
},
} as any);
dispatcher = new ActionDispatcher({ navigate: vi.fn() });
dispatcher.setGlobalStateUpdater((updates: any) => {
(window as any).__templateApp.setGlobalState(updates);
});
});
afterEach(() => {
cleanup();
vi.restoreAllMocks();
delete (window as any).__templateApp;
delete (window as any).__g7PendingLocalState;
delete (window as any).__g7ForcedLocalFields;
delete (window as any).__g7SetLocalOverrideKeys;
delete (window as any).__g7SequenceLocalSync;
(window as any).__g7LayoutContextStack = [];
delete (window as any).__g7ActionContext;
if (originalG7Core === undefined) delete (window as any).G7Core;
else (window as any).G7Core = originalG7Core;
});
// ─────────────────────────────────────────────────────────────────────────────
// 경로키: setState target:"_local"
// ─────────────────────────────────────────────────────────────────────────────
describe('[이중저장소 A→B] setState target:"_local"', () => {
it('레이아웃 setState 가 저장소 B 에 도달한다', async () => {
seed({ filter: 'all' });
await run({ handler: 'setState', params: { target: '_local', filter: 'mine' } });
expect(liveB().filter).toBe('mine');
});
});
describe('[이중저장소 B→A] setState target:"_local"', () => {
it('B 에만 있던 키를 저장소 A 스냅샷이 되돌리지 않는다', async () => {
seed({ filter: 'all' });
// 저장소 B 에만 존재하는 값 (selfManaged 플러그인이 쓴 편집기 본문을 모사)
(window as any).G7Core.state.setLocal(
{ editorBody: '<p>편집분</p>' },
{ render: false, selfManaged: true }
);
(window as any).__g7PendingLocalState = null;
await run({ handler: 'setState', params: { target: '_local', filter: 'mine' } });
expect(liveB().editorBody, 'A 가 아직 모르는 키가 사라지면 안 된다').toBe('<p>편집분</p>');
expect(liveB().filter).toBe('mine');
});
});
// ─────────────────────────────────────────────────────────────────────────────
// 경로키: setState target:"_local.dot"
// ─────────────────────────────────────────────────────────────────────────────
describe('[이중저장소 A→B] setState target:"_local.dot"', () => {
it('dot 경로 setState 가 저장소 B 의 중첩 leaf 에 도달한다', async () => {
seed({ form: { general: { asset_url_mode: 'extension', site_name: 'G7' } } });
await run({
handler: 'setState',
params: { target: '_local.form.general.asset_url_mode', value: 'extensionless' },
});
expect(liveB().form.general.asset_url_mode).toBe('extensionless');
expect(liveB().form.general.site_name, '형제 키를 잃으면 안 된다').toBe('G7');
});
});
describe('[이중저장소 B→A] setState target:"_local.dot"', () => {
it('dot 경로 쓰기가 B 의 다른 최상위 키를 통째로 교체하지 않는다', async () => {
seed({ form: { general: { asset_url_mode: 'extension' } } });
(window as any).G7Core.state.setLocal(
{ editorBody: '<p>편집분</p>' },
{ render: false, selfManaged: true }
);
(window as any).__g7PendingLocalState = null;
await run({
handler: 'setState',
params: { target: '_local.form.general.asset_url_mode', value: 'extensionless' },
});
expect(liveB().editorBody).toBe('<p>편집분</p>');
});
});
// ─────────────────────────────────────────────────────────────────────────────
// 경로키: setState 기본 분기 (target 미지정)
// ─────────────────────────────────────────────────────────────────────────────
describe('[이중저장소 A→B] setState 기본 분기', () => {
it('target 을 지정하지 않은 setState 도 저장소 B 에 도달한다', async () => {
seed({ tab: 'a' });
// target 미지정은 기본값 'component' 로 해석되어 COMPONENT 분기를 탄다
await run({ handler: 'setState', params: { tab: 'b' } });
expect(liveB().tab).toBe('b');
});
});
describe('[이중저장소 B→A] setState 기본 분기', () => {
it('B 전용 키가 기본 분기 쓰기로 사라지지 않는다', async () => {
seed({ tab: 'a' });
(window as any).G7Core.state.setLocal(
{ editorBody: '<p>편집분</p>' },
{ render: false, selfManaged: true }
);
(window as any).__g7PendingLocalState = null;
await run({ handler: 'setState', params: { tab: 'b' } });
expect(liveB().editorBody).toBe('<p>편집분</p>');
});
});
// ─────────────────────────────────────────────────────────────────────────────
// 경로키: 커스텀 핸들러 context.setState
// ─────────────────────────────────────────────────────────────────────────────
describe('[이중저장소 A→B] 커스텀 핸들러 context.setState', () => {
it('핸들러가 저장소 A writer 로 쓴 값이 저장소 B 에 도달한다', async () => {
seed({ selectedOptionItems: [] });
dispatcher.registerHandler('addItem', (_a: any, ctx: any) => {
ctx.setState({ selectedOptionItems: [{ id: '화이트' }], __mergeMode: 'shallow' });
});
await run({ handler: 'addItem' });
expect(liveB().selectedOptionItems).toEqual([{ id: '화이트' }]);
});
});
describe('[이중저장소 B→A] 커스텀 핸들러 context.setState', () => {
it('핸들러 쓰기가 B 전용 키를 지우지 않는다', async () => {
seed({ selectedOptionItems: [] });
(window as any).G7Core.state.setLocal(
{ editorBody: '<p>편집분</p>' },
{ render: false, selfManaged: true }
);
(window as any).__g7PendingLocalState = null;
dispatcher.registerHandler('addItem', (_a: any, ctx: any) => {
ctx.setState({ selectedOptionItems: [{ id: '화이트' }], __mergeMode: 'shallow' });
});
await run({ handler: 'addItem' });
expect(liveB().editorBody).toBe('<p>편집분</p>');
expect(liveB().selectedOptionItems).toEqual([{ id: '화이트' }]);
});
});
// ─────────────────────────────────────────────────────────────────────────────
// 경로키: resultTo _local
// ─────────────────────────────────────────────────────────────────────────────
describe('[이중저장소 A→B] resultTo _local', () => {
it('핸들러 결과를 _local 에 저장하면 저장소 B 에도 도달한다', async () => {
seed({ probe: null });
dispatcher.registerHandler('produce', () => 'RESULT');
await run({ handler: 'produce', resultTo: { target: '_local', key: 'probe' } });
expect(liveB().probe).toBe('RESULT');
});
});
describe('[이중저장소 B→A] resultTo _local', () => {
it('resultTo 쓰기가 B 전용 키를 지우지 않는다', async () => {
seed({ probe: null });
(window as any).G7Core.state.setLocal(
{ editorBody: '<p>편집분</p>' },
{ render: false, selfManaged: true }
);
(window as any).__g7PendingLocalState = null;
dispatcher.registerHandler('produce', () => 'RESULT');
await run({ handler: 'produce', resultTo: { target: '_local', key: 'probe' } });
expect(liveB().editorBody).toBe('<p>편집분</p>');
expect(liveB().probe).toBe('RESULT');
});
});
// ─────────────────────────────────────────────────────────────────────────────
// 경로키: setLocal render:false selfManaged
// ─────────────────────────────────────────────────────────────────────────────
describe('[이중저장소 A→B] setLocal render:false selfManaged', () => {
it('selfManaged 쓰기는 저장소 B 에 즉시 반영된다', () => {
seed({ form: { content: '' } });
(window as any).G7Core.state.setLocal(
{ form: { content: '<p>편집분</p>' } },
{ render: false, selfManaged: true }
);
expect(liveB().form.content).toBe('<p>편집분</p>');
});
});
describe('[이중저장소 B→A] setLocal render:false selfManaged', () => {
it('selfManaged 로 B 에만 쓴 값이 자동바인딩 키입력에 되돌려지지 않는다 (사례 41)', () => {
const BODY = '<p>ZZEDIT본문</p>';
const SERVER = '<p>본문</p>';
globalState._local = { form: { title: '제목', content: BODY } };
(window as any).__g7ForcedLocalFields = { form: { content: BODY } };
(window as any).__g7SetLocalOverrideKeys = { form: { content: BODY } };
(window as any).__g7PendingLocalState = null;
// 저장소 A 는 편집 이전 스냅샷으로 고정돼 있다 (memo 미재계산)
const staleA = { form: { title: '제목', content: SERVER } };
render(
<DynamicRenderer
componentDef={
{ id: 'title-input', type: 'basic', name: 'Input', props: { name: 'title' } } as ComponentDefinition
}
dataContext={{ _local: staleA }}
translationContext={translationContext}
registry={registry}
bindingEngine={bindingEngine}
translationEngine={translationEngine}
actionDispatcher={dispatcher}
parentFormContextProp={
{ dataKey: 'form', state: staleA, setState: () => {}, trackChanges: true } as any
}
/>
);
fireEvent.change(screen.getByTestId('input-title'), { target: { value: '제목X' } });
expect(liveB().form.content, '편집분이 서버 원본으로 되돌아가면 안 된다').toBe(BODY);
expect(liveB().form.title).toBe('제목X');
});
});
// ─────────────────────────────────────────────────────────────────────────────
// 경로키: 자동바인딩
// ─────────────────────────────────────────────────────────────────────────────
describe('[이중저장소 A→B] 자동바인딩', () => {
it('입력값이 저장소 B 에 도달한다', () => {
globalState._local = { form: { title: '제목' } };
(window as any).__g7PendingLocalState = null;
const stateA = { form: { title: '제목' } };
render(
<DynamicRenderer
componentDef={
{ id: 'title-input', type: 'basic', name: 'Input', props: { name: 'title' } } as ComponentDefinition
}
dataContext={{ _local: stateA }}
translationContext={translationContext}
registry={registry}
bindingEngine={bindingEngine}
translationEngine={translationEngine}
actionDispatcher={dispatcher}
parentFormContextProp={
{ dataKey: 'form', state: stateA, setState: () => {}, trackChanges: true } as any
}
/>
);
fireEvent.change(screen.getByTestId('input-title'), { target: { value: '새 제목' } });
expect(liveB().form.title).toBe('새 제목');
});
});
describe('[이중저장소 B→A] 자동바인딩', () => {
it('자동바인딩 쓰기가 저장소 A writer 에도 같은 값을 전달한다', () => {
globalState._local = { form: { title: '제목' } };
(window as any).__g7PendingLocalState = null;
const stateA = { form: { title: '제목' } };
const aCalls: any[] = [];
render(
<DynamicRenderer
componentDef={
{ id: 'title-input', type: 'basic', name: 'Input', props: { name: 'title' } } as ComponentDefinition
}
dataContext={{ _local: stateA }}
translationContext={translationContext}
registry={registry}
bindingEngine={bindingEngine}
translationEngine={translationEngine}
actionDispatcher={dispatcher}
parentFormContextProp={
{ dataKey: 'form', state: stateA, setState: (u: any) => aCalls.push(u), trackChanges: true } as any
}
/>
);
fireEvent.change(screen.getByTestId('input-title'), { target: { value: '새 제목' } });
expect(aCalls.length, '저장소 A 도 함께 갱신돼야 한다').toBeGreaterThan(0);
const last = aCalls[aCalls.length - 1];
expect(last?.form?.title).toBe('새 제목');
});
});
// ─────────────────────────────────────────────────────────────────────────────
// 경로키: setParentLocal
// ─────────────────────────────────────────────────────────────────────────────
describe('[이중저장소 A→B] setParentLocal', () => {
it('부모 스코프 쓰기가 저장소 B 에 도달한다', () => {
seed({ parentKey: 'before' });
const parentA = { _local: { parentKey: 'before' } };
(window as any).__g7LayoutContextStack = [
{ state: parentA, setState: (u: any) => Object.assign(parentA._local, u) },
];
(window as any).G7Core.state.setParentLocal({ parentKey: 'after' });
expect(liveB().parentKey).toBe('after');
});
});
describe('[이중저장소 B→A] setParentLocal', () => {
it('부모 스코프 쓰기가 B 전용 키를 통째 교체로 지우지 않는다 (공개 이슈 #130 계열)', () => {
seed({ parentKey: 'before' });
(window as any).G7Core.state.setLocal(
{ editorBody: '<p>편집분</p>' },
{ render: false, selfManaged: true }
);
(window as any).__g7PendingLocalState = null;
// 부모의 저장소 A 는 editorBody 를 모른다
const parentA = { _local: { parentKey: 'before' } };
(window as any).__g7LayoutContextStack = [
{ state: parentA, setState: (u: any) => Object.assign(parentA._local, u) },
];
(window as any).G7Core.state.setParentLocal({ parentKey: 'after' });
expect(liveB().editorBody, 'A 스냅샷 통째 교체로 B 전용 키가 사라지면 안 된다').toBe(
'<p>편집분</p>'
);
expect(liveB().parentKey).toBe('after');
});
});