diff --git a/AGENTS.md b/AGENTS.md index 9d79d205..9e9e4b5f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -764,9 +764,13 @@ Controller → Request → Service → RepositoryInterface → Repository → Mo 필수: 마이그레이션 한국어 comment 필수, down() 구현 필수 필수: FK 컬럼의 ->comment() 는 ->constrained()/->references()/->on() 앞에 둔다 (뒤에 두면 comment 가 컬럼이 아닌 FK 정의에 부착되어 조용히 사라진다) 필수: 소스 교정만으로는 기설치본이 낫지 않는다 — 마이그레이션은 재실행되지 않으므로 업그레이드 스텝 백필을 함께 작성 +필수: 필터가 걸린 쿼리를 순회하며 그 행을 update/delete 하면 chunkById() (키셋 순회) +절대 금지: 그 경우 chunk()/each()/lazy() 사용 — OFFSET 기반이라 처리된 행이 결과에서 이탈한 만큼 커서가 밀려 미처리 행을 조용히 건너뛴다 (250건/청크 100 → 100건 누락, 예외·로그 없음) 주의: ResponseHelper::success($messageKey, $data) — 메시지가 첫 번째 인수 ``` +갱신값이 항상 필터 소속을 유지해 안전한 경우(예: `whereNotNull` + 갱신값이 항상 non-null)만 예외이며, 그 근거를 코드 주석에 남긴다. 정적 검사가 이 패턴을 검출한다. + > 상세 규칙 (API 리소스, ServiceProvider, validation, 인증, 활동 로그 등): [docs/backend/](docs/backend/) 각 문서 참조 ### 컨트롤러 계층 diff --git a/CHANGELOG.md b/CHANGELOG.md index d35503a3..ac8ac557 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -55,6 +55,21 @@ ### Fixed +#### 확장 업데이트 + +- 모듈·플러그인 업데이트에서 '수정 유지'를 선택해도 직접 고친 화면이 새 버전으로 덮어써지던 문제를 수정했습니다. 업데이트 과정이 보존 여부를 판단하기 전에 모든 화면을 파일 기준으로 먼저 되돌려, 비교할 수정본이 남지 않아 '수정 유지'가 항상 무효가 됐습니다. 이제 선택한 대로 수정한 화면이 그대로 유지됩니다. +- 업데이트 전 표시되는 "수정된 레이아웃" 안내가 확인에 실패했을 때도 "수정된 레이아웃이 없습니다"라고 단언하던 문제를 수정했습니다. 네트워크가 끊긴 상태에서 그대로 '모두 교체'를 진행하면 직접 고친 화면이 사라질 수 있었습니다. 이제 확인하지 못했다는 사실과 함께 '수정 유지' 권장 안내가 표시됩니다. +- 템플릿 업데이트 안내가 그 템플릿에 등록된 모듈·플러그인 화면의 수정까지 자기 것으로 세던 문제를 수정했습니다. 실제로 교체·보존되는 대상은 템플릿 자신의 화면뿐이라 표시 건수와 실제 동작이 어긋났습니다. +- '업데이트 확인' 버튼을 눌러 업데이트가 발견돼도 항상 "모두 최신 상태입니다"라고 안내되던 문제를 수정했습니다. 모듈·플러그인·템플릿 관리 화면 모두에 해당합니다. +- 업데이트 완료 안내에 확장 이름과 버전이 표시되지 않고 자리표시자 글자가 그대로 노출되던 문제를 수정했습니다. +- 모듈·플러그인·템플릿 관리 화면의 목록 요약이 항상 "총 0개 중 1-0개 표시"로 나오고, 목록이 한 화면을 넘어도 다음 쪽으로 넘어갈 수 없던 문제를 수정했습니다. +- 존재하지 않는 확장 이름으로 수정 화면 확인을 요청하면 "수정된 화면 없음"으로 응답하던 것을 "찾을 수 없음"으로 구분해 응답하도록 바꿨습니다. + +#### 관리자 화면 + +- 템플릿 레이아웃 편집 화면의 파일 목록에서 이름·설명이 빈칸으로 보이던 문제를 수정했습니다. 번역 제외 표기를 쓴 글자가 화면 구성 요소의 본문 자리에서만 해석되지 않아 아무것도 출력되지 않았습니다. +- 번역 제외 표기를 쓴 글자가 검색엔진 봇 화면에서 해석되지 않던 문제를 함께 수정했습니다. 일반 화면에는 값이 나오는데 봇 화면에서만 비어 보일 수 있었습니다. + #### 검색엔진 봇 화면 - 검색엔진 봇에게만 게시글·답글의 원글·댓글·페이지·상품 설명의 본문이 통째로 빈 채 전달되던 문제를 수정했습니다. 위지윅 편집기 플러그인이 켜져 있으면 본문 영역이 플러그인 화면으로 교체되는데, 봇용 화면을 만드는 쪽이 그 교체 규칙을 몰라 내용 없는 껍데기만 만들었습니다. 미리보기용 요약(메타 태그)에는 본문이 들어가 있어 겉으로는 정상으로 보였습니다. 이제 일반 화면과 봇용 화면이 같은 본문을 출력합니다. 업그레이드 시 이미 만들어져 있던 봇용 화면은 한 번 비워져 새로 만들어집니다. (#86 @koojunho 님께서 제보해주셨습니다.) @@ -80,6 +95,7 @@ - 데이터베이스 계정 설정이 잘못되었을 때 아무 설명 없이 빈 화면만 뜨던 문제를 수정했습니다. 이전에는 최고 권한 계정을 쓰거나 사용자명이 비어 있으면 사이트 기능이 통째로 동작을 멈추면서도 화면에는 아무 안내가 없어 원인을 알 수 없었습니다. 이제 무엇이 잘못되었고 어떻게 고쳐야 하는지 설명하는 전용 안내 화면이 나타납니다. 서버 관리 명령은 평소대로 실행되므로 이 상태에서도 설정을 고칠 수 있습니다. - 모듈·플러그인의 연동 기능이 실행된 뒤로 같은 요청의 나머지 처리가 요청 정보를 잃어버리던 문제를 수정했습니다. 백그라운드 작업을 별도 프로세스로 돌리지 않는 설정에서 이 현상이 나타나, 뒤이어 실행되는 연동 기능이 필요한 정보를 찾지 못하고 조용히 건너뛰었습니다. 대표적으로 비회원 장바구니에 담아 두고 로그인하면 담은 상품이 사라졌습니다. - 모듈·플러그인 업데이트가 실패하거나 도중에 중단된 뒤, 확장은 정상인데 그 관리자 화면만 "페이지를 찾을 수 없습니다"로 나오고 하루가 지나야 돌아오던 문제를 수정했습니다. 업데이트가 진행되는 동안 사이트를 열어 본 사람이 있으면 그 순간의 "이 확장은 사용 중이 아님" 상태가 기억되는데, 실패로 끝나면 그 기억이 정리되지 않았습니다. 이제 실패로 끝나도 즉시 정리되며, 잘못된 상태가 애초에 기억되지 않도록 함께 보완했습니다. +- 데이터가 많은 사이트를 업그레이드할 때 기존 데이터를 채워 넣는 작업이 일부 행을 건너뛰던 문제를 수정했습니다. 100건씩 나눠 처리하면서 처리한 행이 대상 목록에서 빠지는 만큼 다음 묶음의 시작 위치가 밀려, 250건이면 100건이 처리되지 않은 채 남았습니다. 레이아웃 원본 대조값 채우기와 `json:convert-unicode` 명령이 대상이며, 이제 건수와 무관하게 전건이 처리됩니다. (#84 @glitter-gim 님께서 제보해주셨습니다.) #### 설정 저장·입력 검증 diff --git a/app/Console/Commands/ConvertJsonUnicodeEscapes.php b/app/Console/Commands/ConvertJsonUnicodeEscapes.php index e631005c..84c07b1b 100644 --- a/app/Console/Commands/ConvertJsonUnicodeEscapes.php +++ b/app/Console/Commands/ConvertJsonUnicodeEscapes.php @@ -109,7 +109,7 @@ class ConvertJsonUnicodeEscapes extends Command /** * 테이블 존재 여부를 확인합니다. * - * @param string $table 테이블명 (프리픽스 포함) + * @param string $table 테이블명 (프리픽스 포함) * @return bool 존재 여부 */ private function tableExists(string $table): bool @@ -126,10 +126,10 @@ class ConvertJsonUnicodeEscapes extends Command /** * 특정 테이블의 특정 컬럼을 변환합니다. * - * @param string $table 테이블명 - * @param string $column 컬럼명 - * @param int $chunkSize 청크 크기 - * @param bool $dryRun 드라이런 모드 + * @param string $table 테이블명 + * @param string $column 컬럼명 + * @param int $chunkSize 청크 크기 + * @param bool $dryRun 드라이런 모드 * @return array{int, int} [변환 건수, 스킵 건수] */ private function processColumn(string $table, string $column, int $chunkSize, bool $dryRun): array @@ -152,11 +152,13 @@ class ConvertJsonUnicodeEscapes extends Command $this->components->twoColumnDetail("{$table}.{$column}", "대상 {$total}건 처리 중..."); + // chunkById(키셋 순회) 필수 — 콜백이 필터 조건 컬럼을 UTF-8 로 다시 써서 처리된 + // 행이 `LIKE '%\u%'` 결과에서 이탈한다. OFFSET 기반 chunk() 는 그만큼 앞으로 밀려 + // 아직 변환되지 않은 행을 건너뛴다. (대상 테이블 8종 모두 `id` auto-increment PK) DB::table($table) ->whereNotNull($column) ->where($column, 'LIKE', '%\\\\u%') - ->orderBy('id') - ->chunk($chunkSize, function ($rows) use ($table, $column, $dryRun, &$converted, &$skipped) { + ->chunkById($chunkSize, function ($rows) use ($table, $column, $dryRun, &$converted, &$skipped) { foreach ($rows as $row) { $original = $row->{$column}; $decoded = json_decode($original, true); diff --git a/app/Console/Commands/PlaywrightIssueToken.php b/app/Console/Commands/PlaywrightIssueToken.php index dec5d9b8..cd140197 100644 --- a/app/Console/Commands/PlaywrightIssueToken.php +++ b/app/Console/Commands/PlaywrightIssueToken.php @@ -37,10 +37,14 @@ use Illuminate\Support\Facades\Config; class PlaywrightIssueToken extends Command { protected $signature = 'playwright:issue-token - {--permissions=* : 부여할 권한 식별자 (예: core.templates.layouts.edit). 다중 지정 가능}'; + {--permissions=* : 부여할 권한 식별자 (예: core.templates.layouts.edit). 다중 지정 가능} + {--gc-hours=6 : 이 시간(시)보다 오래된 playwright 테스트 유저/역할을 발급 전 정리. 0 이면 정리 안 함}'; protected $description = 'Playwright E2E 용 Sanctum 토큰 발급 (CLI + G7_PLAYWRIGHT_BYPASS 3중 가드)'; + /** 테스트 전용 역할 식별자 접두사 */ + private const TEST_ROLE_PREFIX = 'playwright_test_'; + public function handle(): int { // ① CLI 한정 — production 웹 요청에서 절대 도달 불가 @@ -61,6 +65,15 @@ class PlaywrightIssueToken extends Command // SettingsServiceProvider::applyDebugConfig 는 bypass flag 가 있으면 settings JSON 덮어쓰기를 이미 건너뛴 상태. Config::set('app.debug', true); + // 발급 전 오래된 테스트 아티팩트 정리 — 이 커맨드는 호출마다 유저 1명 + 역할 1개를 + // 새로 만들지만 회수 주체가 없어 그대로 누적된다. 정리하지 않으면 회원/역할 관리 화면이 + // 테스트 잔재로 뒤덮인다(실측: 발급 2974회 → 유저 2974명·역할 2974개 잔존). + // 시간 임계값을 두어 동시 실행 중인 다른 워커의 계정은 건드리지 않는다. + $gcHours = (int) $this->option('gc-hours'); + if ($gcHours > 0) { + $this->pruneStaleTestArtifacts($gcHours); + } + $permissions = $this->option('permissions') ?: []; $user = $this->makeAdminUser($permissions); @@ -71,6 +84,54 @@ class PlaywrightIssueToken extends Command return self::SUCCESS; } + /** + * 임계 시간보다 오래된 playwright 테스트 유저/역할을 정리한다. + * + * 대상: `playwright_test_*` 역할과, 그 역할이 유일한 확장 역할인 유저(= 이 커맨드가 + * factory 로 만든 계정). 실제 회원과 구분되도록 반드시 역할 소유 관계로만 판별한다. + * + * chunkById(키셋 순회) 필수 — 콜백이 순회 대상 행을 삭제하므로 OFFSET 기반 chunk()/each() + * 는 다음 페이지가 줄어든 결과 집합을 지나쳐 일부를 건너뛴다. + * + * @param int $hours 이 시간보다 오래된 아티팩트만 정리 + * @return void + */ + private function pruneStaleTestArtifacts(int $hours): void + { + $threshold = now()->subHours($hours); + $roles = 0; + $users = 0; + + Role::where('identifier', 'like', self::TEST_ROLE_PREFIX.'%') + ->where('created_at', '<', $threshold) + ->chunkById(100, function ($chunk) use (&$roles, &$users) { + foreach ($chunk as $role) { + // 이 역할을 가진 유저 중, 다른 playwright 역할이 없는 계정만 제거 대상 + foreach ($role->users()->get() as $user) { + $otherTestRoles = $user->roles() + ->where('roles.id', '!=', $role->id) + ->where('roles.identifier', 'like', self::TEST_ROLE_PREFIX.'%') + ->count(); + if ($otherTestRoles === 0) { + $user->tokens()->delete(); + $user->roles()->detach(); + $user->forceDelete(); + $users++; + } + } + + $role->permissions()->detach(); + $role->users()->detach(); + $role->delete(); + $roles++; + } + }); + + if ($roles > 0) { + $this->info("[gc] playwright 테스트 잔재 정리: 역할 {$roles}건, 유저 {$users}건"); + } + } + /** * 권한 식별자 배열로 관리자 유저를 생성하고 권한을 부여한다. * @@ -86,11 +147,15 @@ class PlaywrightIssueToken extends Command $permissionIds = []; foreach ($permissions as $identifier) { + // Role/Permission 의 name·description 은 모델에서 array 로 캐스팅된다. + // 여기서 json_encode 한 문자열을 넣으면 Eloquent 가 한 번 더 인코딩해 + // 이중 인코딩된 값이 저장되고, 관리자 화면(역할 선택 등)에 JSON 원문이 + // `{"ko":"\uXXXX…"}` 형태로 그대로 노출된다. 배열을 그대로 넘긴다. $permission = Permission::firstOrCreate( ['identifier' => $identifier], [ - 'name' => json_encode(['ko' => $identifier, 'en' => $identifier]), - 'description' => json_encode(['ko' => $identifier, 'en' => $identifier]), + 'name' => ['ko' => $identifier, 'en' => $identifier], + 'description' => ['ko' => $identifier, 'en' => $identifier], 'extension_type' => ExtensionOwnerType::Core, 'extension_identifier' => 'core', 'type' => 'admin', @@ -101,16 +166,16 @@ class PlaywrightIssueToken extends Command $testRole = Role::create([ 'identifier' => 'playwright_test_'.uniqid(), - 'name' => json_encode(['ko' => 'Playwright 테스트 관리자', 'en' => 'Playwright Test Admin']), - 'description' => json_encode(['ko' => 'E2E 자동화 전용', 'en' => 'E2E automation only']), + 'name' => ['ko' => 'Playwright 테스트 관리자', 'en' => 'Playwright Test Admin'], + 'description' => ['ko' => 'E2E 자동화 전용', 'en' => 'E2E automation only'], 'is_active' => true, ]); $adminRole = Role::firstOrCreate( ['identifier' => 'admin'], [ - 'name' => json_encode(['ko' => '관리자', 'en' => 'Admin']), - 'description' => json_encode(['ko' => '시스템 관리자', 'en' => 'System Admin']), + 'name' => ['ko' => '관리자', 'en' => 'Admin'], + 'description' => ['ko' => '시스템 관리자', 'en' => 'System Admin'], 'extension_type' => ExtensionOwnerType::Core, 'extension_identifier' => 'core', 'type' => 'admin', diff --git a/app/Extension/ModuleManager.php b/app/Extension/ModuleManager.php index 6bbe445e..1c7b2abd 100644 --- a/app/Extension/ModuleManager.php +++ b/app/Extension/ModuleManager.php @@ -4491,7 +4491,11 @@ class ModuleManager implements ModuleManagerInterface $onProgress?->__invoke('layout', '레이아웃 갱신 중...'); if ($previousStatus === ExtensionStatus::Active->value && $module) { $preserveModified = ($layoutStrategy === 'keep'); - $this->registerModuleLayouts($identifier); + // registerModuleLayouts() 를 여기서 호출하지 않는다 — 그 메서드는 전략을 + // 모른 채 모든 레이아웃의 content 와 original_content_hash 를 파일 기준으로 + // 덮어써서, 뒤따르는 refreshModuleLayouts($preserveModified) 가 비교할 + // "사용자 수정본" 을 이미 지워버린다(= keep 전략이 항상 무효화). + // 신규 레이아웃 생성은 refreshModuleLayouts 의 created 분기가 담당한다. $this->registerLayoutExtensions($module); $this->refreshModuleLayouts($identifier, $preserveModified); } diff --git a/app/Extension/PluginManager.php b/app/Extension/PluginManager.php index e33da04e..3d8783a9 100644 --- a/app/Extension/PluginManager.php +++ b/app/Extension/PluginManager.php @@ -4671,7 +4671,11 @@ class PluginManager implements PluginManagerInterface $onProgress?->__invoke('layout', '레이아웃 갱신 중...'); if ($previousStatus === ExtensionStatus::Active->value && $plugin) { $preserveModified = ($layoutStrategy === 'keep'); - $this->registerPluginLayouts($identifier); + // registerPluginLayouts() 를 여기서 호출하지 않는다 — 그 메서드는 전략을 + // 모른 채 모든 레이아웃의 content 와 original_content_hash 를 파일 기준으로 + // 덮어써서, 뒤따르는 refreshPluginLayouts($preserveModified) 가 비교할 + // "사용자 수정본" 을 이미 지워버린다(= keep 전략이 항상 무효화). + // 신규 레이아웃 생성은 refreshPluginLayouts 의 created 분기가 담당한다. $this->registerLayoutExtensions($plugin); $this->refreshPluginLayouts($identifier, $preserveModified); } diff --git a/app/Extension/TemplateManager.php b/app/Extension/TemplateManager.php index 4767727f..42e2c3d0 100644 --- a/app/Extension/TemplateManager.php +++ b/app/Extension/TemplateManager.php @@ -2806,7 +2806,15 @@ class TemplateManager implements TemplateManagerInterface ]; } - $allLayouts = $this->layoutRepository->getByTemplateId($record->id); + // 템플릿 자신이 소유한 레이아웃만 센다 — getByTemplateId() 는 같은 template_id 에 + // 등록된 모듈/플러그인 소유 레이아웃까지 반환해서, 남의 확장 수정본이 템플릿 + // 업데이트 모달에 자기 것으로 집계된다. 실제 갱신 범위(refreshTemplateLayouts)는 + // source_type='template' + source_identifier=null 뿐이므로 표시와 동작이 어긋난다. + $allLayouts = $this->layoutRepository->getByTemplateIdWithFilter( + $record->id, + 'template', + null + ); $modifiedLayouts = $allLayouts->filter(function ($layout) { if (! $layout->original_content_hash) { return false; // hash 없으면 (레거시 데이터) 미수정 취급 diff --git a/app/Http/Controllers/Api/Admin/ModuleController.php b/app/Http/Controllers/Api/Admin/ModuleController.php index 7cf5d4ac..b1d95d8c 100644 --- a/app/Http/Controllers/Api/Admin/ModuleController.php +++ b/app/Http/Controllers/Api/Admin/ModuleController.php @@ -3,9 +3,11 @@ namespace App\Http\Controllers\Api\Admin; use App\Enums\LanguagePackScope; +use App\Extension\Vendor\VendorMode; use App\Http\Controllers\Api\Base\AdminBaseController; use App\Http\Controllers\Concerns\InjectsExtensionLanguagePacks; use App\Http\Controllers\Concerns\OrchestratesCascadeInstall; +use App\Http\Requests\Extension\ChangelogRequest; use App\Http\Requests\Module\ActivateModuleRequest; use App\Http\Requests\Module\DeactivateModuleRequest; use App\Http\Requests\Module\IndexModuleRequest; @@ -16,10 +18,10 @@ use App\Http\Requests\Module\PerformModuleUpdateRequest; use App\Http\Requests\Module\PreviewModuleManifestRequest; use App\Http\Requests\Module\RefreshModuleLayoutsRequest; use App\Http\Requests\Module\UninstallModuleRequest; -use App\Http\Requests\Extension\ChangelogRequest; use App\Http\Resources\ModuleCollection; use App\Http\Resources\ModuleResource; use App\Services\Extension\ExtensionInstallPreviewBuilder; +use App\Services\LanguagePack\LanguagePackBundledRegistrar; use App\Services\LicenseService; use App\Services\ModuleService; use App\Services\TemplateService; @@ -169,7 +171,7 @@ class ModuleController extends AdminBaseController public function installPreview(string $moduleName, ExtensionInstallPreviewBuilder $builder): JsonResponse { try { - $preview = $builder->build(\App\Enums\LanguagePackScope::Module, $moduleName); + $preview = $builder->build(LanguagePackScope::Module, $moduleName); return $this->success('module.fetch_success', $preview); } catch (\Exception $e) { @@ -188,7 +190,7 @@ class ModuleController extends AdminBaseController try { $validated = $request->validated(); $moduleName = $validated['module_name']; - $vendorMode = \App\Extension\Vendor\VendorMode::fromStringOrAuto( + $vendorMode = VendorMode::fromStringOrAuto( $validated['vendor_mode'] ?? null ); @@ -253,7 +255,7 @@ class ModuleController extends AdminBaseController $moduleInfo = $result['module_info'] ?? null; // 요구사항 #7: 재활성화 시 cascade 비활성화됐던 언어팩 목록 응답에 포함 (요구사항 #8: 빈 배열이면 모달 표시 안 함) - $pendingLanguagePacks = app(\App\Services\LanguagePack\LanguagePackBundledRegistrar::class) + $pendingLanguagePacks = app(LanguagePackBundledRegistrar::class) ->getPendingForReactivation('module', $moduleName); if ($moduleInfo) { @@ -490,6 +492,13 @@ class ModuleController extends AdminBaseController public function checkModifiedLayouts(string $moduleName): JsonResponse { try { + // 미존재 식별자는 404 로 구분한다. 존재 확인 없이 조회하면 레이아웃 0건과 + // 모듈 부재가 똑같이 "수정된 레이아웃 없음" 으로 보고되어, 오타·제거된 모듈이 + // 조용히 "수정 없음" 으로 통과한다 (show/uninstall-info 와 동일 규약). + if (! $this->moduleService->getModuleInfo($moduleName)) { + return $this->error('module.not_found', 404, null, ['module' => $moduleName]); + } + $result = $this->moduleService->checkModifiedLayouts($moduleName); return $this->success('modules.check_modified_layouts_success', $result); @@ -515,7 +524,7 @@ class ModuleController extends AdminBaseController { try { $validated = $request->validated(); - $vendorMode = \App\Extension\Vendor\VendorMode::fromStringOrAuto( + $vendorMode = VendorMode::fromStringOrAuto( $validated['vendor_mode'] ?? null ); $layoutStrategy = $validated['layout_strategy'] ?? 'overwrite'; @@ -524,14 +533,23 @@ class ModuleController extends AdminBaseController $moduleInfo = $result['module_info'] ?? null; + // 메시지 치환 파라미터를 반드시 전달한다 — 누락 시 ":module"/":version" + // 플레이스홀더가 그대로 사용자에게 노출된다. + $messageParams = [ + 'module' => $moduleName, + 'version' => $result['to_version'] ?? ($moduleInfo['version'] ?? ''), + ]; + if ($moduleInfo) { return $this->successWithResource( 'modules.update_success', - new ModuleResource($moduleInfo) + new ModuleResource($moduleInfo), + 200, + $messageParams ); } - return $this->success('modules.update_success', $result); + return $this->success('modules.update_success', $result, 200, $messageParams); } catch (ValidationException $e) { // Service/Manager에서 이미 번역된 메시지를 errors에 포함하므로 // 첫 번째 에러를 top-level message로 직접 사용 (이중 래핑 방지) @@ -601,7 +619,7 @@ class ModuleController extends AdminBaseController /** * 모듈의 라이선스 파일 내용을 반환합니다. * - * @param string $identifier 모듈 식별자 + * @param string $identifier 모듈 식별자 * @return JsonResponse */ public function license(string $identifier): JsonResponse diff --git a/app/Http/Controllers/Api/Admin/PluginController.php b/app/Http/Controllers/Api/Admin/PluginController.php index c9dbd370..a1d80464 100644 --- a/app/Http/Controllers/Api/Admin/PluginController.php +++ b/app/Http/Controllers/Api/Admin/PluginController.php @@ -3,24 +3,26 @@ namespace App\Http\Controllers\Api\Admin; use App\Enums\LanguagePackScope; +use App\Extension\Vendor\VendorMode; use App\Helpers\PermissionHelper; use App\Http\Controllers\Api\Base\AdminBaseController; use App\Http\Controllers\Concerns\InjectsExtensionLanguagePacks; use App\Http\Controllers\Concerns\OrchestratesCascadeInstall; +use App\Http\Requests\Extension\ChangelogRequest; use App\Http\Requests\Plugin\ActivatePluginRequest; use App\Http\Requests\Plugin\DeactivatePluginRequest; use App\Http\Requests\Plugin\IndexPluginRequest; use App\Http\Requests\Plugin\InstallPluginFromFileRequest; -use App\Http\Requests\Plugin\PreviewPluginManifestRequest; use App\Http\Requests\Plugin\InstallPluginFromGithubRequest; use App\Http\Requests\Plugin\InstallPluginRequest; use App\Http\Requests\Plugin\PerformPluginUpdateRequest; +use App\Http\Requests\Plugin\PreviewPluginManifestRequest; use App\Http\Requests\Plugin\RefreshPluginLayoutsRequest; use App\Http\Requests\Plugin\UninstallPluginRequest; -use App\Http\Requests\Extension\ChangelogRequest; use App\Http\Resources\PluginCollection; use App\Http\Resources\PluginResource; use App\Services\Extension\ExtensionInstallPreviewBuilder; +use App\Services\LanguagePack\LanguagePackBundledRegistrar; use App\Services\LicenseService; use App\Services\PluginService; use App\Services\TemplateService; @@ -177,7 +179,7 @@ class PluginController extends AdminBaseController try { $validated = $request->validated(); $pluginName = $validated['plugin_name']; - $vendorMode = \App\Extension\Vendor\VendorMode::fromStringOrAuto( + $vendorMode = VendorMode::fromStringOrAuto( $validated['vendor_mode'] ?? null ); @@ -242,7 +244,7 @@ class PluginController extends AdminBaseController $pluginInfo = $result['plugin_info'] ?? null; // 요구사항 #7: 재활성화 시 cascade 비활성화됐던 언어팩 목록 응답에 포함 - $pendingLanguagePacks = app(\App\Services\LanguagePack\LanguagePackBundledRegistrar::class) + $pendingLanguagePacks = app(LanguagePackBundledRegistrar::class) ->getPendingForReactivation('plugin', $pluginName); if ($pluginInfo) { @@ -498,6 +500,12 @@ class PluginController extends AdminBaseController public function checkModifiedLayouts(string $pluginName): JsonResponse { try { + // 미존재 식별자는 404 로 구분한다. 존재 확인 없이 조회하면 레이아웃 0건과 + // 플러그인 부재가 똑같이 "수정된 레이아웃 없음" 으로 보고된다. + if (! $this->pluginService->getPluginInfo($pluginName)) { + return $this->error('plugins.not_found', 404, null, ['plugin' => $pluginName]); + } + $result = $this->pluginService->checkModifiedLayouts($pluginName); return $this->success('plugins.check_modified_layouts_success', $result); @@ -523,7 +531,7 @@ class PluginController extends AdminBaseController { try { $validated = $request->validated(); - $vendorMode = \App\Extension\Vendor\VendorMode::fromStringOrAuto( + $vendorMode = VendorMode::fromStringOrAuto( $validated['vendor_mode'] ?? null ); $layoutStrategy = $validated['layout_strategy'] ?? 'overwrite'; @@ -532,14 +540,23 @@ class PluginController extends AdminBaseController $pluginInfo = $result['plugin_info'] ?? null; + // 메시지 치환 파라미터를 반드시 전달한다 — 누락 시 ":plugin"/":version" + // 플레이스홀더가 그대로 사용자에게 노출된다. + $messageParams = [ + 'plugin' => $pluginName, + 'version' => $result['to_version'] ?? ($pluginInfo['version'] ?? ''), + ]; + if ($pluginInfo) { return $this->successWithResource( 'plugins.update_success', - new PluginResource($pluginInfo) + new PluginResource($pluginInfo), + 200, + $messageParams ); } - return $this->success('plugins.update_success', $result); + return $this->success('plugins.update_success', $result, 200, $messageParams); } catch (ValidationException $e) { // Service/Manager에서 이미 번역된 메시지를 errors에 포함하므로 // 첫 번째 에러를 top-level message로 직접 사용 (이중 래핑 방지) @@ -623,7 +640,7 @@ class PluginController extends AdminBaseController /** * 플러그인의 라이선스 파일 내용을 반환합니다. * - * @param string $identifier 플러그인 식별자 + * @param string $identifier 플러그인 식별자 * @return JsonResponse */ public function license(string $identifier): JsonResponse diff --git a/app/Http/Controllers/Api/Admin/TemplateController.php b/app/Http/Controllers/Api/Admin/TemplateController.php index eb3dcdc7..8eeabc3a 100644 --- a/app/Http/Controllers/Api/Admin/TemplateController.php +++ b/app/Http/Controllers/Api/Admin/TemplateController.php @@ -7,20 +7,21 @@ use App\Helpers\PermissionHelper; use App\Http\Controllers\Api\Base\AdminBaseController; use App\Http\Controllers\Concerns\InjectsExtensionLanguagePacks; use App\Http\Controllers\Concerns\OrchestratesCascadeInstall; +use App\Http\Requests\Extension\ChangelogRequest; use App\Http\Requests\Template\ActivateTemplateRequest; use App\Http\Requests\Template\DeactivateTemplateRequest; use App\Http\Requests\Template\IndexTemplateRequest; use App\Http\Requests\Template\InstallTemplateFromFileRequest; -use App\Http\Requests\Template\PreviewTemplateManifestRequest; use App\Http\Requests\Template\InstallTemplateFromGithubRequest; use App\Http\Requests\Template\InstallTemplateRequest; use App\Http\Requests\Template\PerformTemplateUpdateRequest; +use App\Http\Requests\Template\PreviewTemplateManifestRequest; use App\Http\Requests\Template\RefreshTemplateLayoutsRequest; use App\Http\Requests\Template\UninstallTemplateRequest; -use App\Http\Requests\Extension\ChangelogRequest; use App\Http\Resources\TemplateCollection; use App\Http\Resources\TemplateResource; use App\Services\Extension\ExtensionInstallPreviewBuilder; +use App\Services\LanguagePack\LanguagePackBundledRegistrar; use App\Services\LicenseService; use App\Services\TemplateService; use Illuminate\Http\JsonResponse; @@ -215,7 +216,7 @@ class TemplateController extends AdminBaseController $templateInfo = $result['template_info'] ?? null; // 요구사항 #7: 재활성화 시 cascade 비활성화됐던 언어팩 목록 응답에 포함 - $pendingLanguagePacks = app(\App\Services\LanguagePack\LanguagePackBundledRegistrar::class) + $pendingLanguagePacks = app(LanguagePackBundledRegistrar::class) ->getPendingForReactivation('template', $templateName); if ($templateInfo) { @@ -435,6 +436,12 @@ class TemplateController extends AdminBaseController public function checkModifiedLayouts(string $templateName): JsonResponse { try { + // 미존재 식별자는 404 로 구분한다. 존재 확인 없이 조회하면 레이아웃 0건과 + // 템플릿 부재가 똑같이 "수정된 레이아웃 없음" 으로 보고된다. + if (! $this->templateService->getTemplateInfo($templateName)) { + return $this->error('templates.not_found', 404, null, ['template' => $templateName]); + } + $result = $this->templateService->checkModifiedLayouts($templateName); return $this->success('templates.check_modified_layouts_success', $result); @@ -466,14 +473,23 @@ class TemplateController extends AdminBaseController $templateInfo = $result['template_info'] ?? null; + // 메시지 치환 파라미터를 반드시 전달한다 — 누락 시 ":template"/":version" + // 플레이스홀더가 그대로 사용자에게 노출된다. + $messageParams = [ + 'template' => $templateName, + 'version' => $result['to_version'] ?? ($templateInfo['version'] ?? ''), + ]; + if ($templateInfo) { return $this->successWithResource( 'templates.update_success', - new TemplateResource($templateInfo) + new TemplateResource($templateInfo), + 200, + $messageParams ); } - return $this->success('templates.update_success', $result); + return $this->success('templates.update_success', $result, 200, $messageParams); } catch (ValidationException $e) { // Service/Manager에서 이미 번역된 메시지를 errors에 포함하므로 // 첫 번째 에러를 top-level message로 직접 사용 (이중 래핑 방지) @@ -516,7 +532,7 @@ class TemplateController extends AdminBaseController /** * 템플릿의 라이선스 파일 내용을 반환합니다. * - * @param string $identifier 템플릿 식별자 + * @param string $identifier 템플릿 식별자 * @return JsonResponse */ public function license(string $identifier): JsonResponse diff --git a/app/Seo/ExpressionEvaluator.php b/app/Seo/ExpressionEvaluator.php index 9ba6324b..3d48d1ba 100644 --- a/app/Seo/ExpressionEvaluator.php +++ b/app/Seo/ExpressionEvaluator.php @@ -24,6 +24,13 @@ class ExpressionEvaluator */ private array $seoOverrides = []; + /** + * 번역 면제 바인딩 접두사 (`{{raw:expr}}`) + * + * 프론트엔드 `rawMarkers.ts` 의 RAW_PREFIX 와 동일해야 합니다. + */ + private const RAW_PREFIX = 'raw:'; + public function __construct() { $this->pipeRegistry = new PipeRegistry; @@ -87,6 +94,11 @@ class ExpressionEvaluator if ($this->isSingleBinding($trimmed)) { $expr = trim(substr($trimmed, 2, -2)); + // raw: 접두사 제거 — 남겨 두면 콜론이 식의 일부로 파싱돼 평가가 실패한다. + if (str_starts_with($expr, self::RAW_PREFIX)) { + $expr = trim(substr($expr, strlen(self::RAW_PREFIX))); + } + // 파이프 표현식: 원본 값을 파이프로 변환 후 반환 if (PipeRegistry::hasPipes($expr)) { [$baseExpr, $pipes] = PipeRegistry::splitPipes($expr); @@ -281,10 +293,21 @@ class ExpressionEvaluator return $this->resolveTranslation($expression, $context); } + // raw: 접두사(번역 면제 바인딩)를 벗기고 후처리 대상에서 제외한다. + // React 는 `{{raw:expr}}` 의 접두사를 떼고 평가한 뒤 결과의 `$t:` 토큰을 + // 번역하지 않는다(rawMarkers). 여기서 접두사를 그대로 두면 콜론이 식의 + // 일부로 파싱되어 평가가 실패하고, 봇 화면에서만 값이 사라진다. + $rawExempt = false; + // {{binding | pipe}} 패턴 치환 (파이프 표현식 지원) - $result = (string) preg_replace_callback('/\{\{(.+?)\}\}/', function ($matches) use ($context) { + $result = (string) preg_replace_callback('/\{\{(.+?)\}\}/', function ($matches) use ($context, &$rawExempt) { $expr = trim($matches[1]); + if (str_starts_with($expr, self::RAW_PREFIX)) { + $rawExempt = true; + $expr = trim(substr($expr, strlen(self::RAW_PREFIX))); + } + // 파이프 분리: expr | pipe1 | pipe2(arg) if (PipeRegistry::hasPipes($expr)) { [$baseExpr, $pipes] = PipeRegistry::splitPipes($expr); @@ -304,7 +327,8 @@ class ExpressionEvaluator }, $expression); // 인라인 $t:key 토큰 해석 ({{}} 외부 텍스트 내 $t:key|param=value 패턴) - if (str_contains($result, '$t:')) { + // raw: 바인딩 결과는 번역 면제 — React 와 동일하게 토큰을 그대로 둔다. + if (! $rawExempt && str_contains($result, '$t:')) { $result = preg_replace_callback('/\$t:(?:defer:)?([\w.\-]+(?:\|[\w.\-]+=[\w.\-{}]+)*)/', function ($matches) use ($context) { return $this->resolveTranslation('$t:'.$matches[1], $context); }, $result); diff --git a/database/migrations/2026_04_01_000704_add_original_content_hash_to_template_layouts_table.php b/database/migrations/2026_04_01_000704_add_original_content_hash_to_template_layouts_table.php index 4545d8d9..3cafc923 100644 --- a/database/migrations/2026_04_01_000704_add_original_content_hash_to_template_layouts_table.php +++ b/database/migrations/2026_04_01_000704_add_original_content_hash_to_template_layouts_table.php @@ -13,21 +13,27 @@ return new class extends Migration public function up(): void { Schema::table('template_layouts', function (Blueprint $table) { - $table->string('original_content_hash', 64) - ->nullable() - ->after('content') - ->comment('원본 레이아웃 콘텐츠 SHA-256 해시 (수정 감지용)'); - $table->unsignedInteger('original_content_size') - ->nullable() - ->after('original_content_hash') - ->comment('원본 레이아웃 콘텐츠 바이트 크기 (변화량 표시용)'); + if (! Schema::hasColumn('template_layouts', 'original_content_hash')) { + $table->string('original_content_hash', 64) + ->nullable() + ->after('content') + ->comment('원본 레이아웃 콘텐츠 SHA-256 해시 (수정 감지용)'); + } + if (! Schema::hasColumn('template_layouts', 'original_content_size')) { + $table->unsignedInteger('original_content_size') + ->nullable() + ->after('original_content_hash') + ->comment('원본 레이아웃 콘텐츠 바이트 크기 (변화량 표시용)'); + } }); // 기존 데이터 hash 백필 (현재 content = 원본으로 간주) + // chunkById(키셋 순회) 필수 — 콜백이 필터 컬럼(original_content_hash)을 채우므로 + // 처리된 행이 필터 결과에서 이탈한다. OFFSET 기반 chunk() 는 그만큼 앞으로 밀려 + // 미처리 행을 건너뛴다. DB::table('template_layouts') ->whereNull('original_content_hash') - ->orderBy('id') - ->chunk(100, function ($layouts) { + ->chunkById(100, function ($layouts) { foreach ($layouts as $layout) { $content = json_decode($layout->content, true); $normalized = json_encode($content, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); diff --git a/database/migrations/2026_05_22_000002_add_original_content_hash_to_template_layout_extensions_table.php b/database/migrations/2026_05_22_000002_add_original_content_hash_to_template_layout_extensions_table.php index 52af35ae..435244da 100644 --- a/database/migrations/2026_05_22_000002_add_original_content_hash_to_template_layout_extensions_table.php +++ b/database/migrations/2026_05_22_000002_add_original_content_hash_to_template_layout_extensions_table.php @@ -28,10 +28,12 @@ return new class extends Migration }); // 기존 데이터 hash 백필 (현재 content = 원본으로 간주) + // chunkById(키셋 순회) 필수 — 콜백이 필터 컬럼(original_content_hash)을 채우므로 + // 처리된 행이 필터 결과에서 이탈한다. OFFSET 기반 chunk() 는 그만큼 앞으로 밀려 + // 미처리 행을 건너뛴다. DB::table('template_layout_extensions') ->whereNull('original_content_hash') - ->orderBy('id') - ->chunk(100, function ($extensions) { + ->chunkById(100, function ($extensions) { foreach ($extensions as $extension) { $content = json_decode($extension->content, true); $normalized = json_encode($content, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); diff --git a/docs/backend/api/modules.md b/docs/backend/api/modules.md index a9aa6a75..1b617fb4 100644 --- a/docs/backend/api/modules.md +++ b/docs/backend/api/modules.md @@ -3312,11 +3312,38 @@ Authorization: Bearer {YOUR_TOKEN} **응답 필드** (`data` 내부) - +| 필드 | 타입 | 설명 | +| --- | --- | --- | +| has_modified_layouts | boolean | 수정된 레이아웃 존재 여부 | +| modified_count | integer | 수정된 레이아웃 수 | +| modified_layouts | array | 수정된 레이아웃 목록 | +| modified_layouts[].id | integer | 레이아웃 ID | +| modified_layouts[].name | string | 레이아웃 이름 | +| modified_layouts[].updated_at | string\|null | 최종 수정 일시 (`Y-m-d H:i:s`) | +| modified_layouts[].size_diff | integer | 원본 대비 바이트 증감 (음수는 축소) | **응답 예시** - +```json +{ + "success": true, + "message": "수정된 레이아웃 확인이 완료되었습니다.", + "data": { + "has_modified_layouts": true, + "modified_count": 1, + "modified_layouts": [ + { + "id": 47, + "name": "sirsoft-board.admin_board_index", + "updated_at": "2026-07-31 09:20:05", + "size_diff": 28 + } + ] + } +} +``` + +집계 범위는 해당 모듈이 **소유한** 레이아웃으로 한정됩니다. 같은 템플릿에 등록된 다른 확장의 레이아웃은 포함되지 않습니다. **에러 응답** @@ -3324,7 +3351,7 @@ Authorization: Bearer {YOUR_TOKEN} | --- | --- | --- | | 401 | Unauthenticated | 유효한 Bearer 토큰이 없거나 만료된 경우 | | 403 | Forbidden | 요구 권한(`core.modules.read`)이 없는 경우 | -| 404 | Not Found | path 파라미터에 해당하는 리소스가 없는 경우 | +| 404 | Not Found | 해당 식별자의 모듈이 설치되어 있지 않은 경우 (레이아웃 0건과 구분됨) | @@ -3467,7 +3494,7 @@ Content-Type: application/json -**설명** 특정 모듈을 최신 버전으로 업데이트합니다. `core.modules.install` 권한이 필요합니다. `layout_strategy` 로 레이아웃 처리 방식을(overwrite: 새 버전으로 교체, keep: 사용자 수정본 유지) 지정하며, `vendor_mode` 로 Composer 의존성 처리 방식을 선택합니다. 버전 제약·호환성 문제로 막힐 경우 `force: true` 로 강제 진행할 수 있습니다. +**설명** 특정 모듈을 최신 버전으로 업데이트합니다. `core.modules.install` 권한이 필요합니다. `layout_strategy` 로 레이아웃 처리 방식을(overwrite: 새 버전으로 교체, keep: 사용자 수정본 유지) 지정하며, `vendor_mode` 로 Composer 의존성 처리 방식을 선택합니다. 버전 제약·호환성 문제로 막힐 경우 `force: true` 로 강제 진행할 수 있습니다. `keep` 을 지정하면 사용자가 수정한 레이아웃(원본 해시와 현재 내용이 다른 레이아웃)은 갱신 대상에서 제외되어 현재 내용이 그대로 유지되고, 나머지 레이아웃만 파일 기준으로 갱신됩니다. 성공 응답 메시지에는 대상 식별자와 적용된 버전이 채워집니다. ### GET /api/modules/assets/{identifier}/{path} diff --git a/docs/backend/api/plugins.md b/docs/backend/api/plugins.md index 05bfd0e3..75a1c561 100644 --- a/docs/backend/api/plugins.md +++ b/docs/backend/api/plugins.md @@ -1064,11 +1064,38 @@ Authorization: Bearer {YOUR_TOKEN} **응답 필드** (`data` 내부) - +| 필드 | 타입 | 설명 | +| --- | --- | --- | +| has_modified_layouts | boolean | 수정된 레이아웃 존재 여부 | +| modified_count | integer | 수정된 레이아웃 수 | +| modified_layouts | array | 수정된 레이아웃 목록 | +| modified_layouts[].id | integer | 레이아웃 ID | +| modified_layouts[].name | string | 레이아웃 이름 | +| modified_layouts[].updated_at | string\|null | 최종 수정 일시 (`Y-m-d H:i:s`) | +| modified_layouts[].size_diff | integer | 원본 대비 바이트 증감 (음수는 축소) | **응답 예시** - +```json +{ + "success": true, + "message": "수정된 레이아웃 확인이 완료되었습니다.", + "data": { + "has_modified_layouts": true, + "modified_count": 1, + "modified_layouts": [ + { + "id": 47, + "name": "sirsoft-board.admin_board_index", + "updated_at": "2026-07-31 09:20:05", + "size_diff": 28 + } + ] + } +} +``` + +집계 범위는 해당 플러그인이 **소유한** 레이아웃으로 한정됩니다. 같은 템플릿에 등록된 다른 확장의 레이아웃은 포함되지 않습니다. **에러 응답** @@ -1076,7 +1103,7 @@ Authorization: Bearer {YOUR_TOKEN} | --- | --- | --- | | 401 | Unauthenticated | 유효한 Bearer 토큰이 없거나 만료된 경우 | | 403 | Forbidden | 요구 권한(`core.plugins.read`)이 없는 경우 | -| 404 | Not Found | path 파라미터에 해당하는 리소스가 없는 경우 | +| 404 | Not Found | 해당 식별자의 플러그인이 설치되어 있지 않은 경우 (레이아웃 0건과 구분됨) | @@ -1219,7 +1246,7 @@ Content-Type: application/json -**설명** 특정 플러그인을 최신 버전으로 업데이트합니다. `core.plugins.install` 권한이 필요합니다. `layout_strategy` 로 레이아웃 처리 방식을(overwrite: 새 버전으로 교체, keep: 사용자 수정본 유지) 지정하며, `vendor_mode` 로 Composer 의존성 처리 방식을 선택합니다. 버전 제약·호환성 문제로 막힐 경우 `force: true` 로 강제 진행할 수 있습니다. +**설명** 특정 플러그인을 최신 버전으로 업데이트합니다. `core.plugins.install` 권한이 필요합니다. `layout_strategy` 로 레이아웃 처리 방식을(overwrite: 새 버전으로 교체, keep: 사용자 수정본 유지) 지정하며, `vendor_mode` 로 Composer 의존성 처리 방식을 선택합니다. 버전 제약·호환성 문제로 막힐 경우 `force: true` 로 강제 진행할 수 있습니다. `keep` 을 지정하면 사용자가 수정한 레이아웃(원본 해시와 현재 내용이 다른 레이아웃)은 갱신 대상에서 제외되어 현재 내용이 그대로 유지되고, 나머지 레이아웃만 파일 기준으로 갱신됩니다. 성공 응답 메시지에는 대상 식별자와 적용된 버전이 채워집니다. ### GET /api/plugins/assets/{identifier}/{path} diff --git a/docs/backend/api/templates.md b/docs/backend/api/templates.md index b2a13ac6..527a2d1f 100644 --- a/docs/backend/api/templates.md +++ b/docs/backend/api/templates.md @@ -1469,11 +1469,38 @@ Authorization: Bearer {YOUR_TOKEN} **응답 필드** (`data` 내부) - +| 필드 | 타입 | 설명 | +| --- | --- | --- | +| has_modified_layouts | boolean | 수정된 레이아웃 존재 여부 | +| modified_count | integer | 수정된 레이아웃 수 | +| modified_layouts | array | 수정된 레이아웃 목록 | +| modified_layouts[].id | integer | 레이아웃 ID | +| modified_layouts[].name | string | 레이아웃 이름 | +| modified_layouts[].updated_at | string\|null | 최종 수정 일시 (`Y-m-d H:i:s`) | +| modified_layouts[].size_diff | integer | 원본 대비 바이트 증감 (음수는 축소) | **응답 예시** - +```json +{ + "success": true, + "message": "수정된 레이아웃 확인이 완료되었습니다.", + "data": { + "has_modified_layouts": true, + "modified_count": 1, + "modified_layouts": [ + { + "id": 47, + "name": "sirsoft-board.admin_board_index", + "updated_at": "2026-07-31 09:20:05", + "size_diff": 28 + } + ] + } +} +``` + +집계 범위는 해당 템플릿이 **소유한** 레이아웃으로 한정됩니다. 같은 템플릿에 등록된 다른 확장의 레이아웃은 포함되지 않습니다. **에러 응답** @@ -1481,7 +1508,7 @@ Authorization: Bearer {YOUR_TOKEN} | --- | --- | --- | | 401 | Unauthenticated | 유효한 Bearer 토큰이 없거나 만료된 경우 | | 403 | Forbidden | 요구 권한(`core.templates.read`)이 없는 경우 | -| 404 | Not Found | path 파라미터에 해당하는 리소스가 없는 경우 | +| 404 | Not Found | 해당 식별자의 템플릿이 설치되어 있지 않은 경우 (레이아웃 0건과 구분됨) | @@ -2523,7 +2550,7 @@ Content-Type: application/json -**설명** 설치된 템플릿을 최신 버전으로 업데이트합니다. `layout_strategy`(overwrite: 레이아웃 전면 교체 / keep: 사용자 수정 레이아웃 유지)로 레이아웃 처리 방식을 결정하며, `force`로 강제 진행할 수 있습니다(TemplateService::performVersionUpdate). `core.templates.install` 권한이 필요합니다. +**설명** 설치된 템플릿을 최신 버전으로 업데이트합니다. `layout_strategy`(overwrite: 레이아웃 전면 교체 / keep: 사용자 수정 레이아웃 유지)로 레이아웃 처리 방식을 결정하며, `force`로 강제 진행할 수 있습니다(TemplateService::performVersionUpdate). `core.templates.install` 권한이 필요합니다. `keep` 을 지정하면 사용자가 수정한 레이아웃(원본 해시와 현재 내용이 다른 레이아웃)은 갱신 대상에서 제외되어 현재 내용이 그대로 유지되고, 나머지 레이아웃만 파일 기준으로 갱신됩니다. 성공 응답 메시지에는 대상 식별자와 적용된 버전이 채워집니다. ### GET /api/templates/assets/{identifier}/{path} diff --git a/lang-packs/_bundled/g7-template-sirsoft-admin_basic-ja/CHANGELOG.md b/lang-packs/_bundled/g7-template-sirsoft-admin_basic-ja/CHANGELOG.md index 43dd0ba6..0861bd7d 100644 --- a/lang-packs/_bundled/g7-template-sirsoft-admin_basic-ja/CHANGELOG.md +++ b/lang-packs/_bundled/g7-template-sirsoft-admin_basic-ja/CHANGELOG.md @@ -8,6 +8,8 @@ ### Added +- 확장 업데이트 모달의 "수정 여부 확인 실패" 안내 문구 일본어 번역 추가 (`{modules,plugins,templates}.modals.modified_layouts_check_failed`) — 네트워크 오류로 수정 여부를 확인하지 못했을 때의 경고와 '수정 유지' 권장 안내가 일본어 로케일에서 자연스럽게 표시됩니다. +- 공용 문구 3종 일본어 번역 추가 (`common.refresh`, `common.activate`, `common.skip`) — 게시판·상품 카테고리 목록의 새로고침 버튼과 언어팩 재활성화 안내에서 번역되지 않은 내부 문구가 보이던 문제가 해소됩니다. - 환경설정 > 보안의 2단계 인증 항목 문구 일본어 번역 추가 (`settings.security.two_factor_auth*`) — 항목 이름과 설명이 일본어 로케일에서 자연스럽게 표시됩니다. - 회원 상세의 계정 잠금 상태 표시와 잠금 해제 버튼 문구 일본어 번역 추가 (`users.detail.unlock*`, `users.detail.lock_status`) — 무기한 잠금·기한부 잠금·정상 상태 안내가 일본어 로케일에서 자연스럽게 표시됩니다. - 언어팩 관리 목록의 "파일 없음" 배지와 다시 설치 버튼 문구 일본어 번역 추가 (`language_packs.badge.files_missing`, `language_packs.actions.reinstall`). diff --git a/lang-packs/_bundled/g7-template-sirsoft-admin_basic-ja/frontend/partial/admin.json b/lang-packs/_bundled/g7-template-sirsoft-admin_basic-ja/frontend/partial/admin.json index 3602a0c4..d3dae1aa 100644 --- a/lang-packs/_bundled/g7-template-sirsoft-admin_basic-ja/frontend/partial/admin.json +++ b/lang-packs/_bundled/g7-template-sirsoft-admin_basic-ja/frontend/partial/admin.json @@ -728,7 +728,8 @@ "modified_layouts_warning": "修正されたレイアウトが {{count}} 個あります。「すべて置き換え」を選択すると、修正内容が削除されます。", "no_modified_layouts": "修正されたレイアウトがありません。", "modified_layouts_list_title": "保持される修正レイアウト ({{count}}個)", - "modified_layouts_keep_notice": "上記のレイアウトはアップデート後も現在の内容が保持されます。" + "modified_layouts_keep_notice": "上記のレイアウトはアップデート後も現在の内容が保持されます。", + "modified_layouts_check_failed": "編集の確認ができませんでした。ネットワークの状態を確認してからもう一度試すか、安全に「編集を保持」を選択してください。" }, "tabs": { "file_upload": "ファイル アップロード", @@ -933,7 +934,8 @@ "modified_layouts_warning": "編集されたレイアウトが{{count}}個あります。「すべて置換」を選択すると、編集内容が削除されます。", "no_modified_layouts": "編集されたレイアウトがありません。", "modified_layouts_list_title": "維持される編集レイアウト({{count}}個)", - "modified_layouts_keep_notice": "上記のレイアウトはアップデート後も現在の内容が維持されます。" + "modified_layouts_keep_notice": "上記のレイアウトはアップデート後も現在の内容が維持されます。", + "modified_layouts_check_failed": "編集の確認ができませんでした。ネットワークの状態を確認してからもう一度試すか、安全に「編集を保持」を選択してください。" }, "tabs": { "file_upload": "ファイルアップロード", @@ -2172,7 +2174,8 @@ "restore_note": "復元後は、必ず保存ボタンを押して変更内容を適用してください。", "lines": "行", "chars": "文字" - } + }, + "modified_layouts_check_failed": "編集の確認ができませんでした。ネットワークの状態を確認してからもう一度試すか、安全に「編集を保持」を選択してください。" }, "tabs_install": { "file_upload": "ファイルアップロード", diff --git a/lang-packs/_bundled/g7-template-sirsoft-admin_basic-ja/frontend/partial/common.json b/lang-packs/_bundled/g7-template-sirsoft-admin_basic-ja/frontend/partial/common.json index 222f3bb8..9f605f47 100644 --- a/lang-packs/_bundled/g7-template-sirsoft-admin_basic-ja/frontend/partial/common.json +++ b/lang-packs/_bundled/g7-template-sirsoft-admin_basic-ja/frontend/partial/common.json @@ -76,5 +76,8 @@ "scope_type_role_desc": "同じロールのユーザーリソースのみ", "multilingual": { "add_language": "言語を追加" - } + }, + "refresh": "更新", + "activate": "有効化", + "skip": "スキップ" } diff --git a/modules/_bundled/sirsoft-board/CHANGELOG.md b/modules/_bundled/sirsoft-board/CHANGELOG.md index 057d9acf..3c63e53f 100644 --- a/modules/_bundled/sirsoft-board/CHANGELOG.md +++ b/modules/_bundled/sirsoft-board/CHANGELOG.md @@ -53,6 +53,7 @@ - 관리자 목록에서 검색·필터·정렬을 바꿀 때 표가 다시 그려지는 동안 로딩 표시가 나오지 않던 문제를 수정했습니다. 응답이 늦으면 아무 반응이 없는 것처럼 보여 같은 조작을 반복하게 되던 상황이 사라집니다. - 관리자 화면 일부 아이콘이 의도한 크기보다 크거나 작게 보이던 문제를 수정했습니다. - 관리자 화면 일부 버튼·배지가 다크 모드에서 밝은 색 그대로 표시되던 문제를 수정했습니다. +- 게시판 모듈을 제거할 때 게시판별로 자동 생성된 관리자·승인 단계 역할이 1,000개를 넘으면 일부가 삭제되지 않고 남던 문제를 수정했습니다. 남은 역할은 사용하지 않는 게시판의 것이면서도 회원 권한 목록에 계속 노출됐습니다. 이제 개수와 무관하게 전부 정리됩니다. (#84 @glitter-gim 님께서 제보해주셨습니다.) ## [1.0.2] - 2026-07-14 diff --git a/modules/_bundled/sirsoft-board/module.php b/modules/_bundled/sirsoft-board/module.php index 6317a2c9..b9b167b1 100644 --- a/modules/_bundled/sirsoft-board/module.php +++ b/modules/_bundled/sirsoft-board/module.php @@ -6,12 +6,13 @@ use App\Extension\AbstractModule; use App\Models\Role; use App\Seo\Concerns\LocalizesSeoValues; use Illuminate\Database\Seeder; +use Illuminate\Support\Facades\Schema; use Modules\Sirsoft\Board\Database\Seeders\BoardTypeSeeder; use Modules\Sirsoft\Board\Listeners\ActivityLogDescriptionResolver; use Modules\Sirsoft\Board\Listeners\BoardActivityLogListener; +use Modules\Sirsoft\Board\Listeners\BoardCommentsCountSyncListener; use Modules\Sirsoft\Board\Listeners\BoardNotificationChannelListener; use Modules\Sirsoft\Board\Listeners\BoardNotificationDataListener; -use Modules\Sirsoft\Board\Listeners\BoardCommentsCountSyncListener; use Modules\Sirsoft\Board\Listeners\BoardPostsCountSyncListener; use Modules\Sirsoft\Board\Listeners\CommentReplySyncListener; use Modules\Sirsoft\Board\Listeners\EcommerceInquiryHookListener; @@ -22,6 +23,7 @@ use Modules\Sirsoft\Board\Listeners\SearchPostsListener; use Modules\Sirsoft\Board\Listeners\SeoBoardCacheListener; use Modules\Sirsoft\Board\Listeners\SeoBoardSettingsCacheListener; use Modules\Sirsoft\Board\Listeners\UserNotificationSettingsListener; +use Modules\Sirsoft\Board\Models\Board; class Module extends AbstractModule { @@ -39,12 +41,17 @@ class Module extends AbstractModule public function uninstall(): bool { // 게시판별 동적 역할 정리 (sirsoft-board.*.manager, sirsoft-board.*.step) + // chunkById(키셋 순회) 필수 — each() 는 OFFSET 기반 청크(기본 1000건)라 + // 콜백이 순회 대상을 삭제하면 다음 페이지의 OFFSET 이 줄어든 결과 집합을 지나쳐 + // 1000건을 넘는 역할이 그대로 남는다. Role::where('extension_type', 'module') ->where('extension_identifier', 'sirsoft-board') - ->each(function (Role $role) { - $role->permissions()->detach(); - $role->users()->detach(); - $role->delete(); + ->chunkById(100, function ($roles) { + foreach ($roles as $role) { + $role->permissions()->detach(); + $role->users()->detach(); + $role->delete(); + } }); return parent::uninstall(); @@ -308,14 +315,14 @@ class Module extends AbstractModule */ public function getDynamicPermissionIdentifiers(): array { - if (! \Illuminate\Support\Facades\Schema::hasTable('boards')) { + if (! Schema::hasTable('boards')) { return []; } $actions = array_keys((array) config('sirsoft-board.board_permission_definitions', [])); $module = $this->getIdentifier(); $ids = []; - foreach (\Modules\Sirsoft\Board\Models\Board::query()->select('slug')->get() as $board) { + foreach (Board::query()->select('slug')->get() as $board) { $category = $module.'.'.$board->slug; $ids[] = $category; foreach ($actions as $action) { @@ -335,13 +342,13 @@ class Module extends AbstractModule */ public function getDynamicRoleIdentifiers(): array { - if (! \Illuminate\Support\Facades\Schema::hasTable('boards')) { + if (! Schema::hasTable('boards')) { return []; } $module = $this->getIdentifier(); $ids = []; - foreach (\Modules\Sirsoft\Board\Models\Board::query()->select('slug')->get() as $board) { + foreach (Board::query()->select('slug')->get() as $board) { $ids[] = $module.'.'.$board->slug.'.manager'; $ids[] = $module.'.'.$board->slug.'.step'; } @@ -356,12 +363,12 @@ class Module extends AbstractModule */ public function getDynamicMenuSlugs(): array { - if (! \Illuminate\Support\Facades\Schema::hasTable('boards')) { + if (! Schema::hasTable('boards')) { return []; } $slugs = []; - foreach (\Modules\Sirsoft\Board\Models\Board::query()->select('slug')->get() as $board) { + foreach (Board::query()->select('slug')->get() as $board) { $slugs[] = 'board-'.$board->slug; } diff --git a/modules/_bundled/sirsoft-board/tests/Feature/UninstallDynamicRoleCleanupTest.php b/modules/_bundled/sirsoft-board/tests/Feature/UninstallDynamicRoleCleanupTest.php new file mode 100644 index 00000000..a0f8aa5b --- /dev/null +++ b/modules/_bundled/sirsoft-board/tests/Feature/UninstallDynamicRoleCleanupTest.php @@ -0,0 +1,195 @@ +each(callback)` 은 Eloquent 의 OFFSET 기반 + * chunk 순회(기본 1000건)다. 콜백이 순회 대상 행을 삭제하므로 두 번째 페이지의 + * OFFSET 1000 이 이미 줄어든 결과 집합을 지나쳐 남은 행을 건너뛴다. + * + * 따라서 동적 역할이 1000건을 넘는 사이트에서 모듈을 제거하면 초과분이 그대로 + * 남는다. `chunkById()`(키셋 순회) 로 바꾸면 삭제와 무관하게 전건이 처리된다. + * + * 시드 건수는 Eloquent `each()` 의 기본 청크 크기(1000)보다 커야 결함이 드러나므로 + * 1100건을 사용한다. + */ +class UninstallDynamicRoleCleanupTest extends ModuleTestCase +{ + /** + * 시드 건수 (Eloquent each() 기본 청크 1000 초과 필수) + */ + private const SEED_COUNT = 1100; + + /** + * 권한/사용자 피벗을 연결할 역할 수 (뒤쪽 = OFFSET skip 구간) + */ + private const PIVOT_TAIL_COUNT = 50; + + /** + * 시드 역할 식별자 프리픽스 (정리 대상 식별용) + */ + private const IDENTIFIER_PREFIX = 'chunkskip'; + + private Module $module; + + protected function setUp(): void + { + parent::setUp(); + + $this->module = new Module; + $this->purgeSeededRoles(); + } + + /** + * ModuleTestCase 는 프로세스당 1회 `migrate:fresh`(DDL) 를 실행하므로 그 케이스의 + * 트랜잭션이 암묵적으로 커밋된다 — 시드 행이 롤백되지 않고 다음 케이스로 새어 + * identifier unique 충돌을 일으킨다. 케이스 전후로 명시 정리한다. + */ + protected function tearDown(): void + { + $this->purgeSeededRoles(); + + parent::tearDown(); + } + + /** + * 이 테스트가 시드한 역할과 그 피벗을 제거합니다. + * + * @return void + */ + private function purgeSeededRoles(): void + { + $roleIds = DB::table('roles') + ->where('identifier', 'LIKE', '%.'.self::IDENTIFIER_PREFIX.'%') + ->pluck('id') + ->all(); + + if ($roleIds === []) { + return; + } + + DB::table('role_permissions')->whereIn('role_id', $roleIds)->delete(); + DB::table('user_roles')->whereIn('role_id', $roleIds)->delete(); + DB::table('roles')->whereIn('id', $roleIds)->delete(); + } + + /** + * 게시판별 동적 역할을 시드합니다. + * + * @return void + */ + private function seedDynamicRoles(): void + { + $rows = []; + + for ($i = 0; $i < self::SEED_COUNT; $i++) { + $rows[] = [ + 'identifier' => 'sirsoft-board.chunkskip'.$i.'.manager', + 'name' => json_encode(['ko' => '게시판 관리자 '.$i, 'en' => 'Board Manager '.$i]), + 'extension_type' => 'module', + 'extension_identifier' => 'sirsoft-board', + 'is_active' => true, + 'created_at' => now(), + 'updated_at' => now(), + ]; + } + + foreach (array_chunk($rows, 200) as $batch) { + DB::table('roles')->insert($batch); + } + } + + /** + * 동적 역할 잔여 건수를 반환합니다. + * + * @return int 잔여 건수 + */ + private function remainingDynamicRoleCount(): int + { + return Role::where('extension_type', 'module') + ->where('extension_identifier', 'sirsoft-board') + ->count(); + } + + public function test_uninstall_removes_every_dynamic_role_beyond_the_first_chunk(): void + { + $this->seedDynamicRoles(); + + $this->assertSame( + self::SEED_COUNT, + $this->remainingDynamicRoleCount(), + '시드 직후에는 동적 역할이 시드 건수만큼 존재해야 합니다.' + ); + + $this->assertTrue($this->module->uninstall()); + + $this->assertSame( + 0, + $this->remainingDynamicRoleCount(), + 'OFFSET 순회로 인해 삭제되지 않고 남은 동적 역할이 있습니다 (each → chunkById 필요).' + ); + } + + public function test_uninstall_detaches_permissions_of_roles_in_the_skipped_range(): void + { + $this->seedDynamicRoles(); + + $permission = Permission::firstOrCreate( + ['identifier' => 'sirsoft-board.chunkskip.test'], + ['name' => ['ko' => '테스트 권한', 'en' => 'Test Permission'], 'type' => 'admin'] + ); + + $tailRoleIds = Role::where('extension_identifier', 'sirsoft-board') + ->orderByDesc('id') + ->limit(self::PIVOT_TAIL_COUNT) + ->pluck('id') + ->all(); + + foreach ($tailRoleIds as $roleId) { + DB::table('role_permissions')->insert([ + 'role_id' => $roleId, + 'permission_id' => $permission->id, + 'created_at' => now(), + 'updated_at' => now(), + ]); + } + + $this->module->uninstall(); + + $this->assertSame( + 0, + DB::table('role_permissions')->whereIn('role_id', $tailRoleIds)->count(), + '삭제된 역할의 권한 피벗이 남아 있습니다.' + ); + } + + public function test_uninstall_keeps_roles_owned_by_other_extensions(): void + { + $this->seedDynamicRoles(); + + DB::table('roles')->insert([ + 'identifier' => 'sirsoft-other.chunkskip.manager', + 'name' => json_encode(['ko' => '타 확장 역할', 'en' => 'Other Extension Role']), + 'extension_type' => 'module', + 'extension_identifier' => 'sirsoft-other', + 'is_active' => true, + 'created_at' => now(), + 'updated_at' => now(), + ]); + + $this->module->uninstall(); + + $this->assertTrue( + Role::where('extension_identifier', 'sirsoft-other')->exists(), + '다른 확장이 소유한 역할은 삭제되지 않아야 합니다.' + ); + } +} diff --git a/modules/_bundled/sirsoft-ecommerce/database/migrations/2026_04_01_000047_modify_i18n_columns_in_ecommerce_order_options_table.php b/modules/_bundled/sirsoft-ecommerce/database/migrations/2026_04_01_000047_modify_i18n_columns_in_ecommerce_order_options_table.php index bc6961de..362eb03b 100644 --- a/modules/_bundled/sirsoft-ecommerce/database/migrations/2026_04_01_000047_modify_i18n_columns_in_ecommerce_order_options_table.php +++ b/modules/_bundled/sirsoft-ecommerce/database/migrations/2026_04_01_000047_modify_i18n_columns_in_ecommerce_order_options_table.php @@ -20,6 +20,9 @@ return new class extends Migration ->whereNotNull($column) ->where($column, '!=', '') ->orderBy('id') + // audit:allow offset-chunk-mutates-filter 갱신값 json_encode(['ko'=>…]) 은 항상 + // `{"ko":…}` 라 non-null·non-empty — 갱신 후에도 whereNotNull + != '' 소속이 + // 유지되어 결과 집합 크기가 변하지 않는다(OFFSET 밀림 없음). ->chunk(500, function ($rows) use ($column) { foreach ($rows as $row) { $value = $row->{$column}; @@ -60,6 +63,9 @@ return new class extends Migration DB::table('ecommerce_order_options') ->whereNotNull($column) ->orderBy('id') + // audit:allow offset-chunk-mutates-filter 갱신값 $koValue 는 최악의 경우 빈 + // 문자열이며 NULL 이 아니다 — 갱신 후에도 whereNotNull 소속이 유지되어 + // 결과 집합 크기가 변하지 않는다(OFFSET 밀림 없음). ->chunk(500, function ($rows) use ($column) { foreach ($rows as $row) { $value = $row->{$column}; diff --git a/public/build/core/devtools.min.js b/public/build/core/devtools.min.js index 4ba3df17..66ccd681 100644 --- a/public/build/core/devtools.min.js +++ b/public/build/core/devtools.min.js @@ -1558,3 +1558,4 @@ details[open] > .g7dt-summary::before { } `,ve=()=>{const d="g7-devtools-styles";if(document.getElementById(d))return;const t=document.createElement("style");t.id=d,t.textContent=be,document.head.appendChild(t)},le={state:"상태",actions:"액션",cache:"캐시",diagnose:"진단",performance:"성능",lifecycle:"라이프사이클",network:"네트워크",form:"Form",conditional:"조건부",expression:"표현식",handlers:"핸들러",events:"이벤트",datasources:"데이터소스",renders:"렌더링",styles:"스타일",auth:"인증",logs:"로그",layout:"레이아웃",changedetection:"변경감지",staleclosure:"Stale Closure",nestedcontext:"Context",modalscope:"모달스코프",namedactions:"Named Actions"},Ne=700,ue=500,re=400,ce=300,ne="g7-devtools-panel",te=d=>d===null||d===void 0?"g7dt-text-gray":typeof d=="string"?"g7dt-text-yellow":typeof d=="number"?"g7dt-text-cyan":typeof d=="boolean"?"g7dt-text-pink":Array.isArray(d)?"g7dt-text-orange":typeof d=="object"?"g7dt-text-blue":"g7dt-text-white",ye=d=>d===null?"null":d===void 0?"undefined":Array.isArray(d)?`Array(${d.length})`:typeof d=="object"?`Object(${Object.keys(d).length})`:typeof d,we=d=>d===null?"null":d===void 0?"undefined":typeof d=="string"?d.length>50?`"${d.substring(0,50)}..."`:`"${d}"`:typeof d=="boolean"?d?"true":"false":typeof d=="number"?String(d):"",oe=()=>{try{const d=localStorage.getItem(ne);if(d)return JSON.parse(d)}catch(d){console.warn("[G7DevTools] 설정 로드 실패:",d)}return{}},ie=d=>{try{const s={...oe(),...d};localStorage.setItem(ne,JSON.stringify(s))}catch(t){console.warn("[G7DevTools] 설정 저장 실패:",t)}},W=({keyName:d,value:t,path:s,expandedPaths:a,onToggle:g,searchTerm:r,depth:o=0})=>{const p=t!==null&&typeof t=="object",v=a.has(s),l=Array.isArray(t),f=r&&(d.toLowerCase().includes(r.toLowerCase())||typeof t=="string"&&t.toLowerCase().includes(r.toLowerCase())||typeof t=="number"&&String(t).includes(r)),c=y=>{y.stopPropagation(),p&&g(s)},h=p?Object.entries(t):[];return e.jsxs("div",{style:{marginLeft:o>0?"16px":"0"},children:[e.jsxs("div",{className:`g7dt-tree-node g7dt-flex g7dt-items-center g7dt-gap-1 ${f?"g7dt-ring-highlight":""}`,onClick:c,children:[p?e.jsx("span",{className:"g7dt-text-gray g7dt-w-4 g7dt-text-xs g7dt-select-none",style:{textAlign:"center"},children:v?"▼":"▶"}):e.jsx("span",{className:"g7dt-w-4"}),e.jsx("span",{className:"g7dt-text-purple g7dt-text-xs",children:d}),e.jsx("span",{className:"g7dt-text-gray-dark g7dt-text-xs",children:":"}),p?e.jsxs("span",{className:`g7dt-text-xs ${te(t)}`,children:[l?"[":"{",!v&&e.jsx("span",{className:"g7dt-text-gray",style:{margin:"0 4px"},children:ye(t)}),!v&&(l?"]":"}")]}):e.jsx("span",{className:`g7dt-text-xs ${te(t)}`,children:we(t)}),!p&&e.jsxs("span",{className:"g7dt-text-gray-dark g7dt-text-xs g7dt-ml-1",children:["(",typeof t,")"]})]}),p&&v&&e.jsxs("div",{className:"g7dt-border-l",style:{marginLeft:"8px"},children:[h.map(([y,n])=>e.jsx(W,{keyName:l?`[${y}]`:y,value:n,path:`${s}.${y}`,expandedPaths:a,onToggle:g,searchTerm:r,depth:o+1},`${s}.${y}`)),e.jsx("div",{className:"g7dt-ml-4 g7dt-text-xs",children:e.jsx("span",{className:te(t),children:l?"]":"}"})})]})]})},ke=({state:d,devTools:t})=>{const[s,a]=x.useState(new Set(["_global","_local","_computed","_isolated","$parent"])),[g,r]=x.useState(""),[o,p]=x.useState(!1),[v,l]=x.useState(!1),[f,c]=x.useState(null),h=x.useCallback(()=>{t&&c(t.getComputedDependencyTrackingInfo())},[t]);x.useEffect(()=>{if(v&&t){h();const w=setInterval(h,2e3);return()=>clearInterval(w)}},[v,t,h]);const y=w=>{switch(w){case"state-change":return"📊";case"prop-change":return"📥";case"dependency-change":return"🔗";case"manual":return"👆";case"initial":return"🚀";default:return"❓"}},n=x.useCallback(w=>{a(S=>{const z=new Set(S);return z.has(w)?z.delete(w):z.add(w),z})},[]),i=x.useCallback((w,S)=>{const z=[S];if(w!==null&&typeof w=="object")for(const[O,K]of Object.entries(w))z.push(...i(K,`${S}.${O}`));return z},[]),u=x.useCallback(()=>{if(o)a(new Set(["_global","_local","_computed","_isolated","$parent"]));else{const w=new Set;i(d._global,"_global").forEach(S=>w.add(S)),i(d._local,"_local").forEach(S=>w.add(S)),i(d._computed,"_computed").forEach(S=>w.add(S)),i(d._isolated,"_isolated").forEach(S=>w.add(S)),d.$parent&&i(d.$parent,"$parent").forEach(S=>w.add(S)),a(w)}p(!o)},[o,d,i]),m=Object.keys(d._global||{}).length,k=Object.keys(d._local||{}).length,b=Object.keys(d._computed||{}).length,N=Object.keys(d._isolated||{}).length,C=Object.keys(d.$parent||{}).length;return e.jsxs("div",{className:"g7dt-space-y-4",children:[e.jsxs("div",{className:"g7dt-flex g7dt-gap-2 g7dt-items-center g7dt-flex-shrink-0",children:[e.jsx("input",{type:"text",placeholder:"키 또는 값 검색...",value:g,onChange:w=>r(w.target.value),className:"g7dt-input g7dt-flex-1"}),e.jsx("button",{onClick:u,className:"g7dt-btn g7dt-bg-gray-700",children:o?"모두 접기":"모두 펼치기"})]}),e.jsxs("div",{className:"g7dt-flex g7dt-gap-3 g7dt-text-xs g7dt-text-gray g7dt-flex-wrap g7dt-flex-shrink-0",children:[e.jsxs("span",{children:[e.jsx("span",{className:"g7dt-text-yellow",children:"●"})," string"]}),e.jsxs("span",{children:[e.jsx("span",{className:"g7dt-text-cyan",children:"●"})," number"]}),e.jsxs("span",{children:[e.jsx("span",{className:"g7dt-text-pink",children:"●"})," boolean"]}),e.jsxs("span",{children:[e.jsx("span",{className:"g7dt-text-gray",children:"●"})," null"]}),e.jsxs("span",{children:[e.jsx("span",{className:"g7dt-text-orange",children:"●"})," array"]}),e.jsxs("span",{children:[e.jsx("span",{className:"g7dt-text-blue",children:"●"})," object"]})]}),e.jsxs("div",{className:"g7dt-bg-gray-800 g7dt-rounded g7dt-p-2 g7dt-overflow-auto g7dt-border",style:{flex:1,minHeight:0},children:[e.jsxs("div",{className:"g7dt-mb-2",children:[e.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2 g7dt-text-sm g7dt-font-bold g7dt-text-green g7dt-mb-1 g7dt-cursor-pointer",onClick:()=>n("_global"),children:[e.jsx("span",{children:s.has("_global")?"▼":"▶"}),e.jsx("span",{children:"_global"}),e.jsxs("span",{className:"g7dt-text-gray g7dt-text-xs",style:{fontWeight:"normal"},children:["(",m,"개 키)"]})]}),s.has("_global")&&e.jsx("div",{className:"g7dt-ml-2 g7dt-border-l",children:Object.entries(d._global||{}).map(([w,S])=>e.jsx(W,{keyName:w,value:S,path:`_global.${w}`,expandedPaths:s,onToggle:n,searchTerm:g},`_global.${w}`))})]}),e.jsxs("div",{className:"g7dt-mb-2",children:[e.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2 g7dt-text-sm g7dt-font-bold g7dt-text-blue g7dt-mb-1 g7dt-cursor-pointer",onClick:()=>n("_local"),children:[e.jsx("span",{children:s.has("_local")?"▼":"▶"}),e.jsx("span",{children:"_local"}),e.jsxs("span",{className:"g7dt-text-gray g7dt-text-xs",style:{fontWeight:"normal"},children:["(",k,"개 키)"]})]}),s.has("_local")&&e.jsx("div",{className:"g7dt-ml-2 g7dt-border-l",children:Object.entries(d._local||{}).map(([w,S])=>e.jsx(W,{keyName:w,value:S,path:`_local.${w}`,expandedPaths:s,onToggle:n,searchTerm:g},`_local.${w}`))})]}),e.jsxs("div",{className:"g7dt-mb-2",children:[e.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2 g7dt-text-sm g7dt-font-bold g7dt-text-purple g7dt-mb-1 g7dt-cursor-pointer",onClick:()=>n("_computed"),children:[e.jsx("span",{children:s.has("_computed")?"▼":"▶"}),e.jsx("span",{children:"_computed"}),e.jsxs("span",{className:"g7dt-text-gray g7dt-text-xs",style:{fontWeight:"normal"},children:["(",b,"개 키)"]})]}),s.has("_computed")&&e.jsx("div",{className:"g7dt-ml-2 g7dt-border-l",children:Object.entries(d._computed||{}).map(([w,S])=>e.jsx(W,{keyName:w,value:S,path:`_computed.${w}`,expandedPaths:s,onToggle:n,searchTerm:g},`_computed.${w}`))})]}),N>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2 g7dt-text-sm g7dt-font-bold g7dt-text-orange g7dt-mb-1 g7dt-cursor-pointer",onClick:()=>n("_isolated"),children:[e.jsx("span",{children:s.has("_isolated")?"▼":"▶"}),e.jsx("span",{children:"_isolated"}),e.jsxs("span",{className:"g7dt-text-gray g7dt-text-xs",style:{fontWeight:"normal"},children:["(",N,"개 스코프)"]})]}),s.has("_isolated")&&e.jsx("div",{className:"g7dt-ml-2 g7dt-border-l",children:Object.entries(d._isolated||{}).map(([w,S])=>e.jsx(W,{keyName:w,value:S,path:`_isolated.${w}`,expandedPaths:s,onToggle:n,searchTerm:g},`_isolated.${w}`))})]}),C>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2 g7dt-text-sm g7dt-font-bold g7dt-text-cyan g7dt-mb-1 g7dt-cursor-pointer",onClick:()=>n("$parent"),children:[e.jsx("span",{children:s.has("$parent")?"▼":"▶"}),e.jsx("span",{children:"$parent"}),e.jsxs("span",{className:"g7dt-text-gray g7dt-text-xs",style:{fontWeight:"normal"},children:["(",C,"개 키)"]})]}),s.has("$parent")&&e.jsx("div",{className:"g7dt-ml-2 g7dt-border-l",children:Object.entries(d.$parent||{}).map(([w,S])=>e.jsx(W,{keyName:w,value:S,path:`$parent.${w}`,expandedPaths:s,onToggle:n,searchTerm:g},`$parent.${w}`))})]})]}),t&&e.jsx("div",{className:"g7dt-flex g7dt-justify-end g7dt-mt-2",children:e.jsx("button",{onClick:()=>l(!v),className:`g7dt-tab-button ${v?"g7dt-tab-active":""}`,children:"🧮 Computed 추적"})}),v&&f&&e.jsxs("div",{className:"g7dt-card g7dt-mt-2",children:[e.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:["Computed 의존성 추적 (",f.properties.length,"개)"]}),e.jsxs("div",{className:"g7dt-stats-grid g7dt-mb-3",children:[e.jsxs("div",{className:"g7dt-stat-card",children:[e.jsx("div",{className:"g7dt-stat-value g7dt-text-purple",children:f.stats.totalComputed}),e.jsx("div",{className:"g7dt-stat-label",children:"Computed"})]}),e.jsxs("div",{className:"g7dt-stat-card",children:[e.jsx("div",{className:"g7dt-stat-value g7dt-text-blue",children:f.stats.totalRecalculations}),e.jsx("div",{className:"g7dt-stat-label",children:"재계산"})]}),e.jsxs("div",{className:"g7dt-stat-card",children:[e.jsx("div",{className:"g7dt-stat-value g7dt-text-yellow",children:f.stats.unnecessaryRecalculations}),e.jsx("div",{className:"g7dt-stat-label",children:"불필요"})]}),e.jsxs("div",{className:"g7dt-stat-card",children:[e.jsxs("div",{className:"g7dt-stat-value g7dt-text-green",children:[f.stats.avgComputationTime.toFixed(1),"ms"]}),e.jsx("div",{className:"g7dt-stat-label",children:"평균시간"})]})]}),f.stats.cycleDetectionCount>0&&e.jsxs("div",{className:"g7dt-text-xs g7dt-text-red g7dt-mb-3 g7dt-p-2 g7dt-bg-red-900 g7dt-rounded",children:["⚠️ 순환 의존성 감지: ",f.stats.cycleDetectionCount,"건"]}),f.stats.topRecalculated.length>0&&e.jsxs("div",{className:"g7dt-mb-3",children:[e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mb-2",children:"자주 재계산되는 속성"}),e.jsx("div",{className:"g7dt-space-y-1",children:f.stats.topRecalculated.slice(0,3).map((w,S)=>e.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-text-xs",children:[e.jsx("span",{className:"g7dt-text-purple g7dt-font-mono",children:w.name}),e.jsxs("span",{className:"g7dt-text-muted",children:[w.count,"회"]})]},S))})]}),f.recalcLogs.length===0?e.jsx("div",{className:"g7dt-empty-state",children:"재계산 로그가 없습니다"}):e.jsx("div",{className:"g7dt-space-y-2 g7dt-max-h-40 g7dt-overflow-y-auto",children:f.recalcLogs.slice().reverse().slice(0,20).map(w=>e.jsxs("div",{className:`g7dt-list-item ${w.valueChanged?"":"g7dt-border-yellow"}`,children:[e.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[e.jsx("span",{children:y(w.trigger)}),e.jsx("span",{className:"g7dt-text-xs g7dt-text-purple g7dt-font-mono",children:w.computedName}),!w.valueChanged&&e.jsx("span",{className:"g7dt-badge g7dt-text-xs g7dt-text-yellow",children:"값 변경 없음"}),e.jsxs("span",{className:"g7dt-text-xs g7dt-text-muted g7dt-ml-auto",children:[w.computationTime.toFixed(1),"ms"]})]}),w.triggeredBy&&e.jsxs("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mt-1",children:["트리거: ",e.jsx("span",{className:"g7dt-text-blue",children:w.triggeredBy.path})]})]},w.id))})]})]})},Ce=({actions:d,devTools:t})=>{const[s,a]=x.useState(""),[g,r]=x.useState("actions"),[o,p]=x.useState(null),[v,l]=x.useState(null),f=x.useCallback(()=>{t&&p(t.getSequenceTrackingInfo())},[t]);x.useEffect(()=>{if(g==="sequences"&&t){f();const i=setInterval(f,2e3);return()=>clearInterval(i)}},[g,t,f]);const c=s?d.filter(i=>i.type.toLowerCase().includes(s.toLowerCase())||i.status===s):d,h=i=>{switch(i){case"success":return"g7dt-status-success";case"error":return"g7dt-status-error";case"started":return"g7dt-status-started";default:return"g7dt-status-default"}},y=i=>{switch(i){case"success":return"g7dt-badge-success";case"error":return"g7dt-badge-error";default:return"g7dt-badge-warning"}},n=v&&o?o.executions.find(i=>i.id===v):null;return e.jsxs("div",{className:"g7dt-space-y-4",children:[t&&e.jsx("div",{className:"g7dt-card",children:e.jsxs("div",{className:"g7dt-flex g7dt-gap-2",children:[e.jsxs("button",{className:`g7dt-tab-button ${g==="actions"?"g7dt-tab-active":""}`,onClick:()=>r("actions"),children:["📋 액션 (",d.length,")"]}),e.jsxs("button",{className:`g7dt-tab-button ${g==="sequences"?"g7dt-tab-active":""}`,onClick:()=>r("sequences"),children:["🔗 Sequence (",o?.executions.length||0,")"]})]})}),g==="actions"&&e.jsxs("div",{className:"g7dt-flex g7dt-gap-2 g7dt-flex-shrink-0",children:[e.jsx("input",{type:"text",placeholder:"액션 타입 또는 상태로 필터...",value:s,onChange:i=>a(i.target.value),className:"g7dt-input g7dt-flex-1"}),e.jsx("button",{onClick:()=>a(""),className:"g7dt-btn-text",children:"초기화"})]}),g==="sequences"&&o&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"g7dt-card",children:[e.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"Sequence 통계"}),e.jsxs("div",{className:"g7dt-stats-grid-3",children:[e.jsxs("div",{className:"g7dt-text-center",children:[e.jsx("div",{className:"g7dt-text-2xl g7dt-font-bold g7dt-text-blue",children:o.stats.totalSequences}),e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"총 실행"})]}),e.jsxs("div",{className:"g7dt-text-center",children:[e.jsx("div",{className:"g7dt-text-2xl g7dt-font-bold g7dt-text-green",children:o.stats.successCount}),e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"성공"})]}),e.jsxs("div",{className:"g7dt-text-center",children:[e.jsx("div",{className:"g7dt-text-2xl g7dt-font-bold g7dt-text-red",children:o.stats.errorCount}),e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"실패"})]})]})]}),e.jsxs("div",{className:"g7dt-card",children:[e.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"Sequence 실행 목록"}),o.executions.length===0?e.jsx("div",{className:"g7dt-empty-state",children:"실행된 Sequence가 없습니다"}):e.jsx("div",{className:"g7dt-space-y-2 g7dt-max-h-40 g7dt-overflow-y-auto",children:o.executions.slice().reverse().map(i=>e.jsx("div",{className:`g7dt-list-item g7dt-cursor-pointer ${v===i.id?"g7dt-selected":""} ${i.status==="error"?"g7dt-border-red":""}`,onClick:()=>l(v===i.id?null:i.id),children:e.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[e.jsx("span",{children:i.status==="completed"?"✅":i.status==="error"?"❌":"⏳"}),e.jsxs("span",{className:"g7dt-text-xs g7dt-text-white",children:[i.actions.length,"개 액션"]}),e.jsxs("span",{className:"g7dt-text-xs g7dt-text-muted g7dt-ml-auto",children:[i.totalDuration.toFixed(0),"ms"]})]})},i.id))})]}),n&&e.jsxs("div",{className:"g7dt-card g7dt-border-blue",children:[e.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:["🔗 Sequence 상세 (",n.actions.length,"개 액션)"]}),e.jsx("div",{className:"g7dt-space-y-2 g7dt-max-h-60 g7dt-overflow-y-auto",children:n.actions.map((i,u)=>e.jsxs("div",{className:`g7dt-list-item ${i.status==="error"?"g7dt-border-red":""}`,children:[e.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[e.jsxs("span",{className:"g7dt-text-xs g7dt-text-muted",children:["#",i.index+1]}),e.jsx("span",{className:"g7dt-text-xs g7dt-text-white g7dt-font-mono",children:i.handler}),e.jsx("span",{className:`g7dt-text-xs ${i.status==="success"?"g7dt-text-green":"g7dt-text-red"}`,children:i.status==="success"?"✓":"✕"}),e.jsxs("span",{className:"g7dt-text-xs g7dt-text-muted g7dt-ml-auto",children:[i.duration.toFixed(0),"ms"]})]}),i.stateChanges&&i.stateChanges.length>0&&e.jsxs("div",{className:"g7dt-mt-1",children:[e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"상태 변경:"}),i.stateChanges.slice(0,3).map((m,k)=>e.jsx("div",{className:"g7dt-text-xs g7dt-text-yellow g7dt-ml-2",children:m.path},k)),i.stateChanges.length>3&&e.jsxs("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-ml-2",children:["...외 ",i.stateChanges.length-3,"개"]})]})]},u))})]})]}),g==="actions"&&e.jsx("div",{className:"g7dt-section",children:e.jsx("div",{className:"g7dt-scroll-list g7dt-space-y-2-flat g7dt-action-list",children:c.length===0?e.jsx("div",{className:"g7dt-empty-message",children:"액션 이력이 없습니다"}):c.slice(-30).reverse().map((i,u)=>e.jsxs("div",{className:`g7dt-action-item ${h(i.status)}`,children:[e.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-start",children:[e.jsxs("div",{children:[e.jsx("span",{className:"g7dt-font-mono g7dt-font-bold",children:i.type}),e.jsx("span",{className:`g7dt-status-badge ${y(i.status)}`,children:i.status})]}),e.jsx("span",{className:"g7dt-text-gray",children:i.duration?`${i.duration.toFixed(2)}ms`:"-"})]}),i.error&&e.jsx("div",{className:"g7dt-error-box",children:i.error.message}),i.params&&Object.keys(i.params).length>0&&e.jsxs("details",{className:"g7dt-details",children:[e.jsx("summary",{className:"g7dt-summary",children:"파라미터"}),e.jsx("pre",{className:"g7dt-pre",children:JSON.stringify(i.params,null,2)})]})]},`${i.id}-${u}`))})})]})},Se=({stats:d,devTools:t})=>{const[s,a]=x.useState(null),[g,r]=x.useState(!1),o=x.useCallback(()=>{a(t.getCacheDecisionTrackingInfo())},[t]);x.useEffect(()=>{if(g){o();const l=setInterval(o,2e3);return()=>clearInterval(l)}},[g,o]);const p=()=>{t.resetCacheStats(),console.log("[G7DevTools] 캐시 통계 초기화")},v=l=>{switch(l){case"use_cache":return"✅";case"skip_cache":return"⏭️";case"invalidate":return"🗑️";default:return"❓"}};return e.jsxs("div",{className:"g7dt-space-y-6",children:[e.jsxs("div",{className:"g7dt-stats-grid",children:[e.jsxs("div",{className:"g7dt-stat-card",children:[e.jsx("div",{className:"g7dt-stat-value g7dt-text-green",children:d.hits}),e.jsx("div",{className:"g7dt-stat-label",children:"Cache Hits"})]}),e.jsxs("div",{className:"g7dt-stat-card",children:[e.jsx("div",{className:"g7dt-stat-value g7dt-text-red",children:d.misses}),e.jsx("div",{className:"g7dt-stat-label",children:"Cache Misses"})]}),e.jsxs("div",{className:"g7dt-stat-card",children:[e.jsx("div",{className:"g7dt-stat-value g7dt-text-blue",children:d.entries}),e.jsx("div",{className:"g7dt-stat-label",children:"Entries"})]}),e.jsxs("div",{className:"g7dt-stat-card",children:[e.jsxs("div",{className:"g7dt-stat-value g7dt-text-purple",children:[(d.hitRate*100).toFixed(1),"%"]}),e.jsx("div",{className:"g7dt-stat-label",children:"Hit Rate"})]})]}),e.jsxs("div",{className:"g7dt-space-y-2",children:[e.jsx("div",{className:"g7dt-text-sm g7dt-text-gray",children:"캐시 히트율"}),e.jsx("div",{className:"g7dt-progress-bar",children:e.jsx("div",{className:"g7dt-progress-fill",style:{width:`${d.hitRate*100}%`}})})]}),e.jsxs("div",{className:"g7dt-flex g7dt-gap-2",children:[e.jsx("button",{onClick:p,className:"g7dt-btn-danger",children:"캐시 통계 초기화"}),e.jsx("button",{onClick:()=>r(!g),className:`g7dt-tab-button ${g?"g7dt-tab-active":""}`,children:"📋 Decision Log"})]}),g&&s&&e.jsxs("div",{className:"g7dt-card",children:[e.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:["캐시 결정 로그 (",s.decisions.length,"개)"]}),s.decisions.length===0?e.jsx("div",{className:"g7dt-empty-state",children:"캐시 결정 기록이 없습니다"}):e.jsx("div",{className:"g7dt-space-y-2 g7dt-max-h-60 g7dt-overflow-y-auto",children:s.decisions.slice().reverse().slice(0,50).map(l=>e.jsxs("div",{className:`g7dt-list-item ${l.decision==="skip_cache"?"g7dt-border-yellow":l.decision==="invalidate"?"g7dt-border-red":""}`,children:[e.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[e.jsx("span",{children:v(l.decision)}),e.jsx("span",{className:"g7dt-text-xs g7dt-text-white g7dt-font-mono g7dt-truncate",style:{maxWidth:"200px"},children:l.expression}),e.jsx("span",{className:"g7dt-text-xs g7dt-text-muted g7dt-ml-auto",children:l.decision})]}),e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mt-1",children:l.reason}),l.context&&e.jsxs("div",{className:"g7dt-flex g7dt-gap-2 g7dt-mt-1",children:[l.context.isInIteration&&e.jsx("span",{className:"g7dt-badge g7dt-text-xs",children:"🔄 iteration"}),l.context.isInAction&&e.jsx("span",{className:"g7dt-badge g7dt-text-xs",children:"⚡ action"})]})]},l.id))})]})]})},Ie=()=>{const[d,t]=x.useState([]),[s,a]=x.useState([]),[g,r]=x.useState(""),o=["이전 값이 전송됨","모든 행이 같은 값","상태가 업데이트 안됨","API 호출이 안됨","초기값이 없음","무한 로딩","Form 값이 저장 안됨","iteration 데이터 중복"],p=f=>{t(c=>c.includes(f)?c.filter(h=>h!==f):[...c,f])},v=()=>{g&&!d.includes(g)&&(t(f=>[...f,g]),r(""))},l=async()=>{const{DiagnosticEngine:f}=await Promise.resolve().then(()=>pe),h=new f().analyze(d);a(h)};return e.jsxs("div",{className:"g7dt-space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-2",children:"증상 선택"}),e.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-2",children:o.map(f=>e.jsx("button",{onClick:()=>p(f),className:d.includes(f)?"g7dt-symptom-btn g7dt-symptom-active":"g7dt-symptom-btn",children:f},f))})]}),e.jsxs("div",{className:"g7dt-flex g7dt-gap-2",children:[e.jsx("input",{type:"text",placeholder:"직접 증상 입력...",value:g,onChange:f=>r(f.target.value),onKeyDown:f=>f.key==="Enter"&&v(),className:"g7dt-input g7dt-flex-1"}),e.jsx("button",{onClick:v,className:"g7dt-btn-secondary",children:"추가"})]}),e.jsxs("button",{onClick:l,disabled:d.length===0,className:d.length===0?"g7dt-btn-primary g7dt-btn-disabled g7dt-w-full":"g7dt-btn-primary g7dt-w-full",children:["진단 실행 (",d.length,"개 증상)"]}),s.length>0&&e.jsxs("div",{className:"g7dt-space-y-3",children:[e.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold",children:"진단 결과"}),s.slice(0,5).map((f,c)=>e.jsxs("div",{className:"g7dt-card",children:[e.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2",children:[e.jsx("span",{className:"g7dt-font-bold g7dt-text-yellow",children:f.rule.name}),e.jsxs("span",{className:"g7dt-confidence-badge",children:[(f.confidence*100).toFixed(0),"%"]})]}),e.jsx("div",{className:"g7dt-text-sm g7dt-text-lightgray",children:f.rule.solution}),f.rule.codeExample&&e.jsx("pre",{className:"g7dt-pre g7dt-mt-2",children:f.rule.codeExample})]},c))]})]})},Te=({devTools:d})=>{const t=d.getPerformanceInfo();return e.jsxs("div",{className:"g7dt-space-y-4",children:[e.jsxs("div",{className:"g7dt-stats-grid-2",children:[e.jsxs("div",{className:"g7dt-stat-card",children:[e.jsx("div",{className:"g7dt-stat-value g7dt-text-blue",children:t.bindingEvalCount}),e.jsx("div",{className:"g7dt-stat-label",children:"바인딩 평가 횟수"})]}),e.jsxs("div",{className:"g7dt-stat-card",children:[e.jsx("div",{className:"g7dt-stat-value g7dt-text-purple",children:t.renderCounts.size}),e.jsx("div",{className:"g7dt-stat-label",children:"렌더링된 컴포넌트"})]})]}),t.memoryWarnings.length>0&&e.jsxs("div",{children:[e.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-text-red g7dt-mb-2",children:"메모리 경고"}),e.jsx("div",{className:"g7dt-space-y-2",children:t.memoryWarnings.map((s,a)=>e.jsxs("div",{className:"g7dt-warning-card",children:[e.jsx("div",{className:"g7dt-font-bold",children:s.type}),e.jsx("div",{className:"g7dt-text-lightgray",children:s.message}),e.jsx("div",{className:"g7dt-text-xs g7dt-text-gray g7dt-mt-1",children:s.suggestion})]},a))})]}),t.renderCounts.size>0&&e.jsxs("div",{children:[e.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-2",children:"컴포넌트별 렌더링"}),e.jsx("div",{className:"g7dt-space-y-1 g7dt-scroll-list",children:Array.from(t.renderCounts.entries()).sort((s,a)=>a[1]-s[1]).slice(0,10).map(([s,a])=>e.jsxs("div",{className:"g7dt-list-item",children:[e.jsx("span",{className:"g7dt-text-lightgray g7dt-truncate",children:s}),e.jsxs("span",{className:a>50?"g7dt-text-red":"g7dt-text-gray",children:[a,"회"]})]},s))})]})]})},De=({devTools:d})=>{const t=d.getLifecycleInfo();return e.jsxs("div",{className:"g7dt-space-y-4",children:[e.jsxs("div",{className:"g7dt-section",children:[e.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-text-green g7dt-mb-2 g7dt-flex-shrink-0",children:["마운트된 컴포넌트 (",t.mountedComponents.length,")"]}),e.jsx("div",{className:"g7dt-scroll-list",children:t.mountedComponents.length===0?e.jsx("div",{className:"g7dt-empty-message",children:"추적된 컴포넌트 없음"}):t.mountedComponents.map(s=>e.jsxs("div",{className:"g7dt-list-item g7dt-text-xs",children:[e.jsx("span",{className:"g7dt-text-lightgray",children:s.name}),e.jsx("span",{className:"g7dt-text-gray",children:s.id})]},s.id))})]}),t.orphanedListeners.length>0&&e.jsxs("div",{className:"g7dt-section",children:[e.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-text-red g7dt-mb-2 g7dt-flex-shrink-0",children:["정리되지 않은 리스너 (",t.orphanedListeners.length,")"]}),e.jsx("div",{className:"g7dt-scroll-list",children:t.orphanedListeners.map((s,a)=>e.jsxs("div",{className:"g7dt-warning-card g7dt-text-xs",children:[e.jsx("span",{className:"g7dt-text-lightgray",children:s.type}),e.jsxs("span",{className:"g7dt-text-gray g7dt-ml-2",children:["on ",s.target]})]},a))})]})]})},Le=({devTools:d})=>{const t=d.getNetworkInfo(),s=o=>{switch(o){case"success":return"g7dt-text-green";case"error":return"g7dt-text-red";case"pending":return"g7dt-text-yellow";default:return"g7dt-text-gray"}},a=o=>o.queryParams&&Object.keys(o.queryParams).length>0,g=o=>Object.entries(o).map(([p,v])=>e.jsxs("div",{className:"g7dt-flex g7dt-gap-2 g7dt-text-xs",children:[e.jsxs("span",{className:"g7dt-text-purple",children:[p,":"]}),e.jsx("span",{className:"g7dt-text-lightgray",children:Array.isArray(v)?JSON.stringify(v):v})]},p)),r=(o,p=5e3)=>{try{const v=JSON.stringify(o,null,2);return v.length>p?v.substring(0,p)+` ... (truncated)`:v}catch{return"(직렬화 불가)"}};return e.jsxs("div",{className:"g7dt-space-y-4",children:[t.activeRequests.length>0&&e.jsxs("div",{children:[e.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-text-yellow g7dt-mb-2",children:["진행 중 (",t.activeRequests.length,")"]}),e.jsx("div",{className:"g7dt-space-y-1",children:t.activeRequests.map(o=>e.jsxs("details",{className:"g7dt-details",children:[e.jsxs("summary",{className:"g7dt-summary g7dt-pending-request",children:[e.jsx("span",{className:"g7dt-font-bold",children:o.method}),e.jsx("span",{className:"g7dt-ml-2 g7dt-text-lightgray g7dt-truncate",children:o.fullUrl||o.url})]}),e.jsxs("div",{className:"g7dt-card g7dt-mt-1 g7dt-text-xs",children:[a(o)&&e.jsxs("div",{className:"g7dt-mb-2",children:[e.jsx("div",{className:"g7dt-text-blue g7dt-font-bold g7dt-mb-1",children:"쿼리 파라미터"}),e.jsx("div",{className:"g7dt-pl-2 g7dt-border-l-2 g7dt-border-blue",children:g(o.queryParams)})]}),o.requestBody&&e.jsxs("div",{children:[e.jsx("div",{className:"g7dt-text-orange g7dt-font-bold g7dt-mb-1",children:"요청 본문"}),e.jsx("pre",{className:"g7dt-pre g7dt-text-xs",children:r(o.requestBody,2e3)})]})]})]},o.id))})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-2",children:"요청 이력"}),e.jsx("div",{className:"g7dt-space-y-1 g7dt-scroll-list-lg",children:t.requestHistory.length===0?e.jsx("div",{className:"g7dt-empty-message",children:"요청 이력 없음"}):t.requestHistory.slice(-20).reverse().map(o=>e.jsxs("details",{className:"g7dt-details",children:[e.jsxs("summary",{className:"g7dt-summary g7dt-card g7dt-text-xs",children:[e.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center g7dt-w-full",children:[e.jsxs("div",{children:[e.jsx("span",{className:"g7dt-font-bold",children:o.method}),e.jsx("span",{className:`g7dt-ml-2 ${s(o.status)}`,children:o.statusCode||o.status})]}),e.jsxs("span",{className:"g7dt-text-gray",children:[o.duration,"ms"]})]}),e.jsx("div",{className:"g7dt-text-gray g7dt-truncate g7dt-mt-1",children:o.fullUrl||o.url})]}),e.jsxs("div",{className:"g7dt-card g7dt-mt-1 g7dt-text-xs g7dt-ml-2 g7dt-border-l-2 g7dt-border-gray",children:[e.jsx("div",{className:"g7dt-mb-2",children:e.jsxs("div",{className:"g7dt-text-xs g7dt-space-y-1",children:[e.jsxs("div",{children:[e.jsx("span",{className:"g7dt-text-gray",children:"URL:"})," ",e.jsx("span",{className:"g7dt-text-lightgray",children:o.fullUrl||o.url})]}),e.jsxs("div",{children:[e.jsx("span",{className:"g7dt-text-gray",children:"상태:"})," ",e.jsx("span",{className:s(o.status),children:o.statusCode||o.status})]}),e.jsxs("div",{children:[e.jsx("span",{className:"g7dt-text-gray",children:"소요시간:"})," ",e.jsxs("span",{className:"g7dt-text-lightgray",children:[o.duration,"ms"]})]}),o.dataSourceId&&e.jsxs("div",{children:[e.jsx("span",{className:"g7dt-text-gray",children:"데이터소스:"})," ",e.jsx("span",{className:"g7dt-text-blue",children:o.dataSourceId})]}),o.error&&e.jsxs("div",{children:[e.jsx("span",{className:"g7dt-text-gray",children:"에러:"})," ",e.jsx("span",{className:"g7dt-text-red",children:o.error})]})]})}),a(o)&&e.jsxs("div",{className:"g7dt-mb-2",children:[e.jsx("div",{className:"g7dt-text-blue g7dt-font-bold g7dt-mb-1",children:"쿼리 파라미터"}),e.jsx("div",{className:"g7dt-pl-2 g7dt-border-l-2 g7dt-border-blue",children:g(o.queryParams)})]}),o.requestBody&&e.jsxs("div",{className:"g7dt-mb-2",children:[e.jsx("div",{className:"g7dt-text-orange g7dt-font-bold g7dt-mb-1",children:"요청 본문"}),e.jsx("pre",{className:"g7dt-pre g7dt-text-xs g7dt-max-h-40 g7dt-overflow-auto",children:r(o.requestBody,2e3)})]}),o.response!==void 0&&e.jsxs("div",{children:[e.jsx("div",{className:"g7dt-text-green g7dt-font-bold g7dt-mb-1",children:"응답 내용"}),e.jsx("pre",{className:"g7dt-pre g7dt-text-xs g7dt-max-h-60 g7dt-overflow-auto",children:r(o.response,5e3)})]})]})]},o.id))})]}),t.pendingDataSources.length>0&&e.jsxs("div",{children:[e.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-text-blue g7dt-mb-2",children:["대기 중인 데이터소스 (",t.pendingDataSources.length,")"]}),e.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-2",children:t.pendingDataSources.map(o=>e.jsx("span",{className:"g7dt-tag-blue",children:o},o))})]})]})},Ee=({devTools:d})=>{const t=d.getFormInfo(),[s,a]=x.useState(!1),[g,r]=x.useState(null),o=x.useCallback(()=>{r(d.getFormBindingValidationTrackingInfo())},[d]);x.useEffect(()=>{if(s){o();const l=setInterval(o,2e3);return()=>clearInterval(l)}},[s,o]);const p=l=>{switch(l){case"missing-datakey":return"🔑";case"missing-input-name":return"📝";case"context-not-propagated":return"🔗";case"sortable-context-break":return"📊";case"modal-context-isolation":return"🪟";case"duplicate-input-name":return"👯";case"value-type-mismatch":return"⚠️";case"binding-path-invalid":return"❌";default:return"❓"}},v=l=>{switch(l){case"error":return"g7dt-text-red";case"warning":return"g7dt-text-yellow";case"info":return"g7dt-text-blue";default:return"g7dt-text-gray"}};return e.jsxs("div",{className:"g7dt-space-y-4",children:[t.length===0?e.jsx("div",{className:"g7dt-empty-message g7dt-py-8",children:"추적된 Form이 없습니다"}):t.map(l=>e.jsxs("div",{className:"g7dt-card",children:[e.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2",children:[e.jsx("span",{className:"g7dt-font-bold g7dt-text-blue",children:l.dataKey||"(no dataKey)"}),!l.dataKey&&e.jsx("span",{className:"g7dt-text-red g7dt-text-xs",children:"dataKey 필요"})]}),e.jsx("div",{className:"g7dt-space-y-1 g7dt-mb-2",children:l.inputs.map((f,c)=>e.jsxs("div",{className:"g7dt-text-xs g7dt-flex g7dt-justify-between",children:[e.jsx("span",{children:f.name||e.jsx("span",{className:"g7dt-text-red",children:"name 없음"})}),e.jsx("span",{className:"g7dt-text-gray",children:f.type})]},c))}),e.jsxs("details",{className:"g7dt-details",children:[e.jsx("summary",{className:"g7dt-summary",children:"현재 값 보기"}),e.jsx("pre",{className:"g7dt-pre",children:JSON.stringify(l,null,2)})]})]},l.id)),e.jsx("div",{className:"g7dt-flex g7dt-justify-end",children:e.jsx("button",{onClick:()=>a(!s),className:`g7dt-tab-button ${s?"g7dt-tab-active":""}`,children:"🔍 Auto-Binding Check"})}),s&&g&&e.jsxs("div",{className:"g7dt-card",children:[e.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"Form 바인딩 검증 결과"}),e.jsxs("div",{className:"g7dt-stats-grid g7dt-mb-3",children:[e.jsxs("div",{className:"g7dt-stat-card",children:[e.jsx("div",{className:"g7dt-stat-value g7dt-text-blue",children:g.stats.totalFormsValidated}),e.jsx("div",{className:"g7dt-stat-label",children:"검증된 Form"})]}),e.jsxs("div",{className:"g7dt-stat-card",children:[e.jsx("div",{className:"g7dt-stat-value g7dt-text-green",children:g.stats.validForms}),e.jsx("div",{className:"g7dt-stat-label",children:"유효"})]}),e.jsxs("div",{className:"g7dt-stat-card",children:[e.jsx("div",{className:"g7dt-stat-value g7dt-text-red",children:g.stats.formsWithIssues}),e.jsx("div",{className:"g7dt-stat-label",children:"문제 있음"})]}),e.jsxs("div",{className:"g7dt-stat-card",children:[e.jsx("div",{className:"g7dt-stat-value g7dt-text-yellow",children:g.stats.totalIssues}),e.jsx("div",{className:"g7dt-stat-label",children:"총 이슈"})]})]}),g.stats.topIssues.length>0&&e.jsxs("div",{className:"g7dt-mb-3",children:[e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mb-2",children:"자주 발생하는 이슈"}),e.jsx("div",{className:"g7dt-space-y-1",children:g.stats.topIssues.slice(0,3).map((l,f)=>e.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2 g7dt-text-xs",children:[e.jsx("span",{children:p(l.type)}),e.jsx("span",{className:"g7dt-text-white",children:l.description}),e.jsxs("span",{className:"g7dt-text-muted",children:["(",l.count,")"]})]},f))})]}),g.issues.length===0?e.jsx("div",{className:"g7dt-empty-state",children:"바인딩 이슈가 없습니다 ✅"}):e.jsx("div",{className:"g7dt-space-y-2 g7dt-max-h-60 g7dt-overflow-y-auto",children:g.issues.slice().reverse().slice(0,30).map(l=>e.jsxs("div",{className:`g7dt-list-item ${l.severity==="error"?"g7dt-border-red":l.severity==="warning"?"g7dt-border-yellow":""}`,children:[e.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[e.jsx("span",{children:p(l.type)}),e.jsx("span",{className:`g7dt-text-xs g7dt-font-bold ${v(l.severity)}`,children:l.type}),l.formDataKey&&e.jsx("span",{className:"g7dt-text-xs g7dt-text-blue g7dt-font-mono",children:l.formDataKey})]}),e.jsx("div",{className:"g7dt-text-xs g7dt-text-white g7dt-mt-1",children:l.description}),e.jsxs("div",{className:"g7dt-text-xs g7dt-text-green g7dt-mt-1",children:["💡 ",l.suggestion]}),l.contextInfo&&e.jsxs("div",{className:"g7dt-flex g7dt-gap-2 g7dt-mt-1",children:[l.contextInfo.isInsideModal&&e.jsx("span",{className:"g7dt-badge g7dt-text-xs",children:"🪟 modal"}),l.contextInfo.isInsideSortable&&e.jsx("span",{className:"g7dt-badge g7dt-text-xs",children:"📊 sortable"}),e.jsxs("span",{className:"g7dt-text-xs g7dt-text-muted",children:["depth: ",l.contextInfo.depth]})]})]},l.id))})]})]})},$e=({devTools:d})=>{const t=d.getConditionalInfo();return e.jsxs("div",{className:"g7dt-space-y-4",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-text-purple g7dt-mb-2",children:["if 조건 (",t.ifConditions.length,")"]}),e.jsx("div",{className:"g7dt-space-y-1 g7dt-scroll-list",children:t.ifConditions.length===0?e.jsx("div",{className:"g7dt-empty-message",children:"추적된 if 조건 없음"}):t.ifConditions.map(s=>e.jsx("div",{className:`g7dt-condition-item ${s.evaluatedValue?"g7dt-condition-true":"g7dt-condition-false"}`,children:e.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center",children:[e.jsx("span",{className:"g7dt-font-mono g7dt-text-lightgray g7dt-truncate-60",children:s.expression}),e.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[e.jsx("span",{className:s.evaluatedValue?"g7dt-badge-success":"g7dt-badge-error",children:s.evaluatedValue?"true":"false"}),e.jsxs("span",{className:"g7dt-text-gray",children:[s.evaluationCount,"회"]})]})]})},s.id))})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-text-cyan g7dt-mb-2",children:["iteration (",t.iterations.length,")"]}),e.jsx("div",{className:"g7dt-space-y-1 g7dt-scroll-list",children:t.iterations.length===0?e.jsx("div",{className:"g7dt-empty-message",children:"추적된 iteration 없음"}):t.iterations.map(s=>e.jsxs("div",{className:"g7dt-card g7dt-text-xs",children:[e.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-1",children:[e.jsx("span",{className:"g7dt-font-mono g7dt-text-lightgray g7dt-truncate-60",children:s.source}),e.jsxs("span",{className:s.sourceLength>0?"g7dt-badge-blue":"g7dt-badge-warning",children:[s.sourceLength,"개 항목"]})]}),e.jsxs("div",{className:"g7dt-text-gray",children:[e.jsxs("span",{className:"g7dt-mr-2",children:["item_var: ",s.itemVar]}),s.indexVar&&e.jsxs("span",{children:["index_var: ",s.indexVar]})]})]},s.id))})]}),(t.ifConditions.some(s=>s.evaluatedValue===!1&&s.evaluationCount>5)||t.iterations.some(s=>s.sourceLength===0))&&e.jsxs("div",{className:"g7dt-warning-box",children:[e.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-text-yellow g7dt-mb-2",children:"잠재적 문제"}),e.jsxs("div",{className:"g7dt-space-y-1 g7dt-text-xs",children:[t.ifConditions.filter(s=>s.evaluatedValue===!1&&s.evaluationCount>5).map(s=>e.jsxs("div",{className:"g7dt-text-lightgray",children:["⚠️ if 조건 항상 false: ",s.expression]},s.id)),t.iterations.filter(s=>s.sourceLength===0).map(s=>e.jsxs("div",{className:"g7dt-text-lightgray",children:["⚠️ iteration 소스 비어있음: ",s.source]},s.id))]})]})]})},ze=({devTools:d})=>{const[t,s]=x.useState([]),[a,g]=x.useState({totalEvaluations:0,uniqueExpressions:0,warningCount:0,cacheHitRate:0,averageDuration:0,byType:{},byWarning:{}}),[r,o]=x.useState(""),[p,v]=x.useState(!1),[l,f]=x.useState(null),c=x.useCallback(()=>{const m=d.getExpressionInfo();s(m.expressions),g(m.stats)},[d]);x.useEffect(()=>{c();const m=d.watchExpressions(()=>{c()}),k=setInterval(c,2e3);return()=>{m(),clearInterval(k)}},[d,c]);const h=t.filter(m=>{if(p&&!m.warning)return!1;if(r){const k=r.toLowerCase();return m.expression.toLowerCase().includes(k)||m.componentName?.toLowerCase().includes(k)||m.propName?.toLowerCase().includes(k)||m.resultType.toLowerCase().includes(k)}return!0}),y=m=>{switch(m){case"string":return"g7dt-text-green";case"number":return"g7dt-text-blue";case"boolean":return"g7dt-text-purple";case"array":return"g7dt-text-cyan";case"object":return"g7dt-text-yellow";case"undefined":case"null":return"g7dt-text-red";default:return"g7dt-text-gray"}},n=m=>{switch(m){case"undefined-result":return"undefined 결과";case"null-result":return"null 결과";case"array-to-string":return"배열→문자열";case"object-to-string":return"객체→문자열";case"missing-optional-chain":return"?. 누락 의심";case"wrong-iteration-var":return"잘못된 반복 변수";case"type-mismatch":return"타입 불일치";case"cache-stale":return"캐시 오래됨";case"slow-evaluation":return"느린 평가";default:return m}},i=(m,k)=>k==="undefined"?"undefined":k==="null"?"null":k==="string"?`"${String(m).substring(0,50)}${String(m).length>50?"...":""}"`:k==="array"?`Array(${Array.isArray(m)?m.length:"?"})`:k==="object"?"Object{...}":String(m),u=()=>{d.clearExpressions(),s([]),f(null)};return e.jsxs("div",{className:"g7dt-space-y-4",children:[e.jsxs("div",{className:"g7dt-stats-grid-5",children:[e.jsxs("div",{className:"g7dt-stat-card-sm",children:[e.jsx("div",{className:"g7dt-stat-value-lg g7dt-text-blue",children:a.totalEvaluations}),e.jsx("div",{className:"g7dt-stat-label-xs",children:"총 평가"})]}),e.jsxs("div",{className:"g7dt-stat-card-sm",children:[e.jsx("div",{className:"g7dt-stat-value-lg g7dt-text-green",children:a.uniqueExpressions}),e.jsx("div",{className:"g7dt-stat-label-xs",children:"고유 표현식"})]}),e.jsxs("div",{className:"g7dt-stat-card-sm",children:[e.jsx("div",{className:"g7dt-stat-value-lg g7dt-text-yellow",children:a.warningCount}),e.jsx("div",{className:"g7dt-stat-label-xs",children:"경고"})]}),e.jsxs("div",{className:"g7dt-stat-card-sm",children:[e.jsxs("div",{className:"g7dt-stat-value-lg g7dt-text-purple",children:[(a.cacheHitRate*100).toFixed(0),"%"]}),e.jsx("div",{className:"g7dt-stat-label-xs",children:"캐시 히트"})]}),e.jsxs("div",{className:"g7dt-stat-card-sm",children:[e.jsxs("div",{className:"g7dt-stat-value-lg g7dt-text-cyan",children:[a.averageDuration.toFixed(1),"ms"]}),e.jsx("div",{className:"g7dt-stat-label-xs",children:"평균 시간"})]})]}),e.jsxs("div",{className:"g7dt-flex g7dt-gap-2 g7dt-items-center",children:[e.jsx("input",{type:"text",placeholder:"표현식, 컴포넌트, prop 검색...",value:r,onChange:m=>o(m.target.value),className:"g7dt-input g7dt-flex-1"}),e.jsxs("label",{className:"g7dt-checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:p,onChange:m=>v(m.target.checked),className:"g7dt-checkbox"}),"경고만"]}),e.jsx("button",{onClick:u,className:"g7dt-btn-danger-sm",children:"초기화"})]}),Object.keys(a.byType).length>0&&e.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-1",children:Object.entries(a.byType).map(([m,k])=>e.jsxs("span",{className:`g7dt-type-tag ${y(m)}`,children:[m,": ",k]},m))}),e.jsx("div",{className:"g7dt-space-y-1 g7dt-expr-list",children:h.length===0?e.jsx("div",{className:"g7dt-empty-message g7dt-py-4",children:r||p?"조건에 맞는 표현식이 없습니다":"추적된 표현식이 없습니다"}):h.slice(-50).reverse().map(m=>e.jsx("div",{onClick:()=>f(m),className:`g7dt-expr-item ${l?.id===m.id?"g7dt-expr-selected":m.warning?"g7dt-expr-warning":""}`,children:e.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-start g7dt-gap-2",children:[e.jsxs("div",{className:"g7dt-flex-1 g7dt-min-w-0",children:[e.jsx("div",{className:"g7dt-font-mono g7dt-text-white g7dt-truncate",title:m.expression,children:m.expression}),e.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2 g7dt-mt-1 g7dt-text-xxs",children:[m.componentName&&e.jsxs("span",{className:"g7dt-text-gray",children:[m.componentName,m.propName&&`.${m.propName}`]}),e.jsx("span",{className:y(m.resultType),children:i(m.result,m.resultType)})]})]}),e.jsxs("div",{className:"g7dt-flex g7dt-flex-col g7dt-items-end g7dt-gap-1",children:[e.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-1",children:[m.fromCache&&e.jsx("span",{className:"g7dt-mini-badge g7dt-badge-success",children:"캐시"}),m.warning&&e.jsx("span",{className:"g7dt-mini-badge g7dt-badge-warning",children:n(m.warning.type)})]}),m.duration!==void 0&&e.jsxs("span",{className:"g7dt-text-xxs g7dt-text-gray",children:[m.duration.toFixed(2),"ms"]})]})]})},m.id))}),l&&e.jsxs("div",{className:"g7dt-card",children:[e.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2",children:[e.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold",children:"표현식 상세"}),e.jsx("button",{onClick:()=>f(null),className:"g7dt-btn-close",children:"✕"})]}),e.jsxs("div",{className:"g7dt-space-y-2 g7dt-text-xs",children:[e.jsxs("div",{children:[e.jsx("span",{className:"g7dt-text-gray",children:"표현식:"}),e.jsx("code",{className:"g7dt-code g7dt-text-green",children:l.expression})]}),e.jsxs("div",{children:[e.jsx("span",{className:"g7dt-text-gray",children:"결과:"}),e.jsx("span",{className:`g7dt-ml-2 ${y(l.resultType)}`,children:JSON.stringify(l.result,null,2)?.substring(0,200)}),e.jsxs("span",{className:"g7dt-ml-2 g7dt-text-darkgray",children:["(",l.resultType,")"]})]}),l.componentName&&e.jsxs("div",{children:[e.jsx("span",{className:"g7dt-text-gray",children:"컴포넌트:"}),e.jsx("span",{className:"g7dt-ml-2 g7dt-text-blue",children:l.componentName}),l.propName&&e.jsxs("span",{className:"g7dt-text-gray",children:[".",l.propName]})]}),l.method&&e.jsxs("div",{children:[e.jsx("span",{className:"g7dt-text-gray",children:"메서드:"}),e.jsx("span",{className:"g7dt-ml-2 g7dt-text-purple",children:l.method})]}),e.jsxs("div",{children:[e.jsx("span",{className:"g7dt-text-gray",children:"캐시:"}),e.jsxs("span",{className:`g7dt-ml-2 ${l.fromCache?"g7dt-text-green":"g7dt-text-gray"}`,children:[l.fromCache?"캐시에서 로드":"새로 평가",l.skipCache&&" (skipCache)"]})]}),l.duration!==void 0&&e.jsxs("div",{children:[e.jsx("span",{className:"g7dt-text-gray",children:"소요 시간:"}),e.jsxs("span",{className:`g7dt-ml-2 ${l.duration>10?"g7dt-text-red":"g7dt-text-lightgray"}`,children:[l.duration.toFixed(3),"ms"]})]}),l.warning&&e.jsxs("div",{className:"g7dt-warning-box-light",children:[e.jsxs("div",{className:"g7dt-text-yellow g7dt-font-bold",children:["⚠️ ",n(l.warning.type)]}),e.jsx("div",{className:"g7dt-text-lightgray g7dt-mt-1",children:l.warning.message}),l.warning.suggestion&&e.jsxs("div",{className:"g7dt-text-gray g7dt-mt-1 g7dt-text-xxs",children:["💡 ",l.warning.suggestion]})]}),l.steps&&l.steps.length>0&&e.jsxs("details",{className:"g7dt-details",children:[e.jsxs("summary",{className:"g7dt-summary",children:["평가 단계 (",l.steps.length,")"]}),e.jsx("div",{className:"g7dt-mt-1 g7dt-space-y-1 g7dt-pl-2 g7dt-border-l",children:l.steps.map((m,k)=>e.jsxs("div",{className:"g7dt-text-xxs",children:[e.jsx("span",{className:"g7dt-text-purple",children:m.step}),m.path&&e.jsx("span",{className:"g7dt-text-gray g7dt-ml-1",children:m.path}),m.fromCache&&e.jsx("span",{className:"g7dt-text-green g7dt-ml-1",children:"(cached)"}),m.error&&e.jsx("span",{className:"g7dt-text-red g7dt-ml-1",children:m.error})]},k))})]})]})]}),Object.keys(a.byWarning).length>0&&e.jsxs("div",{className:"g7dt-warning-box-light",children:[e.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-text-yellow g7dt-mb-2",children:"경고 요약"}),e.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-2",children:Object.entries(a.byWarning).map(([m,k])=>e.jsxs("span",{className:"g7dt-warning-tag",children:[n(m),": ",k]},m))})]})]})},_e=({devTools:d})=>{const t=d.getHandlers(),[s,a]=x.useState(""),[g,r]=x.useState("all"),o={"built-in":t.filter(l=>l.category==="built-in"),custom:t.filter(l=>l.category==="custom"),module:t.filter(l=>l.category==="module"),plugin:t.filter(l=>l.category==="plugin")},p={all:t.length,"built-in":o["built-in"].length,custom:o.custom.length,module:o.module.length,plugin:o.plugin.length},v=t.filter(l=>g!=="all"&&l.category!==g?!1:s?l.name.toLowerCase().includes(s.toLowerCase())||l.description?.toLowerCase().includes(s.toLowerCase()):!0);return e.jsxs("div",{className:"g7dt-space-y-4",children:[e.jsx("div",{className:"g7dt-flex g7dt-gap-2",children:["all","built-in","custom","module","plugin"].map(l=>e.jsxs("button",{onClick:()=>r(l),className:g===l?"g7dt-filter-btn g7dt-filter-active":"g7dt-filter-btn",children:[l==="all"?"전체":l," (",p[l],")"]},l))}),e.jsx("input",{type:"text",placeholder:"핸들러 이름 검색...",value:s,onChange:l=>a(l.target.value),className:"g7dt-input g7dt-w-full"}),e.jsx("div",{className:"g7dt-space-y-1 g7dt-handler-list",children:v.length===0?e.jsx("div",{className:"g7dt-empty-message g7dt-py-4",children:"등록된 핸들러가 없습니다"}):v.map(l=>e.jsxs("div",{className:"g7dt-card",children:[e.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center",children:[e.jsx("span",{className:"g7dt-font-mono g7dt-text-blue",children:l.name}),e.jsx("span",{className:l.category==="built-in"?"g7dt-mini-badge g7dt-badge-success":l.category==="module"?"g7dt-mini-badge g7dt-badge-purple":l.category==="plugin"?"g7dt-mini-badge g7dt-badge-info":"g7dt-mini-badge g7dt-badge-warning",children:l.category})]}),l.description&&e.jsx("div",{className:"g7dt-text-xs g7dt-text-gray g7dt-mt-1",children:l.description})]},l.name))}),e.jsxs("div",{className:"g7dt-text-xs g7dt-text-gray",children:["총 ",t.length,"개 핸들러 | 빌트인 ",p["built-in"]," | 커스텀 ",p.custom," | 모듈 ",p.module," | 플러그인 ",p.plugin]})]})},je=({devTools:d})=>{const[t,s]=x.useState(d.getComponentEventInfo()),[a,g]=x.useState(null),r=x.useCallback(()=>{s(d.getComponentEventInfo())},[d]);x.useEffect(()=>{r();const p=setInterval(r,2e3);return()=>clearInterval(p)},[r]);const o=a?t.emitHistory.filter(p=>p.eventName===a):t.emitHistory;return e.jsxs("div",{className:"g7dt-space-y-4",children:[e.jsxs("div",{className:"g7dt-stats-grid-3",children:[e.jsxs("div",{className:"g7dt-stat-card",children:[e.jsx("div",{className:"g7dt-stat-value-lg g7dt-text-blue",children:t.subscriptions.length}),e.jsx("div",{className:"g7dt-stat-label",children:"이벤트 타입"})]}),e.jsxs("div",{className:"g7dt-stat-card",children:[e.jsx("div",{className:"g7dt-stat-value-lg g7dt-text-green",children:t.totalSubscribers}),e.jsx("div",{className:"g7dt-stat-label",children:"총 구독자"})]}),e.jsxs("div",{className:"g7dt-stat-card",children:[e.jsx("div",{className:"g7dt-stat-value-lg g7dt-text-purple",children:t.totalEmits}),e.jsx("div",{className:"g7dt-stat-label",children:"총 발행"})]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-2",children:"구독된 이벤트"}),e.jsxs("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-2",children:[e.jsx("button",{onClick:()=>g(null),className:a===null?"g7dt-filter-btn g7dt-filter-active":"g7dt-filter-btn",children:"전체"}),t.subscriptions.map(p=>e.jsxs("button",{onClick:()=>g(p.eventName),className:a===p.eventName?"g7dt-filter-btn g7dt-filter-active":"g7dt-filter-btn",children:[p.eventName," (",p.subscriberCount,")"]},p.eventName))]})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-2",children:["발행 이력 ",a&&`(${a})`]}),e.jsx("div",{className:"g7dt-space-y-1 g7dt-event-list",children:o.length===0?e.jsx("div",{className:"g7dt-empty-message g7dt-py-4",children:"이벤트 발행 이력이 없습니다"}):o.slice(-30).reverse().map(p=>e.jsxs("div",{className:`g7dt-card g7dt-text-xs ${p.hasError?"g7dt-card-error":""}`,children:[e.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center",children:[e.jsx("span",{className:"g7dt-font-mono g7dt-text-green",children:p.eventName}),e.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[e.jsxs("span",{className:"g7dt-text-gray",children:[p.listenerCount," listeners"]}),p.hasError&&e.jsx("span",{className:"g7dt-text-red g7dt-text-xxs",children:"에러"})]})]}),p.data!==void 0&&e.jsxs("details",{className:"g7dt-details g7dt-mt-1",children:[e.jsx("summary",{className:"g7dt-summary",children:"데이터"}),e.jsx("pre",{className:"g7dt-pre",children:JSON.stringify(p.data,null,2)})]}),p.hasError&&p.errorMessage&&e.jsx("div",{className:"g7dt-error-inline",children:p.errorMessage})]},p.id))})]}),e.jsx("button",{onClick:r,className:"g7dt-btn-secondary",children:"새로고침"})]})},Ae=({devTools:d})=>{const t=d.getDataSources(),[s,a]=x.useState("all"),[g,r]=x.useState(null),[o,p]=x.useState(!1),[v,l]=x.useState(null),f=x.useCallback(()=>{l(d.getDataPathTransformTrackingInfo())},[d]);x.useEffect(()=>{if(o){f();const u=setInterval(f,2e3);return()=>clearInterval(u)}},[o,f]);const c=u=>{switch(u){case"api_response":return"📥";case"extract_data":return"📄";case"apply_path":return"🔗";case"init_global":return"🌐";case"init_local":return"📌";default:return"❓"}},h=t.filter(u=>s==="all"?!0:u.status===s),y={all:t.length,idle:t.filter(u=>u.status==="idle").length,loading:t.filter(u=>u.status==="loading").length,loaded:t.filter(u=>u.status==="loaded").length,error:t.filter(u=>u.status==="error").length},n=u=>{switch(u){case"loaded":return"g7dt-badge-success";case"loading":return"g7dt-badge-warning";case"error":return"g7dt-badge-error";default:return"g7dt-badge-gray"}},i=g?t.find(u=>u.id===g):null;return e.jsxs("div",{className:"g7dt-space-y-4",children:[e.jsx("div",{className:"g7dt-flex g7dt-gap-2",children:["all","idle","loading","loaded","error"].map(u=>e.jsxs("button",{onClick:()=>a(u),className:s===u?"g7dt-filter-btn g7dt-filter-active":"g7dt-filter-btn",children:[u==="all"?"전체":u," (",y[u],")"]},u))}),e.jsx("div",{className:"g7dt-ds-grid",children:h.length===0?e.jsx("div",{className:"g7dt-empty-message g7dt-col-span-2 g7dt-py-4",children:"데이터소스가 없습니다"}):h.map(u=>e.jsxs("div",{onClick:()=>r(u.id),className:`g7dt-ds-item ${g===u.id?"g7dt-ds-selected":""}`,children:[e.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center",children:[e.jsx("span",{className:"g7dt-font-mono g7dt-text-blue g7dt-truncate",children:u.id}),e.jsx("span",{className:`g7dt-mini-badge ${n(u.status)}`,children:u.status})]}),e.jsx("div",{className:"g7dt-text-gray g7dt-mt-1 g7dt-truncate",children:u.endpoint||"(endpoint 없음)"}),u.itemCount!==void 0&&e.jsxs("div",{className:"g7dt-text-lightgray g7dt-mt-1",children:[u.itemCount,"개 항목"]})]},u.id))}),i&&e.jsxs("div",{className:"g7dt-card",children:[e.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2",children:[e.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold",children:i.id}),e.jsx("button",{onClick:()=>r(null),className:"g7dt-btn-close",children:"✕"})]}),e.jsxs("div",{className:"g7dt-space-y-2 g7dt-text-xs",children:[e.jsxs("div",{children:[e.jsx("span",{className:"g7dt-text-gray",children:"엔드포인트:"}),e.jsx("span",{className:"g7dt-ml-2 g7dt-text-green",children:i.endpoint||"-"})]}),i.dataPath&&e.jsxs("div",{children:[e.jsx("span",{className:"g7dt-text-gray",children:"데이터 경로:"}),e.jsx("span",{className:"g7dt-ml-2 g7dt-text-yellow",children:i.dataPath})]}),e.jsxs("div",{children:[e.jsx("span",{className:"g7dt-text-gray",children:"상태:"}),e.jsx("span",{className:`g7dt-ml-2 g7dt-mini-badge ${n(i.status)}`,children:i.status})]}),i.itemCount!==void 0&&e.jsxs("div",{children:[e.jsx("span",{className:"g7dt-text-gray",children:"항목 수:"}),e.jsx("span",{className:"g7dt-ml-2 g7dt-text-blue",children:i.itemCount})]}),i.keys&&i.keys.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"g7dt-text-gray",children:"키:"}),e.jsxs("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-1 g7dt-mt-1",children:[i.keys.slice(0,10).map(u=>e.jsx("span",{className:"g7dt-key-tag",children:u},u)),i.keys.length>10&&e.jsxs("span",{className:"g7dt-text-gray",children:["+",i.keys.length-10,"개"]})]})]}),i.dependencies&&i.dependencies.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"g7dt-text-gray",children:"의존성:"}),e.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-1 g7dt-mt-1",children:i.dependencies.map(u=>e.jsx("span",{className:"g7dt-dep-tag",children:u},u))})]})]})]}),e.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center",children:[e.jsxs("div",{className:"g7dt-text-xs g7dt-text-gray",children:["총 ",t.length,"개 데이터소스 | 로드됨 ",y.loaded," | 로딩중 ",y.loading," | 에러 ",y.error]}),e.jsx("button",{onClick:()=>p(!o),className:`g7dt-tab-button ${o?"g7dt-tab-active":""}`,children:"🔀 Path Transform"})]}),o&&v&&e.jsxs("div",{className:"g7dt-card",children:[e.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:["데이터 경로 변환 추적 (",v.transforms.length,"개)"]}),e.jsxs("div",{className:"g7dt-stats-grid-3 g7dt-mb-3",children:[e.jsxs("div",{className:"g7dt-text-center",children:[e.jsx("div",{className:"g7dt-text-xl g7dt-font-bold g7dt-text-blue",children:v.stats.totalTransforms}),e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"총 변환"})]}),e.jsxs("div",{className:"g7dt-text-center",children:[e.jsx("div",{className:"g7dt-text-xl g7dt-font-bold g7dt-text-purple",children:Object.keys(v.stats.byDataSource).length}),e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"데이터소스"})]}),e.jsxs("div",{className:"g7dt-text-center",children:[e.jsx("div",{className:"g7dt-text-xl g7dt-font-bold g7dt-text-yellow",children:v.stats.warningsCount}),e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"경고"})]})]}),v.transforms.length===0?e.jsx("div",{className:"g7dt-empty-state",children:"변환 기록이 없습니다"}):e.jsx("div",{className:"g7dt-space-y-2 g7dt-max-h-60 g7dt-overflow-y-auto",children:v.transforms.slice().reverse().slice(0,20).map((u,m)=>e.jsxs("div",{className:`g7dt-list-item ${u.warnings.length>0?"g7dt-border-yellow":""}`,children:[e.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[e.jsx("span",{className:"g7dt-text-xs g7dt-text-blue g7dt-font-mono",children:u.dataSourceId}),u.warnings.length>0&&e.jsxs("span",{className:"g7dt-badge g7dt-text-xs g7dt-text-yellow",children:["⚠️ ",u.warnings.length]})]}),e.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-1 g7dt-mt-1",children:u.transformSteps.map((k,b)=>e.jsxs("span",{className:"g7dt-badge g7dt-text-xs",title:`${k.inputPath} → ${k.outputPath}`,children:[c(k.step)," ",k.step]},b))}),u.finalBinding&&e.jsxs("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mt-1",children:["최종: ",e.jsx("span",{className:"g7dt-text-green",children:u.finalBinding.expression}),"→ ",e.jsx("span",{className:"g7dt-text-blue",children:u.finalBinding.resolvedPath})]}),u.warnings.length>0&&e.jsx("div",{className:"g7dt-text-xs g7dt-text-yellow g7dt-mt-1",children:u.warnings[0]})]},`${u.dataSourceId}-${m}`))}),v.stats.commonWarnings.length>0&&e.jsxs("div",{className:"g7dt-mt-3",children:[e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mb-1",children:"자주 발생하는 경고"}),e.jsx("div",{className:"g7dt-space-y-1",children:v.stats.commonWarnings.slice(0,5).map((u,m)=>e.jsxs("div",{className:"g7dt-text-xs g7dt-text-yellow",children:[u.warning," (",u.count,"회)"]},m))})]})]})]})},Oe=({devTools:d})=>{const[t,s]=x.useState(d.getStateRenderingInfo()),[a,g]=x.useState(null),[r,o]=x.useState(!1),[p,v]=x.useState(""),l=x.useCallback(()=>{s(d.getStateRenderingInfo())},[d]);x.useEffect(()=>{l();const n=setInterval(l,2e3);return()=>clearInterval(n)},[l]);const f=t.logs.filter(n=>!(r&&n.renderedComponents.length>0||p&&!n.statePath.toLowerCase().includes(p.toLowerCase()))),c=a?t.logs.find(n=>n.setStateId===a):null,h=t.stats,y=t.logs.filter(n=>n.renderedComponents.length===0).length;return e.jsxs("div",{className:"g7dt-space-y-4",children:[e.jsxs("div",{className:"g7dt-stats-grid",children:[e.jsxs("div",{className:"g7dt-stat-card",children:[e.jsx("div",{className:"g7dt-stat-value g7dt-text-blue",children:h.totalStateChanges}),e.jsx("div",{className:"g7dt-stat-label",children:"상태 변경"})]}),e.jsxs("div",{className:"g7dt-stat-card",children:[e.jsx("div",{className:"g7dt-stat-value g7dt-text-green",children:h.totalRenders}),e.jsx("div",{className:"g7dt-stat-label",children:"총 렌더링"})]}),e.jsxs("div",{className:"g7dt-stat-card",children:[e.jsxs("div",{className:"g7dt-stat-value g7dt-text-purple",children:[h.avgRenderDuration.toFixed(1),"ms"]}),e.jsx("div",{className:"g7dt-stat-label",children:"평균 렌더 시간"})]}),e.jsxs("div",{className:"g7dt-stat-card",children:[e.jsx("div",{className:`g7dt-stat-value ${y>0?"g7dt-text-yellow":"g7dt-text-green"}`,children:y}),e.jsx("div",{className:"g7dt-stat-label",children:"렌더링 없음"})]})]}),e.jsxs("div",{className:"g7dt-flex g7dt-gap-2",children:[e.jsx("input",{type:"text",placeholder:"상태 경로 필터 (예: _global.user)",value:p,onChange:n=>v(n.target.value),className:"g7dt-input g7dt-flex-1"}),e.jsx("button",{onClick:()=>o(!r),className:r?"g7dt-filter-btn-active-yellow":"g7dt-filter-btn",children:"렌더링 없음만"})]}),e.jsx("div",{className:"g7dt-scroll-list",children:f.length===0?e.jsx("div",{className:"g7dt-empty-state",children:"상태-렌더링 로그가 없습니다"}):f.slice(-30).reverse().map(n=>{const i=n.renderedComponents.length>0,u=i?"✅":"⚠️",m=new Date(n.timestamp).toLocaleTimeString();return e.jsxs("div",{onClick:()=>g(n.setStateId),className:`g7dt-render-log-item ${a===n.setStateId?"g7dt-selected":i?"":"g7dt-warning"}`,children:[e.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center",children:[e.jsxs("span",{className:"g7dt-mono g7dt-text-blue",children:[u," ",n.statePath]}),e.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[i?e.jsxs("span",{className:"g7dt-text-green",children:[n.renderedComponents.length,"개 렌더"]}):e.jsx("span",{className:"g7dt-text-yellow",children:"렌더링 없음"}),e.jsx("span",{className:"g7dt-text-muted",children:m})]})]}),n.triggeredBy?.handlerType&&e.jsxs("div",{className:"g7dt-text-muted g7dt-mt-1",children:["트리거: ",n.triggeredBy.handlerType]})]},n.setStateId)})}),c&&e.jsxs("div",{className:"g7dt-card",children:[e.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2",children:[e.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold",children:c.statePath}),e.jsx("button",{onClick:()=>g(null),className:"g7dt-close-btn",children:"✕"})]}),e.jsxs("div",{className:"g7dt-space-y-2 g7dt-text-xs",children:[e.jsxs("div",{children:[e.jsx("span",{className:"g7dt-text-muted",children:"setStateId:"}),e.jsx("span",{className:"g7dt-ml-2 g7dt-text-purple g7dt-mono",children:c.setStateId})]}),c.triggeredBy&&e.jsxs("div",{children:[e.jsx("span",{className:"g7dt-text-muted",children:"트리거:"}),e.jsxs("span",{className:"g7dt-ml-2 g7dt-text-yellow",children:[c.triggeredBy.handlerType,c.triggeredBy.actionId&&` (${c.triggeredBy.actionId})`]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"g7dt-text-muted",children:"이전 값:"}),e.jsx("pre",{className:"g7dt-pre g7dt-text-red",children:JSON.stringify(c.oldValue,null,2)?.slice(0,200)})]}),e.jsxs("div",{children:[e.jsx("span",{className:"g7dt-text-muted",children:"새 값:"}),e.jsx("pre",{className:"g7dt-pre g7dt-text-green",children:JSON.stringify(c.newValue,null,2)?.slice(0,200)})]}),c.renderedComponents.length>0?e.jsxs("div",{children:[e.jsxs("span",{className:"g7dt-text-muted",children:["렌더링된 컴포넌트 (",c.renderedComponents.length,"개):"]}),e.jsxs("div",{className:"g7dt-mt-1 g7dt-space-y-1",children:[c.renderedComponents.slice(0,10).map((n,i)=>e.jsxs("div",{className:"g7dt-render-comp-item",children:[e.jsx("span",{className:"g7dt-text-blue",children:n.componentName}),e.jsxs("span",{className:"g7dt-text-muted",children:[n.renderDuration.toFixed(2),"ms"]})]},i)),c.renderedComponents.length>10&&e.jsxs("div",{className:"g7dt-text-muted g7dt-text-center",children:["... 외 ",c.renderedComponents.length-10,"개"]})]}),e.jsxs("div",{className:"g7dt-mt-2 g7dt-text-muted",children:["총 렌더 시간: ",c.totalRenderDuration.toFixed(2),"ms"]})]}):e.jsxs("div",{className:"g7dt-warning-box",children:[e.jsx("span",{className:"g7dt-text-yellow",children:"⚠️ 렌더링이 발생하지 않았습니다"}),e.jsxs("div",{className:"g7dt-text-muted g7dt-mt-1 g7dt-text-xxs",children:["가능한 원인:",e.jsxs("ul",{className:"g7dt-list g7dt-mt-1",children:[e.jsx("li",{children:"해당 상태를 바인딩하는 컴포넌트가 없음"}),e.jsx("li",{children:"컴포넌트가 마운트되지 않은 상태"}),e.jsx("li",{children:"동일한 값으로 상태 설정"})]})]})]})]})]}),h.topRenderedComponents.length>0&&e.jsxs("div",{children:[e.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-2",children:"가장 많이 렌더링된 컴포넌트"}),e.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-2",children:h.topRenderedComponents.slice(0,5).map((n,i)=>e.jsxs("span",{className:"g7dt-tag",children:[n.name,": ",e.jsx("span",{className:"g7dt-text-blue",children:n.count})]},i))})]}),e.jsxs("div",{className:"g7dt-flex g7dt-gap-2",children:[e.jsx("button",{onClick:l,className:"g7dt-btn-secondary",children:"새로고침"}),e.jsx("button",{onClick:()=>{d.clearStateRenderingLogs(),l()},className:"g7dt-btn-danger",children:"로그 초기화"})]})]})},Me=({devTools:d})=>{const[t,s]=x.useState(null),[a,g]=x.useState(null),[r,o]=x.useState("all"),p=x.useCallback(()=>{s(d.getStyleValidationInfo())},[d]);if(x.useEffect(()=>{p();const c=setInterval(p,2e3);return()=>clearInterval(c)},[p]),!t)return e.jsx("div",{className:"g7dt-empty-state",children:"로딩 중..."});const v=t.issues.filter(c=>r==="all"?!0:c.type===r),l=a?t.issues.find(c=>c.componentId===a):null,f=t.stats;return e.jsxs("div",{className:"g7dt-space-y-4",children:[e.jsxs("div",{className:"g7dt-stats-grid",children:[e.jsxs("div",{className:"g7dt-stat-card",children:[e.jsx("div",{className:"g7dt-stat-value g7dt-text-blue",children:f.totalComponents}),e.jsx("div",{className:"g7dt-stat-label",children:"총 컴포넌트"})]}),e.jsxs("div",{className:"g7dt-stat-card",children:[e.jsx("div",{className:`g7dt-stat-value ${f.invisibleCount>0?"g7dt-text-red":"g7dt-text-green"}`,children:f.invisibleCount}),e.jsx("div",{className:"g7dt-stat-label",children:"숨겨진 요소"})]}),e.jsxs("div",{className:"g7dt-stat-card",children:[e.jsx("div",{className:`g7dt-stat-value ${f.tailwindIssueCount>0?"g7dt-text-yellow":"g7dt-text-green"}`,children:f.tailwindIssueCount}),e.jsx("div",{className:"g7dt-stat-label",children:"Tailwind 이슈"})]}),e.jsxs("div",{className:"g7dt-stat-card",children:[e.jsx("div",{className:`g7dt-stat-value ${f.darkModeIssueCount>0?"g7dt-text-purple":"g7dt-text-green"}`,children:f.darkModeIssueCount}),e.jsx("div",{className:"g7dt-stat-label",children:"다크모드 이슈"})]})]}),e.jsxs("div",{className:"g7dt-flex g7dt-gap-2",children:[e.jsxs("select",{value:r,onChange:c=>o(c.target.value),className:"g7dt-select",children:[e.jsx("option",{value:"all",children:"모든 이슈"}),e.jsx("option",{value:"invisible-element",children:"숨겨진 요소"}),e.jsx("option",{value:"tailwind-purging",children:"Tailwind 퍼징"}),e.jsx("option",{value:"dark-mode-missing",children:"다크모드 누락"})]}),e.jsx("button",{onClick:p,className:"g7dt-btn-secondary",children:"새로고침"})]}),e.jsx("div",{className:"g7dt-scroll-list",children:v.length===0?e.jsx("div",{className:"g7dt-empty-state",children:t.issues.length===0?"스타일 이슈가 없습니다 ✓":"필터에 맞는 이슈가 없습니다"}):v.map(c=>{const h=c.type==="invisible-element"?"👁️":c.type==="tailwind-purging"?"🎨":"🌙",y=c.severity==="error"?"g7dt-severity-error":c.severity==="warning"?"g7dt-severity-warning":"g7dt-severity-info";return e.jsxs("div",{onClick:()=>g(c.componentId),className:`g7dt-style-issue-item ${y} ${a===c.componentId?"g7dt-selected":""}`,children:[e.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center",children:[e.jsxs("span",{className:"g7dt-mono g7dt-text-blue",children:[h," ",c.componentName]}),e.jsx("span",{className:c.severity==="error"?"g7dt-badge-error":c.severity==="warning"?"g7dt-badge-warning":"g7dt-badge-info",children:c.type})]}),e.jsx("div",{className:"g7dt-text-muted g7dt-mt-1 g7dt-truncate",children:c.description})]},c.componentId)})}),l&&e.jsxs("div",{className:"g7dt-card",children:[e.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2",children:[e.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold",children:l.componentName}),e.jsx("button",{onClick:()=>g(null),className:"g7dt-close-btn",children:"✕"})]}),e.jsxs("div",{className:"g7dt-space-y-2 g7dt-text-xs",children:[e.jsxs("div",{children:[e.jsx("span",{className:"g7dt-text-muted",children:"이슈 타입:"}),e.jsx("span",{className:"g7dt-ml-2 g7dt-text-yellow",children:l.type})]}),e.jsxs("div",{children:[e.jsx("span",{className:"g7dt-text-muted",children:"설명:"}),e.jsx("div",{className:"g7dt-mt-1 g7dt-text-white",children:l.description})]}),e.jsxs("div",{children:[e.jsx("span",{className:"g7dt-text-muted",children:"CSS 속성:"}),e.jsx("span",{className:"g7dt-ml-2 g7dt-text-purple",children:l.property}),e.jsxs("span",{className:"g7dt-ml-2 g7dt-text-muted",children:["= ",l.currentValue]}),l.expectedValue&&e.jsxs("span",{className:"g7dt-ml-2 g7dt-text-green",children:["(예상: ",l.expectedValue,")"]})]}),l.suggestion&&e.jsxs("div",{children:[e.jsx("span",{className:"g7dt-text-muted",children:"해결 방법:"}),e.jsx("div",{className:"g7dt-mt-1 g7dt-text-green",children:l.suggestion})]})]})]}),t.componentStyles.length>0&&e.jsxs("div",{children:[e.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-2",children:["컴포넌트 스타일 (",t.componentStyles.length,")"]}),e.jsx("div",{className:"g7dt-scroll-list-sm",children:t.componentStyles.slice(0,20).map((c,h)=>e.jsxs("div",{className:"g7dt-list-item",children:[e.jsxs("div",{className:"g7dt-flex g7dt-justify-between",children:[e.jsx("span",{className:"g7dt-text-blue",children:c.componentName}),e.jsxs("span",{className:"g7dt-text-muted",children:[c.classes.length," classes"]})]}),c.classes.length>0&&e.jsxs("div",{className:"g7dt-text-muted g7dt-mt-1 g7dt-truncate",children:[c.classes.slice(0,5).join(" "),c.classes.length>5&&"..."]})]},h))})]})]})},Pe=({devTools:d})=>{const[t,s]=x.useState(null),[a,g]=x.useState(null),[r,o]=x.useState("all"),p=x.useCallback(()=>{s(d.getAuthDebugInfo())},[d]);if(x.useEffect(()=>{p();const h=setInterval(p,2e3);return()=>clearInterval(h)},[p]),!t)return e.jsx("div",{className:"g7dt-empty-state",children:"로딩 중..."});const v=t.events.filter(h=>r==="all"?!0:h.type===r),l=a?t.events.find(h=>h.id===a):null,f=t.stats,c=t.state;return e.jsxs("div",{className:"g7dt-space-y-4",children:[e.jsxs("div",{className:"g7dt-card",children:[e.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-justify-between g7dt-mb-3",children:[e.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold",children:"현재 인증 상태"}),e.jsxs("span",{className:"g7dt-text-xs g7dt-text-muted",children:["소스: ",c.source||"unknown"]})]}),e.jsxs("div",{className:"g7dt-stats-grid-3 g7dt-mb-3",children:[e.jsx("div",{className:"g7dt-text-center",children:e.jsx("div",{className:`g7dt-text-lg g7dt-font-bold ${c.isAuthenticated?"g7dt-text-green":"g7dt-text-red"}`,children:c.isAuthenticated?"✓ 인증됨":"✕ 미인증"})}),e.jsx("div",{className:"g7dt-text-center",children:e.jsx("div",{className:`g7dt-text-lg g7dt-font-bold ${c.tokens.hasAccessToken?"g7dt-text-green":"g7dt-text-yellow"}`,children:c.tokens.hasAccessToken?"✓ 토큰 유효":"⚠ 토큰 없음"})}),e.jsx("div",{className:"g7dt-text-center",children:e.jsx("div",{className:"g7dt-text-lg g7dt-font-bold g7dt-text-blue",children:c.user?.name||c.user?.email||"익명"})})]}),c.user&&e.jsxs("div",{className:"g7dt-border-t g7dt-pt-3 g7dt-mt-3",children:[e.jsxs("div",{className:"g7dt-grid-2 g7dt-gap-2 g7dt-text-xs",children:[e.jsxs("div",{className:"g7dt-flex g7dt-justify-between",children:[e.jsx("span",{className:"g7dt-text-muted",children:"ID:"}),e.jsx("span",{className:"g7dt-text-white g7dt-mono",children:c.user.id})]}),e.jsxs("div",{className:"g7dt-flex g7dt-justify-between",children:[e.jsx("span",{className:"g7dt-text-muted",children:"이메일:"}),e.jsx("span",{className:"g7dt-text-white g7dt-truncate g7dt-ml-2",title:c.user.email,children:c.user.email})]}),c.user.name&&e.jsxs("div",{className:"g7dt-flex g7dt-justify-between",children:[e.jsx("span",{className:"g7dt-text-muted",children:"이름:"}),e.jsx("span",{className:"g7dt-text-white",children:c.user.name})]}),c.user.nickname&&e.jsxs("div",{className:"g7dt-flex g7dt-justify-between",children:[e.jsx("span",{className:"g7dt-text-muted",children:"닉네임:"}),e.jsx("span",{className:"g7dt-text-white",children:c.user.nickname})]}),c.user.phone&&e.jsxs("div",{className:"g7dt-flex g7dt-justify-between",children:[e.jsx("span",{className:"g7dt-text-muted",children:"전화번호:"}),e.jsx("span",{className:"g7dt-text-white",children:c.user.phone})]}),c.user.status&&e.jsxs("div",{className:"g7dt-flex g7dt-justify-between",children:[e.jsx("span",{className:"g7dt-text-muted",children:"상태:"}),e.jsx("span",{className:c.user.status==="active"?"g7dt-text-green":"g7dt-text-yellow",children:c.user.status})]}),c.user.locale&&e.jsxs("div",{className:"g7dt-flex g7dt-justify-between",children:[e.jsx("span",{className:"g7dt-text-muted",children:"언어:"}),e.jsx("span",{className:"g7dt-text-white",children:c.user.locale})]})]}),c.user.roles&&c.user.roles.length>0&&e.jsxs("div",{className:"g7dt-mt-2",children:[e.jsx("span",{className:"g7dt-text-muted g7dt-text-xs",children:"역할: "}),e.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-1 g7dt-mt-1",children:c.user.roles.map((h,y)=>e.jsx("span",{className:"g7dt-role-tag",title:h.guard_name?`guard: ${h.guard_name}`:void 0,children:typeof h=="string"?h:h.name},y))})]}),c.user.permissions&&c.user.permissions.length>0&&e.jsxs("div",{className:"g7dt-mt-2",children:[e.jsx("span",{className:"g7dt-text-muted g7dt-text-xs",children:"권한: "}),e.jsxs("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-1 g7dt-mt-1 g7dt-max-h-16 g7dt-overflow-auto",children:[c.user.permissions.slice(0,10).map((h,y)=>e.jsx("span",{className:"g7dt-perm-tag",title:h.guard_name?`guard: ${h.guard_name}`:void 0,children:typeof h=="string"?h:h.name},y)),c.user.permissions.length>10&&e.jsxs("span",{className:"g7dt-text-muted g7dt-text-xs",children:["+",c.user.permissions.length-10,"개"]})]})]}),e.jsxs("div",{className:"g7dt-mt-2 g7dt-grid-2 g7dt-gap-2 g7dt-text-xs",children:[c.user.created_at&&e.jsxs("div",{className:"g7dt-flex g7dt-justify-between",children:[e.jsx("span",{className:"g7dt-text-muted",children:"가입일:"}),e.jsx("span",{className:"g7dt-text-muted",children:new Date(c.user.created_at).toLocaleDateString()})]}),c.user.last_login_at&&e.jsxs("div",{className:"g7dt-flex g7dt-justify-between",children:[e.jsx("span",{className:"g7dt-text-muted",children:"마지막 로그인:"}),e.jsx("span",{className:"g7dt-text-muted",children:new Date(c.user.last_login_at).toLocaleString()})]}),c.user.email_verified_at&&e.jsxs("div",{className:"g7dt-flex g7dt-justify-between",children:[e.jsx("span",{className:"g7dt-text-muted",children:"이메일 인증:"}),e.jsx("span",{className:"g7dt-text-green",children:"✓ 인증됨"})]})]})]}),e.jsx("div",{className:"g7dt-border-t g7dt-pt-3 g7dt-mt-3",children:e.jsxs("div",{className:"g7dt-grid-2 g7dt-gap-2 g7dt-text-xs",children:[e.jsxs("div",{className:"g7dt-flex g7dt-justify-between",children:[e.jsx("span",{className:"g7dt-text-muted",children:"저장소:"}),e.jsx("span",{className:"g7dt-text-white",children:c.tokens.storage})]}),c.tokens.accessTokenPreview&&e.jsxs("div",{className:"g7dt-flex g7dt-justify-between",children:[e.jsx("span",{className:"g7dt-text-muted",children:"토큰:"}),e.jsx("span",{className:"g7dt-text-muted g7dt-mono",children:c.tokens.accessTokenPreview})]})]})}),c.tokens.accessTokenExpiresAt&&e.jsxs("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mt-2 g7dt-text-center",children:["토큰 만료: ",new Date(c.tokens.accessTokenExpiresAt).toLocaleString()]})]}),e.jsxs("div",{className:"g7dt-stats-grid-5",children:[e.jsxs("div",{className:"g7dt-stat-card-sm",children:[e.jsx("div",{className:"g7dt-stat-value-sm g7dt-text-blue",children:f.loginAttempts}),e.jsx("div",{className:"g7dt-stat-label",children:"로그인 시도"})]}),e.jsxs("div",{className:"g7dt-stat-card-sm",children:[e.jsx("div",{className:"g7dt-stat-value-sm g7dt-text-green",children:f.successfulLogins}),e.jsx("div",{className:"g7dt-stat-label",children:"성공"})]}),e.jsxs("div",{className:"g7dt-stat-card-sm",children:[e.jsx("div",{className:`g7dt-stat-value-sm ${f.failedLogins>0?"g7dt-text-red":"g7dt-text-muted"}`,children:f.failedLogins}),e.jsx("div",{className:"g7dt-stat-label",children:"실패"})]}),e.jsxs("div",{className:"g7dt-stat-card-sm",children:[e.jsx("div",{className:"g7dt-stat-value-sm g7dt-text-purple",children:f.tokenRefreshes}),e.jsx("div",{className:"g7dt-stat-label",children:"토큰 갱신"})]}),e.jsxs("div",{className:"g7dt-stat-card-sm",children:[e.jsx("div",{className:`g7dt-stat-value-sm ${f.unauthorizedResponses>0?"g7dt-text-red":"g7dt-text-muted"}`,children:f.unauthorizedResponses}),e.jsx("div",{className:"g7dt-stat-label",children:"401 응답"})]})]}),e.jsxs("div",{className:"g7dt-flex g7dt-gap-2",children:[e.jsxs("select",{value:r,onChange:h=>o(h.target.value),className:"g7dt-select",children:[e.jsx("option",{value:"all",children:"모든 이벤트"}),e.jsx("option",{value:"login",children:"로그인"}),e.jsx("option",{value:"logout",children:"로그아웃"}),e.jsx("option",{value:"token-refresh",children:"토큰 갱신"}),e.jsx("option",{value:"token-expired",children:"토큰 만료"}),e.jsx("option",{value:"api-unauthorized",children:"401 응답"})]}),e.jsx("button",{onClick:p,className:"g7dt-btn-secondary",children:"새로고침"})]}),e.jsx("div",{className:"g7dt-scroll-list-sm",children:v.length===0?e.jsx("div",{className:"g7dt-empty-state",children:"인증 이벤트가 없습니다"}):v.slice(-20).reverse().map(h=>{const y=h.success?"✅":"❌",n=new Date(h.timestamp).toLocaleTimeString();return e.jsxs("div",{onClick:()=>g(h.id),className:`g7dt-auth-event-item ${a===h.id?"g7dt-selected":h.success?"":"g7dt-error"}`,children:[e.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center",children:[e.jsxs("span",{className:"g7dt-mono",children:[y," ",h.type]}),e.jsx("span",{className:"g7dt-text-muted",children:n})]}),h.error&&e.jsx("div",{className:"g7dt-text-red g7dt-mt-1 g7dt-truncate",children:h.error})]},h.id)})}),l&&e.jsxs("div",{className:"g7dt-card",children:[e.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2",children:[e.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold",children:l.type}),e.jsx("button",{onClick:()=>g(null),className:"g7dt-close-btn",children:"✕"})]}),e.jsxs("div",{className:"g7dt-space-y-2 g7dt-text-xs",children:[e.jsxs("div",{children:[e.jsx("span",{className:"g7dt-text-muted",children:"결과:"}),e.jsx("span",{className:`g7dt-ml-2 ${l.success?"g7dt-text-green":"g7dt-text-red"}`,children:l.success?"성공":"실패"})]}),l.error&&e.jsxs("div",{children:[e.jsx("span",{className:"g7dt-text-muted",children:"에러:"}),e.jsx("div",{className:"g7dt-mt-1 g7dt-text-red",children:l.error})]}),l.details&&Object.keys(l.details).length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"g7dt-text-muted",children:"상세:"}),e.jsx("pre",{className:"g7dt-pre g7dt-text-green",children:JSON.stringify(l.details,null,2)})]})]})]}),t.headerAnalysis.length>0&&e.jsxs("div",{children:[e.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-2",children:"최근 API 인증 헤더"}),e.jsx("div",{className:"g7dt-scroll-list-xs",children:t.headerAnalysis.slice(-10).reverse().map((h,y)=>e.jsxs("div",{className:"g7dt-header-item",children:[e.jsx("span",{className:"g7dt-text-blue g7dt-truncate g7dt-flex-1",children:h.url}),e.jsx("span",{className:`g7dt-ml-2 ${h.hasAuthHeader?"g7dt-text-green":"g7dt-text-yellow"}`,children:h.hasAuthHeader?`✓ ${h.headerType}`:"✕ 헤더 없음"}),h.responseStatus&&e.jsx("span",{className:`g7dt-ml-2 ${h.responseStatus<400?"g7dt-text-muted":"g7dt-text-red"}`,children:h.responseStatus})]},y))})]})]})},He=({devTools:d})=>{const[t,s]=x.useState([]),[a,g]=x.useState(null),[r,o]=x.useState(null),[p,v]=x.useState("all"),[l,f]=x.useState(""),[c,h]=x.useState(""),y=x.useCallback(()=>{const b=d.getLogInfo();s(b.entries),g(b.stats)},[d]);x.useEffect(()=>{y();const b=setInterval(y,1e3);return()=>clearInterval(b)},[y]);const n=t.filter(b=>!(p!=="all"&&b.level!==p||l&&!b.prefix.toLowerCase().includes(l.toLowerCase())||c&&!b.message.toLowerCase().includes(c.toLowerCase()))),i=r?t.find(b=>b.id===r):null,u=()=>{d.clearLogs(),y(),o(null)},m=b=>{switch(b){case"error":return"g7dt-text-red";case"warn":return"g7dt-text-yellow";case"info":return"g7dt-text-blue";case"debug":return"g7dt-text-muted";default:return"g7dt-text-white"}},k=b=>{switch(b){case"error":return"g7dt-log-error";case"warn":return"g7dt-log-warn";case"info":return"g7dt-log-info";case"debug":return"g7dt-log-debug";default:return"g7dt-log-default"}};return e.jsxs("div",{className:"g7dt-space-y-4",children:[a&&e.jsxs("div",{className:"g7dt-stats-grid-6",children:[e.jsxs("div",{className:"g7dt-stat-card-sm",children:[e.jsx("div",{className:"g7dt-stat-value-sm g7dt-text-white",children:a.totalLogs}),e.jsx("div",{className:"g7dt-stat-label",children:"전체"})]}),e.jsxs("div",{className:"g7dt-stat-card-sm",children:[e.jsx("div",{className:"g7dt-stat-value-sm g7dt-text-red",children:a.byLevel.error}),e.jsx("div",{className:"g7dt-stat-label",children:"에러"})]}),e.jsxs("div",{className:"g7dt-stat-card-sm",children:[e.jsx("div",{className:"g7dt-stat-value-sm g7dt-text-yellow",children:a.byLevel.warn}),e.jsx("div",{className:"g7dt-stat-label",children:"경고"})]}),e.jsxs("div",{className:"g7dt-stat-card-sm",children:[e.jsx("div",{className:"g7dt-stat-value-sm g7dt-text-blue",children:a.byLevel.info}),e.jsx("div",{className:"g7dt-stat-label",children:"정보"})]}),e.jsxs("div",{className:"g7dt-stat-card-sm",children:[e.jsx("div",{className:`g7dt-stat-value-sm ${a.recentErrors>0?"g7dt-text-red":"g7dt-text-green"}`,children:a.recentErrors}),e.jsx("div",{className:"g7dt-stat-label",children:"최근 에러"})]}),e.jsxs("div",{className:"g7dt-stat-card-sm",children:[e.jsx("div",{className:`g7dt-stat-value-sm ${a.recentWarnings>0?"g7dt-text-yellow":"g7dt-text-green"}`,children:a.recentWarnings}),e.jsx("div",{className:"g7dt-stat-label",children:"최근 경고"})]})]}),e.jsxs("div",{className:"g7dt-flex g7dt-gap-2 g7dt-flex-wrap",children:[e.jsxs("select",{value:p,onChange:b=>v(b.target.value),className:"g7dt-select",children:[e.jsx("option",{value:"all",children:"모든 레벨"}),e.jsx("option",{value:"error",children:"에러"}),e.jsx("option",{value:"warn",children:"경고"}),e.jsx("option",{value:"info",children:"정보"}),e.jsx("option",{value:"log",children:"로그"}),e.jsx("option",{value:"debug",children:"디버그"})]}),e.jsx("input",{type:"text",placeholder:"prefix 필터",value:l,onChange:b=>f(b.target.value),className:"g7dt-input g7dt-w-32"}),e.jsx("input",{type:"text",placeholder:"메시지 검색",value:c,onChange:b=>h(b.target.value),className:"g7dt-input g7dt-flex-1"}),e.jsx("button",{onClick:y,className:"g7dt-btn-secondary",children:"새로고침"}),e.jsx("button",{onClick:u,className:"g7dt-btn-danger",children:"초기화"})]}),e.jsx("div",{className:"g7dt-scroll-list-lg",children:n.length===0?e.jsx("div",{className:"g7dt-empty-state",children:t.length===0?"로그가 없습니다":"필터에 맞는 로그가 없습니다"}):n.slice(-50).reverse().map(b=>{const N=new Date(b.timestamp).toLocaleTimeString();return e.jsxs("div",{onClick:()=>o(b.id),className:`g7dt-log-item ${r===b.id?"g7dt-selected":k(b.level)}`,children:[e.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center",children:[e.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[e.jsx("span",{className:`g7dt-font-bold g7dt-uppercase ${m(b.level)}`,children:b.level}),e.jsxs("span",{className:"g7dt-text-purple",children:["[",b.prefix,"]"]})]}),e.jsx("span",{className:"g7dt-text-muted",children:N})]}),e.jsx("div",{className:"g7dt-text-white g7dt-mt-1 g7dt-truncate",children:b.message})]},b.id)})}),i&&e.jsxs("div",{className:"g7dt-card",children:[e.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2",children:[e.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold",children:[e.jsx("span",{className:m(i.level),children:i.level.toUpperCase()})," ",e.jsxs("span",{className:"g7dt-text-purple",children:["[",i.prefix,"]"]})]}),e.jsx("button",{onClick:()=>o(null),className:"g7dt-close-btn",children:"✕"})]}),e.jsxs("div",{className:"g7dt-space-y-2 g7dt-text-xs",children:[e.jsxs("div",{children:[e.jsx("span",{className:"g7dt-text-muted",children:"시간:"}),e.jsx("span",{className:"g7dt-ml-2 g7dt-text-white",children:new Date(i.timestamp).toLocaleString()})]}),e.jsxs("div",{children:[e.jsx("span",{className:"g7dt-text-muted",children:"메시지:"}),e.jsx("pre",{className:"g7dt-pre g7dt-text-white g7dt-whitespace-pre-wrap",children:i.message})]}),i.args.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"g7dt-text-muted",children:"인수:"}),e.jsx("pre",{className:"g7dt-pre g7dt-text-green",children:JSON.stringify(i.args,null,2)})]}),i.stack&&e.jsxs("div",{children:[e.jsx("span",{className:"g7dt-text-muted",children:"스택 트레이스:"}),e.jsx("pre",{className:"g7dt-pre-stack g7dt-text-red",children:i.stack})]})]})]}),a&&Object.keys(a.byPrefix).length>0&&e.jsxs("div",{children:[e.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-2",children:"Prefix별 로그 수"}),e.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-2",children:Object.entries(a.byPrefix).sort((b,N)=>N[1]-b[1]).slice(0,10).map(([b,N])=>e.jsxs("button",{onClick:()=>f(b),className:l===b?"g7dt-prefix-btn-active":"g7dt-prefix-btn",children:[b,": ",e.jsx("span",{className:"g7dt-text-blue",children:N})]},b))})]})]})},Fe=({devTools:d})=>{const[t,s]=x.useState(d.getLayoutDebugInfo()),[a,g]=x.useState(!1),[r,o]=x.useState(null),[p,v]=x.useState(!1),[l,f]=x.useState({});x.useEffect(()=>{const m=setInterval(()=>{s(d.getLayoutDebugInfo())},1e3);return()=>clearInterval(m)},[d]),x.useEffect(()=>{(async()=>{try{const k=await fetch("/api/admin/permissions",{headers:{Authorization:`Bearer ${localStorage.getItem("auth_token")}`,Accept:"application/json"}});if(k.ok){const b=await k.json(),N={},C=w=>{w.forEach(S=>{N[S.identifier]=S.name,S.children?.length&&C(S.children)})};Object.values(b.data?.permissions||{}).forEach(w=>{w.permissions&&C(w.permissions)}),f(N)}}catch(k){console.warn("[G7DevTools] 권한 목록 조회 실패:",k)}})()},[]);const c=t.current,h=c?.layoutJson,y=t.history,n=t.stats,i=h?[{key:"components",label:"컴포넌트",count:Array.isArray(h.components)?h.components.length:0},{key:"data_sources",label:"데이터소스",count:Array.isArray(h.data_sources)?h.data_sources.length:0},{key:"computed",label:"Computed",count:h.computed?Object.keys(h.computed).length:0},{key:"defines",label:"Defines",count:h.defines?Object.keys(h.defines).length:0},{key:"slots",label:"Slots",count:h.slots?Object.keys(h.slots).length:0},{key:"modals",label:"Modals",count:h.modals?Object.keys(h.modals).length:0},{key:"init_actions",label:"초기화 액션",count:Array.isArray(h.init_actions)?h.init_actions.length:0},{key:"scripts",label:"스크립트",count:Array.isArray(h.scripts)?h.scripts.length:0},{key:"meta",label:"메타데이터",count:h.meta?Object.keys(h.meta).length:0},{key:"errorHandling",label:"에러핸들링",count:h.errorHandling?Object.keys(h.errorHandling).length:0},{key:"permissions",label:"권한",count:Array.isArray(h.permissions)?h.permissions.length:0}]:[],u=m=>{navigator.clipboard.writeText(JSON.stringify(m,null,2))};return c?e.jsxs("div",{className:"g7dt-space-y-4",children:[e.jsxs("div",{className:"g7dt-card",children:[e.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-2",children:"📊 로드 통계"}),e.jsxs("div",{className:"g7dt-grid-3",children:[e.jsxs("div",{className:"g7dt-stat-item",children:[e.jsx("span",{className:"g7dt-text-muted",children:"총 로드:"}),e.jsx("span",{className:"g7dt-text-blue",children:n.totalLoads})]}),e.jsxs("div",{className:"g7dt-stat-item",children:[e.jsx("span",{className:"g7dt-text-muted",children:"캐시 히트:"}),e.jsx("span",{className:"g7dt-text-green",children:n.cacheHits})]}),e.jsxs("div",{className:"g7dt-stat-item",children:[e.jsx("span",{className:"g7dt-text-muted",children:"API 로드:"}),e.jsx("span",{className:"g7dt-text-yellow",children:n.apiLoads})]})]})]}),e.jsxs("div",{className:"g7dt-card",children:[e.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2",children:[e.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold",children:"📋 현재 레이아웃"}),e.jsxs("div",{className:"g7dt-flex g7dt-gap-2",children:[e.jsx("button",{onClick:()=>u(h),className:"g7dt-btn-small",title:"전체 JSON 복사",children:"📋 복사"}),e.jsx("button",{onClick:()=>g(!a),className:"g7dt-btn-small",children:a?"요약 보기":"전체 보기"})]})]}),e.jsxs("div",{className:"g7dt-space-y-2 g7dt-text-xs",children:[e.jsxs("div",{className:"g7dt-flex g7dt-gap-4",children:[e.jsxs("div",{children:[e.jsx("span",{className:"g7dt-text-muted",children:"경로:"}),e.jsx("span",{className:"g7dt-ml-1 g7dt-text-white g7dt-font-mono",children:c.layoutPath})]}),e.jsxs("div",{children:[e.jsx("span",{className:"g7dt-text-muted",children:"템플릿:"}),e.jsx("span",{className:"g7dt-ml-1 g7dt-text-blue",children:c.templateId})]})]}),e.jsxs("div",{className:"g7dt-flex g7dt-gap-4",children:[e.jsxs("div",{children:[e.jsx("span",{className:"g7dt-text-muted",children:"버전:"}),e.jsx("span",{className:"g7dt-ml-1 g7dt-text-white",children:c.version||"-"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"g7dt-text-muted",children:"소스:"}),e.jsx("span",{className:`g7dt-ml-1 ${c.source==="cache"?"g7dt-text-green":"g7dt-text-yellow"}`,children:c.source==="cache"?"💾 캐시":"🌐 API"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"g7dt-text-muted",children:"로드 시간:"}),e.jsx("span",{className:"g7dt-ml-1 g7dt-text-white",children:c.loadedAt?new Date(c.loadedAt).toLocaleTimeString():"-"})]})]}),e.jsx("div",{className:"g7dt-flex g7dt-gap-4 g7dt-mt-2",children:e.jsxs("div",{children:[e.jsx("span",{className:"g7dt-text-muted",children:"권한:"}),h.permissions&&h.permissions.length>0?e.jsxs("span",{className:"g7dt-ml-1 g7dt-text-yellow",children:["🔒 ",h.permissions.map(m=>l[m]||m).join(", ")]}):h.permissions&&h.permissions.length===0?e.jsx("span",{className:"g7dt-ml-1 g7dt-text-green",children:"🌐 공개"}):e.jsx("span",{className:"g7dt-ml-1 g7dt-text-muted",children:"미정의 (부모 상속)"})]})})]})]}),!a&&e.jsxs("div",{className:"g7dt-card",children:[e.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-2",children:"🏗️ 레이아웃 구조"}),e.jsx("div",{className:"g7dt-grid-2",children:i.map(m=>e.jsxs("button",{onClick:()=>o(r===m.key?null:m.key),className:`g7dt-section-btn ${r===m.key?"g7dt-selected":""}`,children:[e.jsx("span",{children:m.label}),e.jsxs("span",{className:"g7dt-text-blue",children:[m.count,"개"]})]},m.key))})]}),(a||r)&&e.jsxs("div",{className:"g7dt-card",children:[e.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2",children:[e.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold",children:a?"📄 전체 레이아웃 JSON":`📎 ${r} 섹션`}),e.jsx("button",{onClick:()=>{a?u(h):r&&h&&u(h[r])},className:"g7dt-btn-small",children:"복사"})]}),r==="permissions"&&!a?e.jsx("div",{className:"g7dt-text-xs",children:h.permissions&&h.permissions.length>0?e.jsxs("table",{className:"g7dt-table g7dt-w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"g7dt-border-b g7dt-border-gray-700",children:[e.jsx("th",{className:"g7dt-text-left g7dt-p-2 g7dt-text-muted",children:"권한 ID"}),e.jsx("th",{className:"g7dt-text-left g7dt-p-2 g7dt-text-muted",children:"명칭"})]})}),e.jsx("tbody",{children:h.permissions.map(m=>e.jsxs("tr",{className:"g7dt-border-b g7dt-border-gray-800",children:[e.jsx("td",{className:"g7dt-p-2 g7dt-font-mono g7dt-text-blue",children:m}),e.jsx("td",{className:"g7dt-p-2 g7dt-text-white",children:l[m]||e.jsx("span",{className:"g7dt-text-muted",children:"-"})})]},m))})]}):h.permissions&&h.permissions.length===0?e.jsx("p",{className:"g7dt-text-muted g7dt-p-2",children:"🌐 공개 레이아웃 (permissions: [])"}):e.jsx("p",{className:"g7dt-text-muted g7dt-p-2",children:"권한 미정의 (부모 레이아웃 상속)"})}):e.jsx("pre",{className:"g7dt-pre g7dt-text-green g7dt-max-h-96 g7dt-overflow-auto",children:JSON.stringify(a?h:r&&h?h[r]:null,null,2)})]}),y.length>0&&e.jsxs("div",{className:"g7dt-card",children:[e.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center g7dt-cursor-pointer",onClick:()=>v(!p),children:[e.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold",children:["📜 로드 이력 (",y.length,")"]}),e.jsx("span",{className:"g7dt-text-muted",children:p?"▼":"▶"})]}),p&&e.jsx("div",{className:"g7dt-mt-2 g7dt-space-y-1",children:y.slice(-20).reverse().map(m=>e.jsxs("div",{className:"g7dt-history-item",children:[e.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center",children:[e.jsx("span",{className:"g7dt-font-mono g7dt-text-xs",children:m.layoutPath}),e.jsx("span",{className:`g7dt-text-xs ${m.source==="cache"?"g7dt-text-green":"g7dt-text-yellow"}`,children:m.source==="cache"?"💾":"🌐"})]}),e.jsxs("div",{className:"g7dt-text-xs g7dt-text-muted",children:[m.templateId," · ",m.loadedAt?new Date(m.loadedAt).toLocaleTimeString():"-"]})]},m.id))})]}),e.jsxs("div",{className:"g7dt-card g7dt-text-xs g7dt-text-muted",children:["💡 레이아웃 캐시 문제가 의심되면:",e.jsxs("ul",{className:"g7dt-ml-4 g7dt-list-disc",children:[e.jsx("li",{children:'"소스" 항목이 💾 캐시인지 🌐 API인지 확인'}),e.jsx("li",{children:"캐시에서 로드된 경우, JSON 내용이 최신인지 확인"}),e.jsxs("li",{children:["문제가 있으면 ",e.jsx("code",{className:"g7dt-code",children:"php artisan template:refresh-layout"})," 실행"]})]})]})]}):e.jsx("div",{className:"g7dt-space-y-4",children:e.jsxs("div",{className:"g7dt-empty-state",children:["현재 로드된 레이아웃이 없습니다.",e.jsx("br",{}),"페이지를 새로고침하거나 라우트를 변경해보세요."]})})},We=({devTools:d})=>{const[t,s]=x.useState(d.getChangeDetectionInfo()),[a,g]=x.useState(null),[r,o]=x.useState(!1),[p,v]=x.useState(new Set);x.useEffect(()=>{const b=setInterval(()=>{s(d.getChangeDetectionInfo())},500);return()=>clearInterval(b)},[d]);const{executionDetails:l,alerts:f,stats:c}=t,h=r?l.filter(b=>b.alerts.length>0||b.stateChanges.length===0):l,y=a?l.find(b=>b.executionId===a):null,n=b=>{v(N=>{const C=new Set(N);return C.has(b)?C.delete(b):C.add(b),C})},i=b=>{switch(b){case"normal":return"✅";case"early-return-condition":return"⏎";case"early-return-validation":return"❌";case"error":return"💥";default:return"❓"}},u=b=>{switch(b){case"no-state-change":return"⚠️";case"no-datasource-change":return"📊";case"expected-not-fulfilled":return"❗";case"object-reference-same":return"🔄";case"early-return-detected":return"⏎";case"async-timing-issue":return"⏱️";default:return"📢"}},m=b=>{switch(b){case"error":return"g7dt-text-red";case"warning":return"g7dt-text-yellow";case"info":return"g7dt-text-blue";default:return"g7dt-text-white"}},k=b=>new Date(b).toLocaleTimeString("ko-KR",{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3});return e.jsxs("div",{className:"g7dt-space-y-4",children:[f.filter(b=>b.severity==="error"||b.severity==="warning").length>0&&e.jsx("div",{className:"g7dt-card",style:{backgroundColor:"#7f1d1d",borderColor:"#991b1b"},children:e.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center",children:[e.jsxs("span",{className:"g7dt-font-bold",children:["⚠️ 변경 감지 알림: ",f.filter(b=>b.severity==="error").length,"개 에러,"," ",f.filter(b=>b.severity==="warning").length,"개 경고"]}),e.jsx("button",{onClick:()=>d.clearChangeDetectionData(),className:"g7dt-btn-small",children:"초기화"})]})}),e.jsxs("div",{className:"g7dt-card",children:[e.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-2",children:"📊 변경 감지 통계"}),e.jsxs("div",{className:"g7dt-grid-3",children:[e.jsxs("div",{className:"g7dt-stat-item",children:[e.jsx("span",{className:"g7dt-text-muted",children:"총 실행:"}),e.jsx("span",{className:"g7dt-text-blue",children:c.totalExecutions})]}),e.jsxs("div",{className:"g7dt-stat-item",children:[e.jsx("span",{className:"g7dt-text-muted",children:"상태 변경 있음:"}),e.jsx("span",{className:"g7dt-text-green",children:c.executionsWithStateChange})]}),e.jsxs("div",{className:"g7dt-stat-item",children:[e.jsx("span",{className:"g7dt-text-muted",children:"상태 변경 없음:"}),e.jsx("span",{className:c.executionsWithoutStateChange>0?"g7dt-text-yellow":"g7dt-text-gray",children:c.executionsWithoutStateChange})]}),e.jsxs("div",{className:"g7dt-stat-item",children:[e.jsx("span",{className:"g7dt-text-muted",children:"Early Return:"}),e.jsx("span",{className:"g7dt-text-orange",children:c.earlyReturnCount})]}),e.jsxs("div",{className:"g7dt-stat-item",children:[e.jsx("span",{className:"g7dt-text-muted",children:"알림:"}),e.jsx("span",{className:c.alertCount>0?"g7dt-text-red":"g7dt-text-gray",children:c.alertCount})]})]})]}),f.length>0&&e.jsxs("div",{className:"g7dt-card",children:[e.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-2",children:"🔔 최근 알림"}),e.jsx("div",{className:"g7dt-space-y-2",style:{maxHeight:"200px",overflowY:"auto"},children:f.slice(-10).reverse().map(b=>e.jsxs("div",{className:"g7dt-list-item",onClick:()=>n(b.id),style:{cursor:"pointer"},children:[e.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-start",children:[e.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[e.jsx("span",{children:u(b.type)}),e.jsx("span",{className:`g7dt-text-xs ${m(b.severity)}`,children:b.message})]}),e.jsx("span",{className:"g7dt-text-xs g7dt-text-muted",children:k(b.timestamp)})]}),p.has(b.id)&&e.jsxs("div",{className:"g7dt-mt-2 g7dt-text-xs g7dt-text-muted g7dt-pl-6",children:[e.jsx("p",{children:b.description}),b.statePath&&e.jsxs("p",{className:"g7dt-mt-1",children:[e.jsx("span",{className:"g7dt-text-cyan",children:"경로:"})," ",b.statePath]}),b.suggestion&&e.jsxs("p",{className:"g7dt-mt-1",children:[e.jsx("span",{className:"g7dt-text-green",children:"제안:"})," ",b.suggestion]}),b.docLink&&e.jsxs("p",{className:"g7dt-mt-1",children:[e.jsx("span",{className:"g7dt-text-blue",children:"문서:"})," ",e.jsx("code",{className:"g7dt-code",children:b.docLink})]})]})]},b.id))})]}),e.jsxs("div",{className:"g7dt-card",children:[e.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center g7dt-mb-2",children:[e.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold",children:"🔧 핸들러 실행 이력"}),e.jsxs("label",{className:"g7dt-flex g7dt-items-center g7dt-gap-2 g7dt-text-xs",children:[e.jsx("input",{type:"checkbox",checked:r,onChange:b=>o(b.target.checked)}),e.jsx("span",{children:"경고만 표시"})]})]}),h.length===0?e.jsxs("div",{className:"g7dt-empty-state",children:["핸들러 실행 이력이 없습니다.",e.jsx("br",{}),"액션을 실행하면 여기에 표시됩니다."]}):e.jsx("div",{className:"g7dt-space-y-1",style:{maxHeight:"300px",overflowY:"auto"},children:h.slice(-20).reverse().map(b=>e.jsxs("div",{className:`g7dt-list-item ${a===b.executionId?"g7dt-selected":""}`,onClick:()=>g(a===b.executionId?null:b.executionId),style:{cursor:"pointer"},children:[e.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center",children:[e.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[e.jsx("span",{children:i(b.exitReason)}),e.jsx("span",{className:"g7dt-text-white g7dt-font-mono g7dt-text-xs",children:b.handlerName}),b.alerts.length>0&&e.jsx("span",{className:"g7dt-badge g7dt-badge-warning",children:b.alerts.length})]}),e.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2 g7dt-text-xs",children:[e.jsxs("span",{className:"g7dt-text-muted",children:["상태: ",b.stateChanges.length]}),e.jsx("span",{className:"g7dt-text-muted",children:b.duration?`${b.duration}ms`:"-"}),e.jsx("span",{className:"g7dt-text-muted",children:k(b.startTime)})]})]}),a===b.executionId&&y&&e.jsxs("div",{className:"g7dt-mt-3 g7dt-pt-3 g7dt-border-t g7dt-border-gray-700",children:[e.jsxs("div",{className:"g7dt-mb-2",children:[e.jsx("span",{className:"g7dt-text-xs g7dt-text-muted",children:"종료 사유: "}),e.jsx("span",{className:"g7dt-text-xs g7dt-text-white",children:y.exitReason||"unknown"}),y.exitLocation&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"g7dt-text-xs g7dt-text-muted g7dt-ml-2",children:"위치: "}),e.jsx("code",{className:"g7dt-code g7dt-text-xs",children:y.exitLocation})]})]}),y.exitDescription&&e.jsx("div",{className:"g7dt-mb-2 g7dt-text-xs g7dt-text-muted",children:y.exitDescription}),y.stateChanges.length>0&&e.jsxs("div",{className:"g7dt-mb-2",children:[e.jsxs("span",{className:"g7dt-text-xs g7dt-font-bold g7dt-text-green",children:["상태 변경 (",y.stateChanges.length,")"]}),e.jsx("div",{className:"g7dt-mt-1 g7dt-space-y-1",children:y.stateChanges.map(N=>e.jsxs("div",{className:"g7dt-text-xs g7dt-pl-2",children:[e.jsx("span",{className:"g7dt-text-cyan",children:N.path}),e.jsxs("span",{className:"g7dt-text-muted",children:[" (",N.changeType,")"]}),N.comparison.changedKeys&&e.jsxs("span",{className:"g7dt-text-muted g7dt-ml-1",children:["[변경: ",N.comparison.changedKeys.join(", "),"]"]})]},N.id))})]}),y.dataSourceChanges.length>0&&e.jsxs("div",{className:"g7dt-mb-2",children:[e.jsxs("span",{className:"g7dt-text-xs g7dt-font-bold g7dt-text-blue",children:["데이터소스 변경 (",y.dataSourceChanges.length,")"]}),e.jsx("div",{className:"g7dt-mt-1 g7dt-space-y-1",children:y.dataSourceChanges.map((N,C)=>e.jsxs("div",{className:"g7dt-text-xs g7dt-pl-2",children:[e.jsx("span",{className:"g7dt-text-cyan",children:N.dataSourceId}),e.jsxs("span",{className:"g7dt-text-muted",children:[" ","(",N.changeType,": ",N.previousStatus," → ",N.newStatus,")"]})]},C))})]}),y.expectedChanges&&e.jsxs("div",{className:"g7dt-mb-2",children:[e.jsx("span",{className:"g7dt-text-xs g7dt-font-bold g7dt-text-yellow",children:"기대 변경"}),e.jsxs("div",{className:"g7dt-mt-1 g7dt-text-xs g7dt-pl-2 g7dt-text-muted",children:["상태: ",y.expectedChanges.expectedStatePaths.join(", ")||"없음",e.jsx("br",{}),"데이터소스: ",y.expectedChanges.expectedDataSources.join(", ")||"없음"]})]}),y.alerts.length>0&&e.jsxs("div",{children:[e.jsxs("span",{className:"g7dt-text-xs g7dt-font-bold g7dt-text-red",children:["알림 (",y.alerts.length,")"]}),e.jsx("div",{className:"g7dt-mt-1 g7dt-space-y-1",children:y.alerts.map(N=>e.jsxs("div",{className:"g7dt-text-xs g7dt-pl-2",children:[e.jsx("span",{children:u(N.type)}),e.jsx("span",{className:`g7dt-ml-1 ${m(N.severity)}`,children:N.message})]},N.id))})]})]})]},b.executionId))})]}),e.jsxs("div",{className:"g7dt-card",children:[e.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-2",children:"💡 변경 감지 가이드"}),e.jsxs("ul",{className:"g7dt-help-list",children:[e.jsx("li",{children:"핸들러 실행 후 상태 변경이 없으면 ⚠️ 경고가 표시됩니다"}),e.jsx("li",{children:"early return으로 종료된 경우 ⏎ 아이콘으로 표시됩니다"}),e.jsx("li",{children:"객체 변경 시 참조가 동일하면 🔄 경고가 발생합니다"}),e.jsx("li",{children:"문제 해결: exitLocation 확인 → 조건문 검토 → 불변성 확인"})]})]})]})},Ve=({devTools:d})=>{const[t,s]=x.useState(null),[a,g]=x.useState(null),[r,o]=x.useState("all"),p=x.useCallback(()=>{s(d.getStaleClosureTrackingInfo())},[d]);if(x.useEffect(()=>{p();const n=setInterval(p,2e3);return()=>clearInterval(n)},[p]),!t)return e.jsx("div",{className:"g7dt-empty-state",children:"로딩 중..."});const{warnings:v,stats:l}=t,f=v.filter(n=>r==="all"?!0:n.severity===r),c=a?v.find(n=>n.id===a):null,h=n=>{switch(n){case"error":return"❌";case"warning":return"⚠️";default:return"❓"}},y=n=>{switch(n){case"state-changed-during-async":return"⏳";case"captured-in-callback":return"📸";case"stale-in-handler":return"🔄";default:return"❓"}};return e.jsxs("div",{className:"g7dt-space-y-4",children:[e.jsxs("div",{className:"g7dt-card",children:[e.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"Stale Closure 통계"}),e.jsxs("div",{className:"g7dt-stats-grid-3",children:[e.jsxs("div",{className:"g7dt-text-center",children:[e.jsx("div",{className:"g7dt-text-2xl g7dt-font-bold g7dt-text-yellow",children:l.totalWarnings||0}),e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"총 경고"})]}),e.jsxs("div",{className:"g7dt-text-center",children:[e.jsx("div",{className:"g7dt-text-2xl g7dt-font-bold g7dt-text-red",children:l.warningsBySeverity?.error||0}),e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"에러"})]}),e.jsxs("div",{className:"g7dt-text-center",children:[e.jsx("div",{className:"g7dt-text-2xl g7dt-font-bold g7dt-text-orange",children:l.warningsBySeverity?.warning||0}),e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"경고"})]})]})]}),l.warningsByType&&Object.keys(l.warningsByType).length>0&&e.jsxs("div",{className:"g7dt-card",children:[e.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"타입별 분포"}),e.jsx("div",{className:"g7dt-space-y-2",children:Object.entries(l.warningsByType).map(([n,i])=>e.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-text-xs",children:[e.jsxs("span",{className:"g7dt-text-muted",children:[y(n)," ",n]}),e.jsx("span",{className:"g7dt-text-white g7dt-font-mono",children:i})]},n))})]}),e.jsx("div",{className:"g7dt-card",children:e.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[e.jsx("span",{className:"g7dt-text-xs g7dt-text-muted",children:"심각도:"}),e.jsxs("select",{value:r,onChange:n=>o(n.target.value),className:"g7dt-select",children:[e.jsx("option",{value:"all",children:"전체"}),e.jsx("option",{value:"error",children:"에러"}),e.jsx("option",{value:"warning",children:"경고"})]}),e.jsxs("span",{className:"g7dt-text-xs g7dt-text-muted g7dt-ml-auto",children:[f.length,"개 표시"]})]})}),e.jsxs("div",{className:"g7dt-card",children:[e.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"Stale Closure 경고"}),f.length===0?e.jsx("div",{className:"g7dt-empty-state g7dt-text-green",children:"✅ Stale Closure 경고가 없습니다"}):e.jsx("div",{className:"g7dt-space-y-2 g7dt-max-h-60 g7dt-overflow-y-auto",children:f.slice().reverse().map(n=>e.jsxs("div",{className:`g7dt-list-item g7dt-cursor-pointer ${a===n.id?"g7dt-selected":""}`,onClick:()=>g(a===n.id?null:n.id),children:[e.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[e.jsx("span",{children:h(n.severity)}),e.jsx("span",{children:y(n.type)}),e.jsx("span",{className:"g7dt-text-xs g7dt-text-white g7dt-truncate",children:n.location}),e.jsx("span",{className:"g7dt-text-xs g7dt-text-muted g7dt-ml-auto",children:new Date(n.timestamp).toLocaleTimeString()})]}),e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mt-1 g7dt-truncate",children:n.statePath})]},n.id))})]}),c&&e.jsxs("div",{className:"g7dt-card g7dt-border-yellow",children:[e.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:[h(c.severity)," 경고 상세"]}),e.jsxs("div",{className:"g7dt-space-y-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"위치"}),e.jsx("div",{className:"g7dt-text-sm g7dt-text-white g7dt-mono",children:c.location})]}),e.jsxs("div",{children:[e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"타입"}),e.jsxs("div",{className:"g7dt-text-sm g7dt-text-white",children:[y(c.type)," ",c.type]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"상태 경로"}),e.jsx("div",{className:"g7dt-text-sm g7dt-text-yellow g7dt-mono",children:c.statePath})]}),e.jsxs("div",{className:"g7dt-grid-2 g7dt-gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"캡처된 값"}),e.jsx("pre",{className:"g7dt-code-block g7dt-text-red",children:JSON.stringify(c.capturedValue,null,2)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"현재 값"}),e.jsx("pre",{className:"g7dt-code-block g7dt-text-green",children:JSON.stringify(c.currentValue,null,2)})]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"시간 차이"}),e.jsxs("div",{className:"g7dt-text-sm g7dt-text-white",children:[c.timeDiff,"ms"]})]}),c.suggestion&&e.jsxs("div",{className:"g7dt-bg-blue-dark g7dt-p-2 g7dt-rounded",children:[e.jsx("div",{className:"g7dt-text-xs g7dt-text-blue",children:"💡 제안"}),e.jsx("div",{className:"g7dt-text-sm g7dt-text-white g7dt-mt-1",children:c.suggestion})]})]})]})]})},Be=({devTools:d})=>{const[t,s]=x.useState(null),[a,g]=x.useState(null),[r,o]=x.useState("all"),p=x.useCallback(()=>{s(d.getNestedContextTrackingInfo())},[d]);if(x.useEffect(()=>{p();const n=setInterval(p,2e3);return()=>clearInterval(n)},[p]),!t)return e.jsx("div",{className:"g7dt-empty-state",children:"로딩 중..."});const{contexts:v,stats:l}=t,f=v.filter(n=>r==="all"?!0:n.componentType===r),c=a?v.find(n=>n.id===a):null,h=n=>{switch(n){case"expandChildren":return"📂";case"cellChildren":return"📊";case"iteration":return"🔄";case"modal":return"🪟";case"slot":return"🔲";default:return"❓"}},y=n=>"│".repeat(Math.max(0,n-1))+(n>0?"├─":"");return e.jsxs("div",{className:"g7dt-space-y-4",children:[e.jsxs("div",{className:"g7dt-card",children:[e.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"Nested Context 통계"}),e.jsxs("div",{className:"g7dt-stats-grid-3",children:[e.jsxs("div",{className:"g7dt-text-center",children:[e.jsx("div",{className:"g7dt-text-2xl g7dt-font-bold g7dt-text-blue",children:l.totalContexts||0}),e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"총 컨텍스트"})]}),e.jsxs("div",{className:"g7dt-text-center",children:[e.jsx("div",{className:"g7dt-text-2xl g7dt-font-bold g7dt-text-purple",children:l.maxDepth||0}),e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"최대 깊이"})]}),e.jsxs("div",{className:"g7dt-text-center",children:[e.jsx("div",{className:"g7dt-text-2xl g7dt-font-bold g7dt-text-red",children:l.failedAccessCount||0}),e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"접근 오류"})]})]})]}),l.byType&&Object.keys(l.byType).length>0&&e.jsxs("div",{className:"g7dt-card",children:[e.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"타입별 분포"}),e.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-3",children:Object.entries(l.byType).map(([n,i])=>e.jsxs("div",{className:`g7dt-badge g7dt-cursor-pointer ${r===n?"g7dt-badge-selected":""}`,onClick:()=>o(r===n?"all":n),children:[h(n)," ",n,": ",i]},n))})]}),e.jsx("div",{className:"g7dt-card",children:e.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[e.jsx("span",{className:"g7dt-text-xs g7dt-text-muted",children:"타입:"}),e.jsxs("select",{value:r,onChange:n=>o(n.target.value),className:"g7dt-select",children:[e.jsx("option",{value:"all",children:"전체"}),e.jsx("option",{value:"expandChildren",children:"expandChildren"}),e.jsx("option",{value:"cellChildren",children:"cellChildren"}),e.jsx("option",{value:"iteration",children:"iteration"}),e.jsx("option",{value:"modal",children:"modal"}),e.jsx("option",{value:"slot",children:"slot"})]}),e.jsxs("span",{className:"g7dt-text-xs g7dt-text-muted g7dt-ml-auto",children:[f.length,"개 표시"]})]})}),e.jsxs("div",{className:"g7dt-card",children:[e.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"컨텍스트 목록"}),f.length===0?e.jsx("div",{className:"g7dt-empty-state",children:"추적된 Nested Context가 없습니다"}):e.jsx("div",{className:"g7dt-space-y-2 g7dt-max-h-60 g7dt-overflow-y-auto",children:f.slice().reverse().map(n=>{const i=n.accessAttempts?.some(m=>!m.found),u=n.mergedContext?.all||[];return e.jsxs("div",{className:`g7dt-list-item g7dt-cursor-pointer ${a===n.id?"g7dt-selected":""} ${i?"g7dt-border-red":""}`,onClick:()=>g(a===n.id?null:n.id),children:[e.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[e.jsx("span",{className:"g7dt-text-muted g7dt-mono g7dt-text-xs",children:y(n.depth)}),e.jsx("span",{children:h(n.componentType)}),e.jsx("span",{className:"g7dt-text-xs g7dt-text-white",children:n.componentId||n.componentType}),i&&e.jsx("span",{className:"g7dt-text-red g7dt-text-xs",children:"⚠️ 오류"}),e.jsxs("span",{className:"g7dt-text-xs g7dt-text-muted g7dt-ml-auto",children:["깊이: ",n.depth]})]}),e.jsxs("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mt-1",children:["변수: ",u.slice(0,5).join(", "),u.length>5&&"..."]})]},n.id)})})]}),c&&e.jsxs("div",{className:"g7dt-card g7dt-border-blue",children:[e.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:[h(c.componentType)," 컨텍스트 상세"]}),e.jsxs("div",{className:"g7dt-space-y-3",children:[e.jsxs("div",{className:"g7dt-grid-2 g7dt-gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"타입"}),e.jsx("div",{className:"g7dt-text-sm g7dt-text-white",children:c.componentType})]}),e.jsxs("div",{children:[e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"깊이"}),e.jsx("div",{className:"g7dt-text-sm g7dt-text-white",children:c.depth})]})]}),c.componentId&&e.jsxs("div",{children:[e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"컴포넌트 ID"}),e.jsx("div",{className:"g7dt-text-sm g7dt-text-blue g7dt-mono",children:c.componentId})]}),c.parentId&&e.jsxs("div",{children:[e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"부모 컨텍스트"}),e.jsx("div",{className:"g7dt-text-sm g7dt-text-purple g7dt-mono",children:c.parentId})]}),e.jsxs("div",{children:[e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mb-2",children:"사용 가능한 변수"}),e.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-1",children:(c.mergedContext?.all||[]).map(n=>e.jsx("span",{className:"g7dt-badge g7dt-badge-blue g7dt-text-xs",children:n},n))})]}),c.ownContext?.added&&c.ownContext.added.length>0&&e.jsxs("div",{children:[e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mb-2",children:"추가된 변수 (이 컨텍스트에서)"}),e.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-1",children:c.ownContext.added.map(n=>e.jsxs("span",{className:"g7dt-badge g7dt-badge-green g7dt-text-xs",children:["+ ",n]},n))})]}),c.accessAttempts&&c.accessAttempts.length>0&&e.jsxs("div",{children:[e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mb-2",children:"접근 시도"}),e.jsx("div",{className:"g7dt-space-y-1",children:c.accessAttempts.slice(0,10).map((n,i)=>e.jsxs("div",{className:`g7dt-flex g7dt-justify-between g7dt-text-xs ${n.found?"":"g7dt-text-red"}`,children:[e.jsx("span",{className:"g7dt-mono",children:n.path}),e.jsx("span",{children:n.found?"✓":"✕"})]},i))})]})]})]})]})},Ge=({devTools:d})=>{const[t,s]=x.useState(null),[a,g]=x.useState(null),[r,o]=x.useState(null),[p,v]=x.useState("modals"),l=x.useCallback(()=>{s(d.getModalStateScopeTrackingInfo())},[d]);if(x.useEffect(()=>{l();const N=setInterval(l,2e3);return()=>clearInterval(N)},[l]),!t)return e.jsx("div",{className:"g7dt-empty-state",children:"로딩 중..."});const{modals:f,issues:c,relations:h,changeLogs:y,stats:n}=t,i=a?f.find(N=>N.modalId===a):null,u=r?c.find(N=>N.id===r):null,m=N=>{switch(N){case"isolated":return"🔒";case"shared":return"🔓";case"inherited":return"📥";default:return"❓"}},k=N=>{switch(N){case"state-leakage":return"💧";case"isolation-violation":return"🔓";case"parent-mutation":return"👆";case"orphaned-state":return"👻";case"scope-mismatch":return"🔀";case"cleanup-failure":return"🧹";case"missing-definition":return"🚫";default:return"❓"}},b=N=>{switch(N){case"error":return"❌";case"warning":return"⚠️";default:return"❓"}};return e.jsxs("div",{className:"g7dt-space-y-4",children:[e.jsxs("div",{className:"g7dt-card",children:[e.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"모달 상태 스코프 통계"}),e.jsxs("div",{className:"g7dt-stats-grid-3",children:[e.jsxs("div",{className:"g7dt-text-center",children:[e.jsx("div",{className:"g7dt-text-2xl g7dt-font-bold g7dt-text-blue",children:n.totalModals}),e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"총 모달"})]}),e.jsxs("div",{className:"g7dt-text-center",children:[e.jsx("div",{className:"g7dt-text-2xl g7dt-font-bold g7dt-text-green",children:n.openModals}),e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"열린 모달"})]}),e.jsxs("div",{className:"g7dt-text-center",children:[e.jsx("div",{className:"g7dt-text-2xl g7dt-font-bold g7dt-text-red",children:n.totalIssues}),e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"이슈"})]})]})]}),e.jsxs("div",{className:"g7dt-card",children:[e.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"스코프별 / 이슈별"}),e.jsxs("div",{className:"g7dt-grid-2 g7dt-gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mb-2",children:"스코프 타입"}),e.jsx("div",{className:"g7dt-space-y-1",children:Object.entries(n.byScope).map(([N,C])=>e.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-text-xs",children:[e.jsxs("span",{children:[m(N)," ",N]}),e.jsx("span",{className:"g7dt-font-mono",children:C})]},N))})]}),e.jsxs("div",{children:[e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mb-2",children:"이슈 타입"}),e.jsxs("div",{className:"g7dt-space-y-1",children:[Object.entries(n.issuesByType).filter(([N,C])=>C>0).map(([N,C])=>e.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-text-xs",children:[e.jsxs("span",{children:[k(N)," ",N]}),e.jsx("span",{className:"g7dt-font-mono g7dt-text-red",children:C})]},N)),Object.values(n.issuesByType).every(N=>N===0)&&e.jsx("div",{className:"g7dt-text-xs g7dt-text-green",children:"✅ 이슈 없음"})]})]})]})]}),e.jsx("div",{className:"g7dt-card",children:e.jsxs("div",{className:"g7dt-flex g7dt-gap-2",children:[e.jsxs("button",{className:`g7dt-tab-button ${p==="modals"?"g7dt-tab-active":""}`,onClick:()=>v("modals"),children:["🪟 모달 (",f.length,")"]}),e.jsxs("button",{className:`g7dt-tab-button ${p==="issues"?"g7dt-tab-active":""}`,onClick:()=>v("issues"),children:["⚠️ 이슈 (",c.length,")"]}),e.jsxs("button",{className:`g7dt-tab-button ${p==="logs"?"g7dt-tab-active":""}`,onClick:()=>v("logs"),children:["📝 로그 (",y.length,")"]})]})}),p==="modals"&&e.jsxs("div",{className:"g7dt-card",children:[e.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"모달 목록"}),f.length===0?e.jsx("div",{className:"g7dt-empty-state",children:"추적된 모달이 없습니다"}):e.jsx("div",{className:"g7dt-space-y-2 g7dt-max-h-60 g7dt-overflow-y-auto",children:f.map(N=>{const C=c.some(w=>w.modalId===N.modalId);return e.jsx("div",{className:`g7dt-list-item g7dt-cursor-pointer ${a===N.modalId?"g7dt-selected":""} ${C?"g7dt-border-red":""}`,onClick:()=>g(a===N.modalId?null:N.modalId),children:e.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[e.jsx("span",{children:N.closedAt===null?"📭":"📪"}),e.jsx("span",{children:m(N.scopeType)}),e.jsx("span",{className:"g7dt-text-xs g7dt-text-white",children:N.modalName}),C&&e.jsx("span",{className:"g7dt-text-red",children:"⚠️"}),e.jsxs("span",{className:"g7dt-text-xs g7dt-text-muted g7dt-ml-auto",children:["변경: ",N.stateChangeCount]})]})},N.modalId)})})]}),p==="issues"&&e.jsxs("div",{className:"g7dt-card",children:[e.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"이슈 목록"}),c.length===0?e.jsx("div",{className:"g7dt-empty-state g7dt-text-green",children:"✅ 모달 상태 이슈가 없습니다"}):e.jsx("div",{className:"g7dt-space-y-2 g7dt-max-h-60 g7dt-overflow-y-auto",children:c.slice().reverse().map(N=>e.jsxs("div",{className:`g7dt-list-item g7dt-cursor-pointer ${r===N.id?"g7dt-selected":""}`,onClick:()=>o(r===N.id?null:N.id),children:[e.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[e.jsx("span",{children:b(N.severity)}),e.jsx("span",{children:k(N.type)}),e.jsx("span",{className:"g7dt-text-xs g7dt-text-white",children:N.modalName}),e.jsx("span",{className:"g7dt-text-xs g7dt-text-muted g7dt-ml-auto",children:new Date(N.timestamp).toLocaleTimeString()})]}),e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mt-1 g7dt-truncate",children:N.description})]},N.id))})]}),p==="logs"&&e.jsxs("div",{className:"g7dt-card",children:[e.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"상태 변경 로그"}),y.length===0?e.jsx("div",{className:"g7dt-empty-state",children:"상태 변경 로그가 없습니다"}):e.jsx("div",{className:"g7dt-space-y-2 g7dt-max-h-60 g7dt-overflow-y-auto",children:y.slice().reverse().slice(0,50).map(N=>e.jsxs("div",{className:`g7dt-list-item ${N.violatesIsolation?"g7dt-border-red":""}`,children:[e.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2",children:[e.jsx("span",{className:"g7dt-text-xs g7dt-text-white",children:N.modalName}),e.jsx("span",{className:"g7dt-text-xs g7dt-text-blue g7dt-mono",children:N.stateKey}),N.violatesIsolation&&e.jsx("span",{className:"g7dt-text-red",children:"⚠️ 격리 위반"}),e.jsx("span",{className:"g7dt-text-xs g7dt-text-muted g7dt-ml-auto",children:new Date(N.timestamp).toLocaleTimeString()})]}),e.jsxs("div",{className:"g7dt-flex g7dt-gap-2 g7dt-text-xs g7dt-mt-1",children:[e.jsx("span",{className:"g7dt-text-red g7dt-truncate",style:{maxWidth:"45%"},children:JSON.stringify(N.previousValue)}),e.jsx("span",{className:"g7dt-text-muted",children:"→"}),e.jsx("span",{className:"g7dt-text-green g7dt-truncate",style:{maxWidth:"45%"},children:JSON.stringify(N.newValue)})]})]},N.id))})]}),i&&p==="modals"&&e.jsxs("div",{className:"g7dt-card g7dt-border-blue",children:[e.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:[m(i.scopeType)," 모달 상세: ",i.modalName]}),e.jsxs("div",{className:"g7dt-space-y-3",children:[e.jsxs("div",{className:"g7dt-grid-2 g7dt-gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"스코프"}),e.jsxs("div",{className:"g7dt-text-sm g7dt-text-white",children:[m(i.scopeType)," ",i.scopeType]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"상태"}),e.jsx("div",{className:"g7dt-text-sm g7dt-text-white",children:i.closedAt===null?"📭 열림":"📪 닫힘"})]})]}),i.parentModalId&&e.jsxs("div",{children:[e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"부모 모달"}),e.jsx("div",{className:"g7dt-text-sm g7dt-text-purple g7dt-mono",children:i.parentModalId})]}),e.jsxs("div",{children:[e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"상태 변경 횟수"}),e.jsx("div",{className:"g7dt-text-sm g7dt-text-white",children:i.stateChangeCount})]}),i.isolatedStateKeys.length>0&&e.jsxs("div",{children:[e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mb-1",children:"격리된 상태 키"}),e.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-1",children:i.isolatedStateKeys.map(N=>e.jsxs("span",{className:"g7dt-badge g7dt-badge-red g7dt-text-xs",children:["🔒 ",N]},N))})]}),i.sharedStateKeys.length>0&&e.jsxs("div",{children:[e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted g7dt-mb-1",children:"공유된 상태 키"}),e.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-1",children:i.sharedStateKeys.map(N=>e.jsxs("span",{className:"g7dt-badge g7dt-badge-blue g7dt-text-xs",children:["🔓 ",N]},N))})]})]})]}),u&&p==="issues"&&e.jsxs("div",{className:"g7dt-card g7dt-border-red",children:[e.jsxs("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:[b(u.severity)," 이슈 상세"]}),e.jsxs("div",{className:"g7dt-space-y-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"타입"}),e.jsxs("div",{className:"g7dt-text-sm g7dt-text-white",children:[k(u.type)," ",u.type]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"설명"}),e.jsx("div",{className:"g7dt-text-sm g7dt-text-white",children:u.description})]}),u.affectedStateKeys.length>0&&e.jsxs("div",{children:[e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"영향 받는 상태 키"}),e.jsx("div",{className:"g7dt-flex g7dt-flex-wrap g7dt-gap-1 g7dt-mt-1",children:u.affectedStateKeys.map(N=>e.jsx("span",{className:"g7dt-badge g7dt-text-xs",children:N},N))})]}),u.leakedValue!==void 0&&e.jsxs("div",{children:[e.jsx("div",{className:"g7dt-text-xs g7dt-text-muted",children:"유출된 값"}),e.jsx("pre",{className:"g7dt-code-block g7dt-text-red",children:JSON.stringify(u.leakedValue,null,2)})]})]})]}),h.length>0&&e.jsxs("div",{className:"g7dt-card",children:[e.jsx("h3",{className:"g7dt-text-sm g7dt-font-bold g7dt-mb-3",children:"모달 관계"}),e.jsx("div",{className:"g7dt-space-y-2",children:h.map((N,C)=>e.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-gap-2 g7dt-text-xs",children:[e.jsx("span",{className:"g7dt-text-purple",children:N.parentModalId}),e.jsx("span",{className:"g7dt-text-muted",children:"→"}),e.jsx("span",{className:"g7dt-text-blue",children:N.childModalId}),e.jsx("span",{className:"g7dt-badge g7dt-text-xs g7dt-ml-auto",children:N.relationType})]},C))})]})]})},Je=({devTools:d})=>{const[t,s]=x.useState("definitions"),[a,g]=x.useState(null),[r,o]=x.useState(""),p=x.useCallback(()=>{d&&g(d.getNamedActionTrackingInfo())},[d]);if(x.useEffect(()=>{p();const n=setInterval(p,2e3);return()=>clearInterval(n)},[p]),!a)return e.jsx("div",{className:"g7dt-empty-message g7dt-py-4",children:"데이터 로딩 중..."});const{definitions:v,refLogs:l,stats:f}=a,c=Object.keys(v),h=c.filter(n=>!r||n.toLowerCase().includes(r.toLowerCase())||v[n]?.handler?.toLowerCase().includes(r.toLowerCase())),y=l.filter(n=>!r||n.actionRefName.toLowerCase().includes(r.toLowerCase())||n.resolvedHandler.toLowerCase().includes(r.toLowerCase()));return e.jsxs("div",{className:"g7dt-space-y-4",children:[e.jsxs("div",{className:"g7dt-grid g7dt-grid-cols-3 g7dt-gap-2",children:[e.jsxs("div",{className:"g7dt-stat-card",children:[e.jsx("div",{className:"g7dt-stat-value",children:f.totalDefinitions}),e.jsx("div",{className:"g7dt-stat-label",children:"정의"})]}),e.jsxs("div",{className:"g7dt-stat-card",children:[e.jsx("div",{className:"g7dt-stat-value",children:f.totalRefs}),e.jsx("div",{className:"g7dt-stat-label",children:"참조"})]}),e.jsxs("div",{className:"g7dt-stat-card",children:[e.jsx("div",{className:"g7dt-stat-value",style:{color:f.unusedDefinitions.length>0?"#f59e0b":"#10b981"},children:f.unusedDefinitions.length}),e.jsx("div",{className:"g7dt-stat-label",children:"미사용"})]})]}),e.jsxs("div",{className:"g7dt-flex g7dt-gap-2",children:[e.jsxs("button",{onClick:()=>s("definitions"),className:t==="definitions"?"g7dt-filter-btn g7dt-filter-active":"g7dt-filter-btn",children:["정의 목록 (",c.length,")"]}),e.jsxs("button",{onClick:()=>s("refs"),className:t==="refs"?"g7dt-filter-btn g7dt-filter-active":"g7dt-filter-btn",children:["참조 이력 (",l.length,")"]}),e.jsx("button",{onClick:p,className:"g7dt-filter-btn",title:"새로고침",children:"↻"})]}),e.jsx("input",{type:"text",placeholder:t==="definitions"?"액션 이름 검색...":"actionRef 검색...",value:r,onChange:n=>o(n.target.value),className:"g7dt-input g7dt-w-full"}),t==="definitions"&&e.jsx("div",{className:"g7dt-space-y-1",children:h.length===0?e.jsx("div",{className:"g7dt-empty-message g7dt-py-4",children:c.length===0?"정의된 named_actions가 없습니다":"검색 결과 없음"}):h.map(n=>{const i=v[n],u=f.refCountByName[n]||0,m=f.unusedDefinitions.includes(n);return e.jsxs("div",{className:"g7dt-card",style:{borderLeft:m?"3px solid #f59e0b":"3px solid #10b981"},children:[e.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center",children:[e.jsxs("div",{children:[e.jsx("span",{className:"g7dt-font-bold",children:n}),e.jsxs("span",{className:"g7dt-text-muted g7dt-ml-2",children:["→ ",i.handler]})]}),e.jsxs("span",{className:"g7dt-badge",title:"참조 횟수",children:[u,"회"]})]}),i.params&&e.jsxs("details",{className:"g7dt-mt-1",children:[e.jsx("summary",{className:"g7dt-text-xs g7dt-text-muted g7dt-cursor-pointer",children:"params"}),e.jsx("pre",{className:"g7dt-pre g7dt-text-xs g7dt-mt-1",style:{maxHeight:"200px",overflow:"auto"},children:JSON.stringify(i.params,null,2)})]}),m&&e.jsx("div",{className:"g7dt-text-xs",style:{color:"#f59e0b",marginTop:"4px"},children:"⚠ 미사용 정의"})]},n)})}),t==="refs"&&e.jsx("div",{className:"g7dt-space-y-1",children:y.length===0?e.jsx("div",{className:"g7dt-empty-message g7dt-py-4",children:l.length===0?"actionRef 해석 이력이 없습니다":"검색 결과 없음"}):[...y].reverse().map(n=>e.jsx("div",{className:"g7dt-card",children:e.jsxs("div",{className:"g7dt-flex g7dt-justify-between g7dt-items-center",children:[e.jsxs("div",{children:[e.jsx("span",{className:"g7dt-font-bold",children:n.actionRefName}),e.jsxs("span",{className:"g7dt-text-muted g7dt-ml-2",children:["→ ",n.resolvedHandler]})]}),e.jsx("span",{className:"g7dt-text-xs g7dt-text-muted",children:new Date(n.timestamp).toLocaleTimeString()})]})},n.id))})]})},ge=()=>{x.useEffect(()=>{ve()},[]);const d=x.useRef(oe()),[t,s]=x.useState(d.current.isOpen??!1),[a,g]=x.useState(!1),[r,o]=x.useState("state"),[p,v]=x.useState({_global:{},_local:{},_computed:{}}),[l,f]=x.useState([]),[c,h]=x.useState({hits:0,misses:0,entries:0,hitRate:0}),[y,n]=x.useState(!1),[i,u]=x.useState(d.current.position??{x:-1,y:-1}),[m,k]=x.useState(!1),b=x.useRef(null),N=x.useRef(null),[C,w]=x.useState(d.current.size??{width:Ne,height:ue}),[S,z]=x.useState(!1),[O,K]=x.useState(null),L=x.useRef(null),[V,he]=x.useState(!1),q=x.useRef(null),I=G.getInstance(),se=R();x.useEffect(()=>{if(i.x===-1&&i.y===-1){const T=window.innerWidth-C.width-16;u({x:T,y:16})}},[i,C.width]),x.useEffect(()=>{if(i.x===-1&&i.y===-1||m||S)return;const T=setTimeout(()=>{ie({position:i,size:C})},300);return()=>clearTimeout(T)},[i,C,m,S]),x.useEffect(()=>{ie({isOpen:t})},[t]);const Ke=x.useCallback(T=>{T.target.tagName!=="BUTTON"&&(k(!0),b.current={x:T.clientX,y:T.clientY,posX:i.x,posY:i.y},T.preventDefault())},[i]);x.useEffect(()=>{if(!m)return;const T=_=>{if(!b.current)return;const Y=_.clientX-b.current.x,X=_.clientY-b.current.y;let j=b.current.posX+Y,A=b.current.posY+X;const H=window.innerWidth-C.width,F=window.innerHeight-C.height;j=Math.max(0,Math.min(j,H)),A=Math.max(0,Math.min(A,F)),u({x:j,y:A})},D=()=>{k(!1),b.current=null};return document.addEventListener("mousemove",T),document.addEventListener("mouseup",D),()=>{document.removeEventListener("mousemove",T),document.removeEventListener("mouseup",D)}},[m,C.width,C.height]);const M=x.useCallback(T=>D=>{D.preventDefault(),D.stopPropagation(),z(!0),K(T),L.current={x:D.clientX,y:D.clientY,width:C.width,height:C.height,posX:i.x,posY:i.y}},[C,i]);x.useEffect(()=>{if(!S||!O)return;const T=_=>{if(!L.current)return;const Y=_.clientX-L.current.x,X=_.clientY-L.current.y;let j=L.current.width,A=L.current.height,H=L.current.posX,F=L.current.posY;if(O.includes("e")&&(j=Math.max(re,L.current.width+Y)),O.includes("w")){const B=Math.min(Y,L.current.width-re);j=L.current.width-B,H=L.current.posX+B}if(O.includes("s")&&(A=Math.max(ce,L.current.height+X)),O.includes("n")){const B=Math.min(X,L.current.height-ce);A=L.current.height-B,F=L.current.posY+B}j=Math.min(j,window.innerWidth-H),A=Math.min(A,window.innerHeight-F),H=Math.max(0,H),F=Math.max(0,F),w({width:j,height:A}),u({x:H,y:F})},D=()=>{z(!1),K(null),L.current=null};return document.addEventListener("mousemove",T),document.addEventListener("mouseup",D),()=>{document.removeEventListener("mousemove",T),document.removeEventListener("mouseup",D)}},[S,O]);const qe=x.useCallback(()=>{V?(q.current&&(u(q.current.position),w(q.current.size)),he(!1)):(q.current={position:i,size:C},u({x:0,y:0}),w({width:window.innerWidth,height:window.innerHeight}),he(!0))},[V,i,C]),U=x.useCallback(()=>{I.isEnabled()&&(v(I.getState()),f(I.getActionHistory()),h(I.getCacheStats()),n(se.isConnected()))},[I,se]);x.useEffect(()=>{const T=D=>{D.ctrlKey&&D.shiftKey&&D.key==="G"&&(D.preventDefault(),s(_=>!_))};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[]),x.useEffect(()=>{if(!t||!I.isEnabled())return;U();const T=I.watchState("*",()=>{v(I.getState())}),D=I.watchActions(()=>{f(I.getActionHistory()),h(I.getCacheStats())}),_=setInterval(U,5e3);return()=>{T(),D(),clearInterval(_)}},[t,I,U]);const Ue=async()=>{try{const T=await se.dumpState();console.log("[G7DevTools] 상태 덤프 완료:",T),n(!0)}catch(T){console.error("[G7DevTools] 상태 덤프 실패:",T),n(!1)}};return I.isEnabled()?t?a?e.jsx("div",{className:"g7dt-minimized",children:e.jsxs("div",{className:"g7dt-minimized-content",children:[e.jsx("span",{className:"g7dt-font-bold g7dt-text-sm",children:"G7 DevTools"}),e.jsx("button",{onClick:()=>g(!1),className:"g7dt-btn g7dt-text-xs",title:"확장",children:"▲"}),e.jsx("button",{onClick:()=>s(!1),className:"g7dt-btn g7dt-text-xs",children:"✕"})]})}):e.jsxs("div",{ref:N,className:`g7dt-panel ${V?"maximized":""} ${S?"g7dt-resizing":""}`,style:{left:`${i.x>=0?i.x:0}px`,top:`${i.y>=0?i.y:0}px`,width:`${C.width}px`,height:`${C.height}px`},children:[!V&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"g7dt-resize-handle g7dt-resize-corner g7dt-resize-nw",onMouseDown:M("nw")}),e.jsx("div",{className:"g7dt-resize-handle g7dt-resize-corner g7dt-resize-ne",onMouseDown:M("ne")}),e.jsx("div",{className:"g7dt-resize-handle g7dt-resize-corner g7dt-resize-sw",onMouseDown:M("sw")}),e.jsx("div",{className:"g7dt-resize-handle g7dt-resize-corner g7dt-resize-se",onMouseDown:M("se")}),e.jsx("div",{className:"g7dt-resize-handle g7dt-resize-edge-h g7dt-resize-n",onMouseDown:M("n")}),e.jsx("div",{className:"g7dt-resize-handle g7dt-resize-edge-h g7dt-resize-s",onMouseDown:M("s")}),e.jsx("div",{className:"g7dt-resize-handle g7dt-resize-edge-v g7dt-resize-w",onMouseDown:M("w")}),e.jsx("div",{className:"g7dt-resize-handle g7dt-resize-edge-v g7dt-resize-e",onMouseDown:M("e")})]}),e.jsxs("div",{className:`g7dt-header ${m?"dragging":""}`,onMouseDown:Ke,children:[e.jsxs("div",{className:"g7dt-header-left",children:[e.jsx("span",{className:"g7dt-header-title",children:"G7 DevTools"}),e.jsx("span",{className:`g7dt-header-badge ${y?"connected":""}`,title:y?"서버 덤프 성공":"서버에 덤프되지 않음 (덤프 버튼 클릭)",children:y?"덤프 완료":"로컬 모드"})]}),e.jsxs("div",{className:"g7dt-header-right",children:[e.jsx("button",{onClick:Ue,className:"g7dt-btn g7dt-btn-primary",title:"서버로 상태 덤프",children:"덤프"}),e.jsx("button",{onClick:U,className:"g7dt-btn",title:"새로고침",children:"↻"}),e.jsx("button",{onClick:qe,className:"g7dt-btn",title:V?"복원":"최대화",children:V?"❐":"□"}),e.jsx("button",{onClick:()=>g(!0),className:"g7dt-btn",title:"최소화",children:"▼"}),e.jsx("button",{onClick:()=>s(!1),className:"g7dt-btn",children:"✕"})]})]}),e.jsx("div",{className:"g7dt-tabs",children:Object.keys(le).map(T=>e.jsx("button",{onClick:()=>o(T),className:`g7dt-tab ${r===T?"active":""}`,children:le[T]},T))}),e.jsxs("div",{className:"g7dt-content",children:[r==="state"&&e.jsx(ke,{state:p,devTools:I}),r==="actions"&&e.jsx(Ce,{actions:l,devTools:I}),r==="cache"&&e.jsx(Se,{stats:c,devTools:I}),r==="diagnose"&&e.jsx(Ie,{}),r==="performance"&&e.jsx(Te,{devTools:I}),r==="lifecycle"&&e.jsx(De,{devTools:I}),r==="network"&&e.jsx(Le,{devTools:I}),r==="form"&&e.jsx(Ee,{devTools:I}),r==="conditional"&&e.jsx($e,{devTools:I}),r==="expression"&&e.jsx(ze,{devTools:I}),r==="handlers"&&e.jsx(_e,{devTools:I}),r==="events"&&e.jsx(je,{devTools:I}),r==="datasources"&&e.jsx(Ae,{devTools:I}),r==="renders"&&e.jsx(Oe,{devTools:I}),r==="styles"&&e.jsx(Me,{devTools:I}),r==="auth"&&e.jsx(Pe,{devTools:I}),r==="logs"&&e.jsx(He,{devTools:I}),r==="layout"&&e.jsx(Fe,{devTools:I}),r==="changedetection"&&e.jsx(We,{devTools:I}),r==="staleclosure"&&e.jsx(Ve,{devTools:I}),r==="nestedcontext"&&e.jsx(Be,{devTools:I}),r==="modalscope"&&e.jsx(Ge,{devTools:I}),r==="namedactions"&&e.jsx(Je,{devTools:I})]}),e.jsxs("div",{className:"g7dt-footer",children:[e.jsx("span",{children:"Ctrl+Shift+G 토글 | 헤더 드래그로 이동"}),e.jsxs("span",{children:["액션: ",l.length," | 캐시 히트율: ",(c.hitRate*100).toFixed(1),"%"]})]})]}):e.jsx("button",{onClick:()=>s(!0),className:"g7dt-floating-btn",title:"G7 DevTools (Ctrl+Shift+G)",children:e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:[e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"}),e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"})]})}):t?e.jsxs("div",{className:"g7dt-disabled-notice",children:[e.jsxs("div",{className:"g7dt-flex g7dt-items-center g7dt-justify-between g7dt-mb-2",children:[e.jsx("span",{className:"g7dt-font-bold g7dt-text-yellow",children:"G7 DevTools"}),e.jsx("button",{onClick:()=>s(!1),className:"g7dt-btn",children:"✕"})]}),e.jsx("p",{className:"g7dt-text-sm g7dt-text-gray",children:"DevTools가 비활성화되어 있습니다."}),e.jsx("p",{className:"g7dt-text-xs g7dt-text-gray-dark g7dt-mt-2",children:"환경설정 > 고급 설정 > 디버그 모드를 켜세요."})]}):null};if(typeof window<"u"){const d=window.G7Core||(window.G7Core={});if(d.__devtools={DiagnosticEngine:Z,getServerConnector:R,getStyleTracker:ae,DevToolsPanel:ge},typeof d.__onDevToolsReady=="function")try{d.__onDevToolsReady()}catch{}}$.DevToolsPanel=ge,$.DiagnosticEngine=Z,$.getServerConnector=R,$.getStyleTracker=ae,Object.defineProperty($,Symbol.toStringTag,{value:"Module"})})(this.G7DevToolsBundle=this.G7DevToolsBundle||{},ReactJSXRuntime,React); +//# sourceMappingURL=devtools.min.js.map diff --git a/public/build/core/layout-editor.min.js b/public/build/core/layout-editor.min.js index 134f02b3..afea6728 100644 --- a/public/build/core/layout-editor.min.js +++ b/public/build/core/layout-editor.min.js @@ -11,3 +11,4 @@ var iM=Object.defineProperty;var sM=(dn,i,u)=>i in dn?iM(dn,i,{enumerable:!0,con Press space again to drop the item in its new position, or press escape to cancel. `},z7={onDragStart(e){let{active:t}=e;return"Picked up draggable item "+t.id+"."},onDragOver(e){let{active:t,over:n}=e;return n?"Draggable item "+t.id+" was moved over droppable area "+n.id+".":"Draggable item "+t.id+" is no longer over a droppable area."},onDragEnd(e){let{active:t,over:n}=e;return n?"Draggable item "+t.id+" was dropped over droppable area "+n.id:"Draggable item "+t.id+" was dropped."},onDragCancel(e){let{active:t}=e;return"Dragging was cancelled. Draggable item "+t.id+" was dropped."}};function M7(e){let{announcements:t=z7,container:n,hiddenTextDescribedById:o,screenReaderInstructions:r=N7}=e;const{announce:s,announcement:a}=A7(),l=ei("DndLiveRegion"),[d,c]=u.useState(!1);if(u.useEffect(()=>{c(!0)},[]),T7(u.useMemo(()=>({onDragStart(f){let{active:y}=f;s(t.onDragStart({active:y}))},onDragMove(f){let{active:y,over:g}=f;t.onDragMove&&s(t.onDragMove({active:y,over:g}))},onDragOver(f){let{active:y,over:g}=f;s(t.onDragOver({active:y,over:g}))},onDragEnd(f){let{active:y,over:g}=f;s(t.onDragEnd({active:y,over:g}))},onDragCancel(f){let{active:y,over:g}=f;s(t.onDragCancel({active:y,over:g}))}}),[s,t])),!d)return null;const p=u.createElement(u.Fragment,null,u.createElement(E7,{id:o,value:r.draggable}),u.createElement(I7,{id:l,announcement:a}));return n?Cn.createPortal(p,n):p}var it;(function(e){e.DragStart="dragStart",e.DragMove="dragMove",e.DragEnd="dragEnd",e.DragCancel="dragCancel",e.DragOver="dragOver",e.RegisterDroppable="registerDroppable",e.SetDroppableDisabled="setDroppableDisabled",e.UnregisterDroppable="unregisterDroppable"})(it||(it={}));function oi(){}function L7(e,t){return u.useMemo(()=>({sensor:e,options:t??{}}),[e,t])}function P7(){for(var e=arguments.length,t=new Array(e),n=0;n[...t].filter(o=>o!=null),[...t])}const Ht=Object.freeze({x:0,y:0});function O7(e,t){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}function B7(e,t){const n=ni(e);if(!n)return"0 0";const o={x:(n.x-t.left)/t.width*100,y:(n.y-t.top)/t.height*100};return o.x+"% "+o.y+"%"}function W7(e,t){let{data:{value:n}}=e,{data:{value:o}}=t;return n-o}function j7(e,t){let{data:{value:n}}=e,{data:{value:o}}=t;return o-n}function H7(e){let{left:t,top:n,height:o,width:r}=e;return[{x:t,y:n},{x:t+r,y:n},{x:t,y:n+o},{x:t+r,y:n+o}]}function F7(e,t){if(!e||e.length===0)return null;const[n]=e;return n[t]}function K7(e,t){const n=Math.max(t.top,e.top),o=Math.max(t.left,e.left),r=Math.min(t.left+t.width,e.left+e.width),s=Math.min(t.top+t.height,e.top+e.height),a=r-o,l=s-n;if(o{let{collisionRect:t,droppableRects:n,droppableContainers:o}=e;const r=[];for(const s of o){const{id:a}=s,l=n.get(a);if(l){const d=K7(l,t);d>0&&r.push({id:a,data:{droppableContainer:s,value:d}})}}return r.sort(j7)};function U7(e,t){const{top:n,left:o,bottom:r,right:s}=t;return n<=e.y&&e.y<=r&&o<=e.x&&e.x<=s}const q7=e=>{let{droppableContainers:t,droppableRects:n,pointerCoordinates:o}=e;if(!o)return[];const r=[];for(const s of t){const{id:a}=s,l=n.get(a);if(l&&U7(o,l)){const c=H7(l).reduce((f,y)=>f+O7(o,y),0),p=Number((c/4).toFixed(4));r.push({id:a,data:{droppableContainer:s,value:p}})}}return r.sort(W7)};function G7(e,t,n){return{...e,scaleX:t&&n?t.width/n.width:1,scaleY:t&&n?t.height/n.height:1}}function jp(e,t){return e&&t?{x:e.left-t.left,y:e.top-t.top}:Ht}function Y7(e){return function(n){for(var o=arguments.length,r=new Array(o>1?o-1:0),s=1;s({...a,top:a.top+e*l.y,bottom:a.bottom+e*l.y,left:a.left+e*l.x,right:a.right+e*l.x}),{...n})}}const X7=Y7(1);function Hp(e){if(e.startsWith("matrix3d(")){const t=e.slice(9,-1).split(/, /);return{x:+t[12],y:+t[13],scaleX:+t[0],scaleY:+t[5]}}else if(e.startsWith("matrix(")){const t=e.slice(7,-1).split(/, /);return{x:+t[4],y:+t[5],scaleX:+t[0],scaleY:+t[3]}}return null}function J7(e,t,n){const o=Hp(t);if(!o)return e;const{scaleX:r,scaleY:s,x:a,y:l}=o,d=e.left-a-(1-r)*parseFloat(n),c=e.top-l-(1-s)*parseFloat(n.slice(n.indexOf(" ")+1)),p=r?e.width/r:e.width,f=s?e.height/s:e.height;return{width:p,height:f,top:c,right:d+p,bottom:c+f,left:d}}const Z7={ignoreTransform:!1};function jo(e,t){t===void 0&&(t=Z7);let n=e.getBoundingClientRect();if(t.ignoreTransform){const{transform:c,transformOrigin:p}=_t(e).getComputedStyle(e);c&&(n=J7(n,c,p))}const{top:o,left:r,width:s,height:a,bottom:l,right:d}=n;return{top:o,left:r,width:s,height:a,bottom:l,right:d}}function Fp(e){return jo(e,{ignoreTransform:!0})}function Q7(e){const t=e.innerWidth,n=e.innerHeight;return{top:0,left:0,right:t,bottom:n,width:t,height:n}}function R7(e,t){return t===void 0&&(t=_t(e).getComputedStyle(e)),t.position==="fixed"}function e2(e,t){t===void 0&&(t=_t(e).getComputedStyle(e));const n=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(r=>{const s=t[r];return typeof s=="string"?n.test(s):!1})}function da(e,t){const n=[];function o(r){if(t!=null&&n.length>=t||!r)return n;if(sa(r)&&r.scrollingElement!=null&&!n.includes(r.scrollingElement))return n.push(r.scrollingElement),n;if(!Po(r)||Pp(r)||n.includes(r))return n;const s=_t(e).getComputedStyle(r);return r!==e&&e2(r,s)&&n.push(r),R7(r,s)?n:o(r.parentNode)}return e?o(e):n}function Kp(e){const[t]=da(e,1);return t??null}function ca(e){return!Jr||!e?null:lo(e)?e:ia(e)?sa(e)||e===co(e).scrollingElement?window:Po(e)?e:null:null}function Vp(e){return lo(e)?e.scrollX:e.scrollLeft}function Up(e){return lo(e)?e.scrollY:e.scrollTop}function ua(e){return{x:Vp(e),y:Up(e)}}var lt;(function(e){e[e.Forward=1]="Forward",e[e.Backward=-1]="Backward"})(lt||(lt={}));function qp(e){return!Jr||!e?!1:e===document.scrollingElement}function Gp(e){const t={x:0,y:0},n=qp(e)?{height:window.innerHeight,width:window.innerWidth}:{height:e.clientHeight,width:e.clientWidth},o={x:e.scrollWidth-n.width,y:e.scrollHeight-n.height},r=e.scrollTop<=t.y,s=e.scrollLeft<=t.x,a=e.scrollTop>=o.y,l=e.scrollLeft>=o.x;return{isTop:r,isLeft:s,isBottom:a,isRight:l,maxScroll:o,minScroll:t}}const t2={x:.2,y:.2};function n2(e,t,n,o,r){let{top:s,left:a,right:l,bottom:d}=n;o===void 0&&(o=10),r===void 0&&(r=t2);const{isTop:c,isBottom:p,isLeft:f,isRight:y}=Gp(e),g={x:0,y:0},m={x:0,y:0},h={height:t.height*r.y,width:t.width*r.x};return!c&&s<=t.top+h.height?(g.y=lt.Backward,m.y=o*Math.abs((t.top+h.height-s)/h.height)):!p&&d>=t.bottom-h.height&&(g.y=lt.Forward,m.y=o*Math.abs((t.bottom-h.height-d)/h.height)),!y&&l>=t.right-h.width?(g.x=lt.Forward,m.x=o*Math.abs((t.right-h.width-l)/h.width)):!f&&a<=t.left+h.width&&(g.x=lt.Backward,m.x=o*Math.abs((t.left+h.width-a)/h.width)),{direction:g,speed:m}}function o2(e){if(e===document.scrollingElement){const{innerWidth:s,innerHeight:a}=window;return{top:0,left:0,right:s,bottom:a,width:s,height:a}}const{top:t,left:n,right:o,bottom:r}=e.getBoundingClientRect();return{top:t,left:n,right:o,bottom:r,width:e.clientWidth,height:e.clientHeight}}function Yp(e){return e.reduce((t,n)=>uo(t,ua(n)),Ht)}function r2(e){return e.reduce((t,n)=>t+Vp(n),0)}function i2(e){return e.reduce((t,n)=>t+Up(n),0)}function Xp(e,t){if(t===void 0&&(t=jo),!e)return;const{top:n,left:o,bottom:r,right:s}=t(e);Kp(e)&&(r<=0||s<=0||n>=window.innerHeight||o>=window.innerWidth)&&e.scrollIntoView({block:"center",inline:"center"})}const s2=[["x",["left","right"],r2],["y",["top","bottom"],i2]];class pa{constructor(t,n){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;const o=da(n),r=Yp(o);this.rect={...t},this.width=t.width,this.height=t.height;for(const[s,a,l]of s2)for(const d of a)Object.defineProperty(this,d,{get:()=>{const c=l(o),p=r[s]-c;return this.rect[d]+p},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class Ho{constructor(t){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(n=>{var o;return(o=this.target)==null?void 0:o.removeEventListener(...n)})},this.target=t}add(t,n,o){var r;(r=this.target)==null||r.addEventListener(t,n,o),this.listeners.push([t,n,o])}}function a2(e){const{EventTarget:t}=_t(e);return e instanceof t?e:co(e)}function fa(e,t){const n=Math.abs(e.x),o=Math.abs(e.y);return typeof t=="number"?Math.sqrt(n**2+o**2)>t:"x"in t&&"y"in t?n>t.x&&o>t.y:"x"in t?n>t.x:"y"in t?o>t.y:!1}var At;(function(e){e.Click="click",e.DragStart="dragstart",e.Keydown="keydown",e.ContextMenu="contextmenu",e.Resize="resize",e.SelectionChange="selectionchange",e.VisibilityChange="visibilitychange"})(At||(At={}));function Jp(e){e.preventDefault()}function l2(e){e.stopPropagation()}var Ke;(function(e){e.Space="Space",e.Down="ArrowDown",e.Right="ArrowRight",e.Left="ArrowLeft",e.Up="ArrowUp",e.Esc="Escape",e.Enter="Enter",e.Tab="Tab"})(Ke||(Ke={}));const Zp={start:[Ke.Space,Ke.Enter],cancel:[Ke.Esc],end:[Ke.Space,Ke.Enter,Ke.Tab]},d2=(e,t)=>{let{currentCoordinates:n}=t;switch(e.code){case Ke.Right:return{...n,x:n.x+25};case Ke.Left:return{...n,x:n.x-25};case Ke.Down:return{...n,y:n.y+25};case Ke.Up:return{...n,y:n.y-25}}};class Qp{constructor(t){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=t;const{event:{target:n}}=t;this.props=t,this.listeners=new Ho(co(n)),this.windowListeners=new Ho(_t(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(At.Resize,this.handleCancel),this.windowListeners.add(At.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(At.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:n}=this.props,o=t.node.current;o&&Xp(o),n(Ht)}handleKeyDown(t){if(la(t)){const{active:n,context:o,options:r}=this.props,{keyboardCodes:s=Zp,coordinateGetter:a=d2,scrollBehavior:l="smooth"}=r,{code:d}=t;if(s.end.includes(d)){this.handleEnd(t);return}if(s.cancel.includes(d)){this.handleCancel(t);return}const{collisionRect:c}=o.current,p=c?{x:c.left,y:c.top}:Ht;this.referenceCoordinates||(this.referenceCoordinates=p);const f=a(t,{active:n,context:o.current,currentCoordinates:p});if(f){const y=ti(f,p),g={x:0,y:0},{scrollableAncestors:m}=o.current;for(const h of m){const v=t.code,{isTop:b,isRight:x,isLeft:k,isBottom:w,maxScroll:_,minScroll:S}=Gp(h),E=o2(h),C={x:Math.min(v===Ke.Right?E.right-E.width/2:E.right,Math.max(v===Ke.Right?E.left:E.left+E.width/2,f.x)),y:Math.min(v===Ke.Down?E.bottom-E.height/2:E.bottom,Math.max(v===Ke.Down?E.top:E.top+E.height/2,f.y))},N=v===Ke.Right&&!x||v===Ke.Left&&!k,$=v===Ke.Down&&!w||v===Ke.Up&&!b;if(N&&C.x!==f.x){const A=h.scrollLeft+y.x,z=v===Ke.Right&&A<=_.x||v===Ke.Left&&A>=S.x;if(z&&!y.y){h.scrollTo({left:A,behavior:l});return}z?g.x=h.scrollLeft-A:g.x=v===Ke.Right?h.scrollLeft-_.x:h.scrollLeft-S.x,g.x&&h.scrollBy({left:-g.x,behavior:l});break}else if($&&C.y!==f.y){const A=h.scrollTop+y.y,z=v===Ke.Down&&A<=_.y||v===Ke.Up&&A>=S.y;if(z&&!y.x){h.scrollTo({top:A,behavior:l});return}z?g.y=h.scrollTop-A:g.y=v===Ke.Down?h.scrollTop-_.y:h.scrollTop-S.y,g.y&&h.scrollBy({top:-g.y,behavior:l});break}}this.handleMove(t,uo(ti(f,this.referenceCoordinates),g))}}}handleMove(t,n){const{onMove:o}=this.props;t.preventDefault(),o(n)}handleEnd(t){const{onEnd:n}=this.props;t.preventDefault(),this.detach(),n()}handleCancel(t){const{onCancel:n}=this.props;t.preventDefault(),this.detach(),n()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}Qp.activators=[{eventName:"onKeyDown",handler:(e,t,n)=>{let{keyboardCodes:o=Zp,onActivation:r}=t,{active:s}=n;const{code:a}=e.nativeEvent;if(o.start.includes(a)){const l=s.activatorNode.current;return l&&e.target!==l?!1:(e.preventDefault(),r?.({event:e.nativeEvent}),!0)}return!1}}];function Rp(e){return!!(e&&"distance"in e)}function ef(e){return!!(e&&"delay"in e)}class ga{constructor(t,n,o){var r;o===void 0&&(o=a2(t.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=t,this.events=n;const{event:s}=t,{target:a}=s;this.props=t,this.events=n,this.document=co(a),this.documentListeners=new Ho(this.document),this.listeners=new Ho(o),this.windowListeners=new Ho(_t(a)),this.initialCoordinates=(r=ni(s))!=null?r:Ht,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){const{events:t,props:{options:{activationConstraint:n,bypassActivationConstraint:o}}}=this;if(this.listeners.add(t.move.name,this.handleMove,{passive:!1}),this.listeners.add(t.end.name,this.handleEnd),t.cancel&&this.listeners.add(t.cancel.name,this.handleCancel),this.windowListeners.add(At.Resize,this.handleCancel),this.windowListeners.add(At.DragStart,Jp),this.windowListeners.add(At.VisibilityChange,this.handleCancel),this.windowListeners.add(At.ContextMenu,Jp),this.documentListeners.add(At.Keydown,this.handleKeydown),n){if(o!=null&&o({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(ef(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(Rp(n)){this.handlePending(n);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(t,n){const{active:o,onPending:r}=this.props;r(o,t,this.initialCoordinates,n)}handleStart(){const{initialCoordinates:t}=this,{onStart:n}=this.props;t&&(this.activated=!0,this.documentListeners.add(At.Click,l2,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(At.SelectionChange,this.removeTextSelection),n(t))}handleMove(t){var n;const{activated:o,initialCoordinates:r,props:s}=this,{onMove:a,options:{activationConstraint:l}}=s;if(!r)return;const d=(n=ni(t))!=null?n:Ht,c=ti(r,d);if(!o&&l){if(Rp(l)){if(l.tolerance!=null&&fa(c,l.tolerance))return this.handleCancel();if(fa(c,l.distance))return this.handleStart()}if(ef(l)&&fa(c,l.tolerance))return this.handleCancel();this.handlePending(l,c);return}t.cancelable&&t.preventDefault(),a(d)}handleEnd(){const{onAbort:t,onEnd:n}=this.props;this.detach(),this.activated||t(this.props.active),n()}handleCancel(){const{onAbort:t,onCancel:n}=this.props;this.detach(),this.activated||t(this.props.active),n()}handleKeydown(t){t.code===Ke.Esc&&this.handleCancel()}removeTextSelection(){var t;(t=this.document.getSelection())==null||t.removeAllRanges()}}const c2={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class ha extends ga{constructor(t){const{event:n}=t,o=co(n.target);super(t,c2,o)}}ha.activators=[{eventName:"onPointerDown",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:o}=t;return!n.isPrimary||n.button!==0?!1:(o?.({event:n}),!0)}}];const u2={move:{name:"mousemove"},end:{name:"mouseup"}};var ya;(function(e){e[e.RightClick=2]="RightClick"})(ya||(ya={}));class p2 extends ga{constructor(t){super(t,u2,co(t.event.target))}}p2.activators=[{eventName:"onMouseDown",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:o}=t;return n.button===ya.RightClick?!1:(o?.({event:n}),!0)}}];const ba={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class f2 extends ga{constructor(t){super(t,ba)}static setup(){return window.addEventListener(ba.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(ba.move.name,t)};function t(){}}}f2.activators=[{eventName:"onTouchStart",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:o}=t;const{touches:r}=n;return r.length>1?!1:(o?.({event:n}),!0)}}];var Fo;(function(e){e[e.Pointer=0]="Pointer",e[e.DraggableRect=1]="DraggableRect"})(Fo||(Fo={}));var ri;(function(e){e[e.TreeOrder=0]="TreeOrder",e[e.ReversedTreeOrder=1]="ReversedTreeOrder"})(ri||(ri={}));function g2(e){let{acceleration:t,activator:n=Fo.Pointer,canScroll:o,draggingRect:r,enabled:s,interval:a=5,order:l=ri.TreeOrder,pointerCoordinates:d,scrollableAncestors:c,scrollableAncestorRects:p,delta:f,threshold:y}=e;const g=y2({delta:f,disabled:!s}),[m,h]=w7(),v=u.useRef({x:0,y:0}),b=u.useRef({x:0,y:0}),x=u.useMemo(()=>{switch(n){case Fo.Pointer:return d?{top:d.y,bottom:d.y,left:d.x,right:d.x}:null;case Fo.DraggableRect:return r}},[n,r,d]),k=u.useRef(null),w=u.useCallback(()=>{const S=k.current;if(!S)return;const E=v.current.x*b.current.x,C=v.current.y*b.current.y;S.scrollBy(E,C)},[]),_=u.useMemo(()=>l===ri.TreeOrder?[...c].reverse():c,[l,c]);u.useEffect(()=>{if(!s||!c.length||!x){h();return}for(const S of _){if(o?.(S)===!1)continue;const E=c.indexOf(S),C=p[E];if(!C)continue;const{direction:N,speed:$}=n2(S,C,x,t,y);for(const A of["x","y"])g[A][N[A]]||($[A]=0,N[A]=0);if($.x>0||$.y>0){h(),k.current=S,m(w,a),v.current=$,b.current=N;return}}v.current={x:0,y:0},b.current={x:0,y:0},h()},[t,w,o,h,s,a,JSON.stringify(x),JSON.stringify(g),m,c,_,p,JSON.stringify(y)])}const h2={x:{[lt.Backward]:!1,[lt.Forward]:!1},y:{[lt.Backward]:!1,[lt.Forward]:!1}};function y2(e){let{delta:t,disabled:n}=e;const o=Rr(t);return Bo(r=>{if(n||!o||!r)return h2;const s={x:Math.sign(t.x-o.x),y:Math.sign(t.y-o.y)};return{x:{[lt.Backward]:r.x[lt.Backward]||s.x===-1,[lt.Forward]:r.x[lt.Forward]||s.x===1},y:{[lt.Backward]:r.y[lt.Backward]||s.y===-1,[lt.Forward]:r.y[lt.Forward]||s.y===1}}},[n,t,o])}function b2(e,t){const n=t!=null?e.get(t):void 0,o=n?n.node.current:null;return Bo(r=>{var s;return t==null?null:(s=o??r)!=null?s:null},[o,t])}function m2(e,t){return u.useMemo(()=>e.reduce((n,o)=>{const{sensor:r}=o,s=r.activators.map(a=>({eventName:a.eventName,handler:t(a.handler,o)}));return[...n,...s]},[]),[e,t])}var Ko;(function(e){e[e.Always=0]="Always",e[e.BeforeDragging=1]="BeforeDragging",e[e.WhileDragging=2]="WhileDragging"})(Ko||(Ko={}));var ma;(function(e){e.Optimized="optimized"})(ma||(ma={}));const tf=new Map;function v2(e,t){let{dragging:n,dependencies:o,config:r}=t;const[s,a]=u.useState(null),{frequency:l,measure:d,strategy:c}=r,p=u.useRef(e),f=v(),y=Oo(f),g=u.useCallback(function(b){b===void 0&&(b=[]),!y.current&&a(x=>x===null?b:x.concat(b.filter(k=>!x.includes(k))))},[y]),m=u.useRef(null),h=Bo(b=>{if(f&&!n)return tf;if(!b||b===tf||p.current!==e||s!=null){const x=new Map;for(let k of e){if(!k)continue;if(s&&s.length>0&&!s.includes(k.id)&&k.rect.current){x.set(k.id,k.rect.current);continue}const w=k.node.current,_=w?new pa(d(w),w):null;k.rect.current=_,_&&x.set(k.id,_)}return x}return b},[e,s,n,f,d]);return u.useEffect(()=>{p.current=e},[e]),u.useEffect(()=>{f||g()},[n,f]),u.useEffect(()=>{s&&s.length>0&&a(null)},[JSON.stringify(s)]),u.useEffect(()=>{f||typeof l!="number"||m.current!==null||(m.current=setTimeout(()=>{g(),m.current=null},l))},[l,f,g,...o]),{droppableRects:h,measureDroppableContainers:g,measuringScheduled:s!=null};function v(){switch(c){case Ko.Always:return!1;case Ko.BeforeDragging:return n;default:return!n}}}function va(e,t){return Bo(n=>e?n||(typeof t=="function"?t(e):e):null,[t,e])}function _2(e,t){return va(e,t)}function x2(e){let{callback:t,disabled:n}=e;const o=Zr(t),r=u.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:s}=window;return new s(o)},[o,n]);return u.useEffect(()=>()=>r?.disconnect(),[r]),r}function ii(e){let{callback:t,disabled:n}=e;const o=Zr(t),r=u.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:s}=window;return new s(o)},[n]);return u.useEffect(()=>()=>r?.disconnect(),[r]),r}function w2(e){return new pa(jo(e),e)}function nf(e,t,n){t===void 0&&(t=w2);const[o,r]=u.useState(null);function s(){r(d=>{if(!e)return null;if(e.isConnected===!1){var c;return(c=d??n)!=null?c:null}const p=t(e);return JSON.stringify(d)===JSON.stringify(p)?d:p})}const a=x2({callback(d){if(e)for(const c of d){const{type:p,target:f}=c;if(p==="childList"&&f instanceof HTMLElement&&f.contains(e)){s();break}}}}),l=ii({callback:s});return sn(()=>{s(),e?(l?.observe(e),a?.observe(document.body,{childList:!0,subtree:!0})):(l?.disconnect(),a?.disconnect())},[e]),o}function k2(e){const t=va(e);return jp(e,t)}const of=[];function S2(e){const t=u.useRef(e),n=Bo(o=>e?o&&o!==of&&e&&t.current&&e.parentNode===t.current.parentNode?o:da(e):of,[e]);return u.useEffect(()=>{t.current=e},[e]),n}function C2(e){const[t,n]=u.useState(null),o=u.useRef(e),r=u.useCallback(s=>{const a=ca(s.target);a&&n(l=>l?(l.set(a,ua(a)),new Map(l)):null)},[]);return u.useEffect(()=>{const s=o.current;if(e!==s){a(s);const l=e.map(d=>{const c=ca(d);return c?(c.addEventListener("scroll",r,{passive:!0}),[c,ua(c)]):null}).filter(d=>d!=null);n(l.length?new Map(l):null),o.current=e}return()=>{a(e),a(s)};function a(l){l.forEach(d=>{const c=ca(d);c?.removeEventListener("scroll",r)})}},[r,e]),u.useMemo(()=>e.length?t?Array.from(t.values()).reduce((s,a)=>uo(s,a),Ht):Yp(e):Ht,[e,t])}function rf(e,t){t===void 0&&(t=[]);const n=u.useRef(null);return u.useEffect(()=>{n.current=null},t),u.useEffect(()=>{const o=e!==Ht;o&&!n.current&&(n.current=e),!o&&n.current&&(n.current=null)},[e]),n.current?ti(e,n.current):Ht}function $2(e){u.useEffect(()=>{if(!Jr)return;const t=e.map(n=>{let{sensor:o}=n;return o.setup==null?void 0:o.setup()});return()=>{for(const n of t)n?.()}},e.map(t=>{let{sensor:n}=t;return n}))}function E2(e,t){return u.useMemo(()=>e.reduce((n,o)=>{let{eventName:r,handler:s}=o;return n[r]=a=>{s(a,t)},n},{}),[e,t])}function sf(e){return u.useMemo(()=>e?Q7(e):null,[e])}const af=[];function I2(e,t){t===void 0&&(t=jo);const[n]=e,o=sf(n?_t(n):null),[r,s]=u.useState(af);function a(){s(()=>e.length?e.map(d=>qp(d)?o:new pa(t(d),d)):af)}const l=ii({callback:a});return sn(()=>{l?.disconnect(),a(),e.forEach(d=>l?.observe(d))},[e]),r}function lf(e){if(!e)return null;if(e.children.length>1)return e;const t=e.children[0];return Po(t)?t:e}function A2(e){let{measure:t}=e;const[n,o]=u.useState(null),r=u.useCallback(c=>{for(const{target:p}of c)if(Po(p)){o(f=>{const y=t(p);return f?{...f,width:y.width,height:y.height}:y});break}},[t]),s=ii({callback:r}),a=u.useCallback(c=>{const p=lf(c);s?.disconnect(),p&&s?.observe(p),o(p?t(p):null)},[t,s]),[l,d]=Qr(a);return u.useMemo(()=>({nodeRef:l,rect:n,setRef:d}),[n,l,d])}const T2=[{sensor:ha,options:{}},{sensor:Qp,options:{}}],D2={current:{}},si={draggable:{measure:Fp},droppable:{measure:Fp,strategy:Ko.WhileDragging,frequency:ma.Optimized},dragOverlay:{measure:jo}};class Vo extends Map{get(t){var n;return t!=null&&(n=super.get(t))!=null?n:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(t=>{let{disabled:n}=t;return!n})}getNodeFor(t){var n,o;return(n=(o=this.get(t))==null?void 0:o.node.current)!=null?n:void 0}}const N2={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new Vo,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:oi},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:si,measureDroppableContainers:oi,windowRect:null,measuringScheduled:!1},df={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:oi,draggableNodes:new Map,over:null,measureDroppableContainers:oi},Uo=u.createContext(df),cf=u.createContext(N2);function z2(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new Vo}}}function M2(e,t){switch(t.type){case it.DragStart:return{...e,draggable:{...e.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case it.DragMove:return e.draggable.active==null?e:{...e,draggable:{...e.draggable,translate:{x:t.coordinates.x-e.draggable.initialCoordinates.x,y:t.coordinates.y-e.draggable.initialCoordinates.y}}};case it.DragEnd:case it.DragCancel:return{...e,draggable:{...e.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case it.RegisterDroppable:{const{element:n}=t,{id:o}=n,r=new Vo(e.droppable.containers);return r.set(o,n),{...e,droppable:{...e.droppable,containers:r}}}case it.SetDroppableDisabled:{const{id:n,key:o,disabled:r}=t,s=e.droppable.containers.get(n);if(!s||o!==s.key)return e;const a=new Vo(e.droppable.containers);return a.set(n,{...s,disabled:r}),{...e,droppable:{...e.droppable,containers:a}}}case it.UnregisterDroppable:{const{id:n,key:o}=t,r=e.droppable.containers.get(n);if(!r||o!==r.key)return e;const s=new Vo(e.droppable.containers);return s.delete(n),{...e,droppable:{...e.droppable,containers:s}}}default:return e}}function L2(e){let{disabled:t}=e;const{active:n,activatorEvent:o,draggableNodes:r}=u.useContext(Uo),s=Rr(o),a=Rr(n?.id);return u.useEffect(()=>{if(!t&&!o&&s&&a!=null){if(!la(s)||document.activeElement===s.target)return;const l=r.get(a);if(!l)return;const{activatorNode:d,node:c}=l;if(!d.current&&!c.current)return;requestAnimationFrame(()=>{for(const p of[d.current,c.current]){if(!p)continue;const f=C7(p);if(f){f.focus();break}}})}},[o,t,r,a,s]),null}function uf(e,t){let{transform:n,...o}=t;return e!=null&&e.length?e.reduce((r,s)=>s({transform:r,...o}),n):n}function P2(e){return u.useMemo(()=>({draggable:{...si.draggable,...e?.draggable},droppable:{...si.droppable,...e?.droppable},dragOverlay:{...si.dragOverlay,...e?.dragOverlay}}),[e?.draggable,e?.droppable,e?.dragOverlay])}function O2(e){let{activeNode:t,measure:n,initialRect:o,config:r=!0}=e;const s=u.useRef(!1),{x:a,y:l}=typeof r=="boolean"?{x:r,y:r}:r;sn(()=>{if(!a&&!l||!t){s.current=!1;return}if(s.current||!o)return;const c=t?.node.current;if(!c||c.isConnected===!1)return;const p=n(c),f=jp(p,o);if(a||(f.x=0),l||(f.y=0),s.current=!0,Math.abs(f.x)>0||Math.abs(f.y)>0){const y=Kp(c);y&&y.scrollBy({top:f.y,left:f.x})}},[t,a,l,o,n])}const ai=u.createContext({...Ht,scaleX:1,scaleY:1});var hn;(function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Initializing=1]="Initializing",e[e.Initialized=2]="Initialized"})(hn||(hn={}));const B2=u.memo(function(t){var n,o,r,s;let{id:a,accessibility:l,autoScroll:d=!0,children:c,sensors:p=T2,collisionDetection:f=V7,measuring:y,modifiers:g,...m}=t;const h=u.useReducer(M2,void 0,z2),[v,b]=h,[x,k]=D7(),[w,_]=u.useState(hn.Uninitialized),S=w===hn.Initialized,{draggable:{active:E,nodes:C,translate:N},droppable:{containers:$}}=v,A=E!=null?C.get(E):null,z=u.useRef({initial:null,translated:null}),D=u.useMemo(()=>{var J;return E!=null?{id:E,data:(J=A?.data)!=null?J:D2,rect:z}:null},[E,A]),O=u.useRef(null),[M,B]=u.useState(null),[T,H]=u.useState(null),L=Oo(m,Object.values(m)),I=ei("DndDescribedBy",a),P=u.useMemo(()=>$.getEnabled(),[$]),F=P2(y),{droppableRects:G,measureDroppableContainers:V,measuringScheduled:Y}=v2(P,{dragging:S,dependencies:[N.x,N.y],config:F.droppable}),Z=b2(C,E),se=u.useMemo(()=>T?ni(T):null,[T]),re=ue(),U=_2(Z,F.draggable.measure);O2({activeNode:E!=null?C.get(E):null,config:re.layoutShiftCompensation,initialRect:U,measure:F.draggable.measure});const ee=nf(Z,F.draggable.measure,U),fe=nf(Z?Z.parentElement:null),K=u.useRef({activatorEvent:null,active:null,activeNode:Z,collisionRect:null,collisions:null,droppableRects:G,draggableNodes:C,draggingNode:null,draggingNodeRect:null,droppableContainers:$,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),ne=$.getNodeFor((n=K.current.over)==null?void 0:n.id),me=A2({measure:F.dragOverlay.measure}),Ce=(o=me.nodeRef.current)!=null?o:Z,ze=S?(r=me.rect)!=null?r:ee:null,Se=!!(me.nodeRef.current&&me.rect),qe=k2(Se?null:ee),De=sf(Ce?_t(Ce):null),Pe=S2(S?ne??Z:null),Qe=I2(Pe),Me=uf(g,{transform:{x:N.x-qe.x,y:N.y-qe.y,scaleX:1,scaleY:1},activatorEvent:T,active:D,activeNodeRect:ee,containerNodeRect:fe,draggingNodeRect:ze,over:K.current.over,overlayNodeRect:me.rect,scrollableAncestors:Pe,scrollableAncestorRects:Qe,windowRect:De}),Re=se?uo(se,N):null,ve=C2(Pe),te=rf(ve),he=rf(ve,[ee]),Q=uo(Me,te),ie=ze?X7(ze,Me):null,_e=D&&ie?f({active:D,collisionRect:ie,droppableRects:G,droppableContainers:P,pointerCoordinates:Re}):null,ge=F7(_e,"id"),[Ae,Ne]=u.useState(null),Le=Se?Me:uo(Me,he),q=G7(Le,(s=Ae?.rect)!=null?s:null,ee),ae=u.useRef(null),pe=u.useCallback((J,le)=>{let{sensor:Ie,options:dt}=le;if(O.current==null)return;const pt=C.get(O.current);if(!pt)return;const ot=J.nativeEvent,Oe=new Ie({active:O.current,activeNode:pt,event:ot,options:dt,context:K,onAbort(Ye){if(!C.get(Ye))return;const{onDragAbort:Dt}=L.current,Nt={id:Ye};Dt?.(Nt),x({type:"onDragAbort",event:Nt})},onPending(Ye,Tt,Dt,Nt){if(!C.get(Ye))return;const{onDragPending:wn}=L.current,Zt={id:Ye,constraint:Tt,initialCoordinates:Dt,offset:Nt};wn?.(Zt),x({type:"onDragPending",event:Zt})},onStart(Ye){const Tt=O.current;if(Tt==null)return;const Dt=C.get(Tt);if(!Dt)return;const{onDragStart:Nt}=L.current,xn={activatorEvent:ot,active:{id:Tt,data:Dt.data,rect:z}};Cn.unstable_batchedUpdates(()=>{Nt?.(xn),_(hn.Initializing),b({type:it.DragStart,initialCoordinates:Ye,active:Tt}),x({type:"onDragStart",event:xn}),B(ae.current),H(ot)})},onMove(Ye){b({type:it.DragMove,coordinates:Ye})},onEnd:He(it.DragEnd),onCancel:He(it.DragCancel)});ae.current=Oe;function He(Ye){return async function(){const{active:Dt,collisions:Nt,over:xn,scrollAdjustedTranslate:wn}=K.current;let Zt=null;if(Dt&&wn){const{cancelDrop:Hn}=L.current;Zt={activatorEvent:ot,active:Dt,collisions:Nt,delta:wn,over:xn},Ye===it.DragEnd&&typeof Hn=="function"&&await Promise.resolve(Hn(Zt))&&(Ye=it.DragCancel)}O.current=null,Cn.unstable_batchedUpdates(()=>{b({type:Ye}),_(hn.Uninitialized),Ne(null),B(null),H(null),ae.current=null;const Hn=Ye===it.DragEnd?"onDragEnd":"onDragCancel";if(Zt){const ln=L.current[Hn];ln?.(Zt),x({type:Hn,event:Zt})}})}}},[C]),$e=u.useCallback((J,le)=>(Ie,dt)=>{const pt=Ie.nativeEvent,ot=C.get(dt);if(O.current!==null||!ot||pt.dndKit||pt.defaultPrevented)return;const Oe={active:ot};J(Ie,le.options,Oe)===!0&&(pt.dndKit={capturedBy:le.sensor},O.current=dt,pe(Ie,le))},[C,pe]),be=m2(p,$e);$2(p),sn(()=>{ee&&w===hn.Initializing&&_(hn.Initialized)},[ee,w]),u.useEffect(()=>{const{onDragMove:J}=L.current,{active:le,activatorEvent:Ie,collisions:dt,over:pt}=K.current;if(!le||!Ie)return;const ot={active:le,activatorEvent:Ie,collisions:dt,delta:{x:Q.x,y:Q.y},over:pt};Cn.unstable_batchedUpdates(()=>{J?.(ot),x({type:"onDragMove",event:ot})})},[Q.x,Q.y]),u.useEffect(()=>{const{active:J,activatorEvent:le,collisions:Ie,droppableContainers:dt,scrollAdjustedTranslate:pt}=K.current;if(!J||O.current==null||!le||!pt)return;const{onDragOver:ot}=L.current,Oe=dt.get(ge),He=Oe&&Oe.rect.current?{id:Oe.id,rect:Oe.rect.current,data:Oe.data,disabled:Oe.disabled}:null,Ye={active:J,activatorEvent:le,collisions:Ie,delta:{x:pt.x,y:pt.y},over:He};Cn.unstable_batchedUpdates(()=>{Ne(He),ot?.(Ye),x({type:"onDragOver",event:Ye})})},[ge]),sn(()=>{K.current={activatorEvent:T,active:D,activeNode:Z,collisionRect:ie,collisions:_e,droppableRects:G,draggableNodes:C,draggingNode:Ce,draggingNodeRect:ze,droppableContainers:$,over:Ae,scrollableAncestors:Pe,scrollAdjustedTranslate:Q},z.current={initial:ze,translated:ie}},[D,Z,_e,ie,C,Ce,ze,G,$,Ae,Pe,Q]),g2({...re,delta:N,draggingRect:ie,pointerCoordinates:Re,scrollableAncestors:Pe,scrollableAncestorRects:Qe});const j=u.useMemo(()=>({active:D,activeNode:Z,activeNodeRect:ee,activatorEvent:T,collisions:_e,containerNodeRect:fe,dragOverlay:me,draggableNodes:C,droppableContainers:$,droppableRects:G,over:Ae,measureDroppableContainers:V,scrollableAncestors:Pe,scrollableAncestorRects:Qe,measuringConfiguration:F,measuringScheduled:Y,windowRect:De}),[D,Z,ee,T,_e,fe,me,C,$,G,Ae,V,Pe,Qe,F,Y,De]),oe=u.useMemo(()=>({activatorEvent:T,activators:be,active:D,activeNodeRect:ee,ariaDescribedById:{draggable:I},dispatch:b,draggableNodes:C,over:Ae,measureDroppableContainers:V}),[T,be,D,ee,b,I,C,Ae,V]);return u.createElement(Wp.Provider,{value:k},u.createElement(Uo.Provider,{value:oe},u.createElement(cf.Provider,{value:j},u.createElement(ai.Provider,{value:q},c)),u.createElement(L2,{disabled:l?.restoreFocus===!1})),u.createElement(M7,{...l,hiddenTextDescribedById:I}));function ue(){const J=M?.autoScrollEnabled===!1,le=typeof d=="object"?d.enabled===!1:d===!1,Ie=S&&!J&&!le;return typeof d=="object"?{...d,enabled:Ie}:{enabled:Ie}}}),W2=u.createContext(null),pf="button",j2="Draggable";function H2(e){let{id:t,data:n,disabled:o=!1,attributes:r}=e;const s=ei(j2),{activators:a,activatorEvent:l,active:d,activeNodeRect:c,ariaDescribedById:p,draggableNodes:f,over:y}=u.useContext(Uo),{role:g=pf,roleDescription:m="draggable",tabIndex:h=0}=r??{},v=d?.id===t,b=u.useContext(v?ai:W2),[x,k]=Qr(),[w,_]=Qr(),S=E2(a,t),E=Oo(n);sn(()=>(f.set(t,{id:t,key:s,node:x,activatorNode:w,data:E}),()=>{const N=f.get(t);N&&N.key===s&&f.delete(t)}),[f,t]);const C=u.useMemo(()=>({role:g,tabIndex:h,"aria-disabled":o,"aria-pressed":v&&g===pf?!0:void 0,"aria-roledescription":m,"aria-describedby":p.draggable}),[o,g,h,v,m,p.draggable]);return{active:d,activatorEvent:l,activeNodeRect:c,attributes:C,isDragging:v,listeners:o?void 0:S,node:x,over:y,setNodeRef:k,setActivatorNodeRef:_,transform:b}}function F2(){return u.useContext(cf)}const K2="Droppable",V2={timeout:25};function U2(e){let{data:t,disabled:n=!1,id:o,resizeObserverConfig:r}=e;const s=ei(K2),{active:a,dispatch:l,over:d,measureDroppableContainers:c}=u.useContext(Uo),p=u.useRef({disabled:n}),f=u.useRef(!1),y=u.useRef(null),g=u.useRef(null),{disabled:m,updateMeasurementsFor:h,timeout:v}={...V2,...r},b=Oo(h??o),x=u.useCallback(()=>{if(!f.current){f.current=!0;return}g.current!=null&&clearTimeout(g.current),g.current=setTimeout(()=>{c(Array.isArray(b.current)?b.current:[b.current]),g.current=null},v)},[v]),k=ii({callback:x,disabled:m||!a}),w=u.useCallback((C,N)=>{k&&(N&&(k.unobserve(N),f.current=!1),C&&k.observe(C))},[k]),[_,S]=Qr(w),E=Oo(t);return u.useEffect(()=>{!k||!_.current||(k.disconnect(),f.current=!1,k.observe(_.current))},[_,k]),u.useEffect(()=>(l({type:it.RegisterDroppable,element:{id:o,key:s,disabled:n,node:_,rect:y,data:E}}),()=>l({type:it.UnregisterDroppable,key:s,id:o})),[o]),u.useEffect(()=>{n!==p.current.disabled&&(l({type:it.SetDroppableDisabled,id:o,key:s,disabled:n}),p.current.disabled=n)},[o,s,n,l]),{active:a,rect:y,isOver:d?.id===o,node:_,over:d,setNodeRef:S}}function q2(e){let{animation:t,children:n}=e;const[o,r]=u.useState(null),[s,a]=u.useState(null),l=Rr(n);return!n&&!o&&l&&r(l),sn(()=>{if(!s)return;const d=o?.key,c=o?.props.id;if(d==null||c==null){r(null);return}Promise.resolve(t(c,s)).then(()=>{r(null)})},[t,o,s]),u.createElement(u.Fragment,null,n,o?u.cloneElement(o,{ref:a}):null)}const G2={x:0,y:0,scaleX:1,scaleY:1};function Y2(e){let{children:t}=e;return u.createElement(Uo.Provider,{value:df},u.createElement(ai.Provider,{value:G2},t))}const X2={position:"fixed",touchAction:"none"},J2=e=>la(e)?"transform 250ms ease":void 0,Z2=u.forwardRef((e,t)=>{let{as:n,activatorEvent:o,adjustScale:r,children:s,className:a,rect:l,style:d,transform:c,transition:p=J2}=e;if(!l)return null;const f=r?c:{...c,scaleX:1,scaleY:1},y={...X2,width:l.width,height:l.height,top:l.top,left:l.left,transform:Wo.Transform.toString(f),transformOrigin:r&&o?B7(o,l):void 0,transition:typeof p=="function"?p(o):p,...d};return u.createElement(n,{className:a,style:y,ref:t},s)}),Q2={duration:250,easing:"ease",keyframes:e=>{let{transform:{initial:t,final:n}}=e;return[{transform:Wo.Transform.toString(t)},{transform:Wo.Transform.toString(n)}]},sideEffects:(e=>t=>{let{active:n,dragOverlay:o}=t;const r={},{styles:s,className:a}=e;if(s!=null&&s.active)for(const[l,d]of Object.entries(s.active))d!==void 0&&(r[l]=n.node.style.getPropertyValue(l),n.node.style.setProperty(l,d));if(s!=null&&s.dragOverlay)for(const[l,d]of Object.entries(s.dragOverlay))d!==void 0&&o.node.style.setProperty(l,d);return a!=null&&a.active&&n.node.classList.add(a.active),a!=null&&a.dragOverlay&&o.node.classList.add(a.dragOverlay),function(){for(const[d,c]of Object.entries(r))n.node.style.setProperty(d,c);a!=null&&a.active&&n.node.classList.remove(a.active)}})({styles:{active:{opacity:"0"}}})};function R2(e){let{config:t,draggableNodes:n,droppableContainers:o,measuringConfiguration:r}=e;return Zr((s,a)=>{if(t===null)return;const l=n.get(s);if(!l)return;const d=l.node.current;if(!d)return;const c=lf(a);if(!c)return;const{transform:p}=_t(a).getComputedStyle(a),f=Hp(p);if(!f)return;const y=typeof t=="function"?t:eI(t);return Xp(d,r.draggable.measure),y({active:{id:s,data:l.data,node:d,rect:r.draggable.measure(d)},draggableNodes:n,dragOverlay:{node:a,rect:r.dragOverlay.measure(c)},droppableContainers:o,measuringConfiguration:r,transform:f})})}function eI(e){const{duration:t,easing:n,sideEffects:o,keyframes:r}={...Q2,...e};return s=>{let{active:a,dragOverlay:l,transform:d,...c}=s;if(!t)return;const p={x:l.rect.left-a.rect.left,y:l.rect.top-a.rect.top},f={scaleX:d.scaleX!==1?a.rect.width*d.scaleX/l.rect.width:1,scaleY:d.scaleY!==1?a.rect.height*d.scaleY/l.rect.height:1},y={x:d.x-p.x,y:d.y-p.y,...f},g=r({...c,active:a,dragOverlay:l,transform:{initial:d,final:y}}),[m]=g,h=g[g.length-1];if(JSON.stringify(m)===JSON.stringify(h))return;const v=o?.({active:a,dragOverlay:l,...c}),b=l.node.animate(g,{duration:t,easing:n,fill:"forwards"});return new Promise(x=>{b.onfinish=()=>{v?.(),x()}})}}let ff=0;function tI(e){return u.useMemo(()=>{if(e!=null)return ff++,ff},[e])}const nI=u.memo(e=>{let{adjustScale:t=!1,children:n,dropAnimation:o,style:r,transition:s,modifiers:a,wrapperElement:l="div",className:d,zIndex:c=999}=e;const{activatorEvent:p,active:f,activeNodeRect:y,containerNodeRect:g,draggableNodes:m,droppableContainers:h,dragOverlay:v,over:b,measuringConfiguration:x,scrollableAncestors:k,scrollableAncestorRects:w,windowRect:_}=F2(),S=u.useContext(ai),E=tI(f?.id),C=uf(a,{activatorEvent:p,active:f,activeNodeRect:y,containerNodeRect:g,draggingNodeRect:v.rect,over:b,overlayNodeRect:v.rect,scrollableAncestors:k,scrollableAncestorRects:w,transform:S,windowRect:_}),N=va(y),$=R2({config:o,draggableNodes:m,droppableContainers:h,measuringConfiguration:x}),A=N?v.setRef:void 0;return u.createElement(Y2,null,u.createElement(q2,{animation:$},f&&E?u.createElement(Z2,{key:E,id:f.id,ref:A,as:l,activatorEvent:p,adjustScale:t,className:d,transition:s,rect:N,style:{zIndex:c,...r},transform:C},n):null))});function qo(e,t){return!t||!Array.isArray(t.draggable)?!1:t.draggable.includes(e)}function oI({draggedComponentName:e,targetContainerName:t,nesting:n}){if(!n||!qo(e,n))return!1;const o=n.containers;if(!o||typeof o!="object")return!1;const r=o[t];return!r||!Array.isArray(r.accepts)?!1:r.accepts.includes(e)}function gf(e,t){if(!t?.containers)return!1;const n=t.containers[e];return!!(n&&Array.isArray(n.accepts)&&n.accepts.length>0)}function rI(e,t,n,o,r){if(!n||n.length===0)return{parentPath:[],index:r};if(e&&gf(e,o))return{parentPath:n,index:t};const s=n.slice(0,-1),a=n[n.length-1]??0;return{parentPath:s,index:a+1}}function hf(e,t){return e===t||e.startsWith(`${t}.`)}function yf(e,t){if(e==="")return/^\d+$/.test(t)?Number(t):null;const n=`${e}.children.`;if(!t.startsWith(n))return null;const o=t.slice(n.length);return/^\d+$/.test(o)?Number(o):null}function iI(e,t){const n=[];return e.querySelectorAll("[data-editor-path]").forEach(o=>{if(o.hasAttribute("data-dnd-placeholder")||o.closest("[data-dnd-placeholder]"))return;const r=o.dataset.editorPath;typeof r=="string"&&n.push({path:t(r),domPath:r,rect:o.getBoundingClientRect()})}),n}const sI=16;function aI(e){const{frameEl:t,draggedPath:n,acceptsContainer:o,allowsNestSlot:r,includeContainer:s}=e,a=e.normalizeContainerPath??(g=>g),l=t.getBoundingClientRect(),d=iI(t,a),c=new Map;for(const g of d)c.has(g.path)||c.set(g.path,g.domPath);const p=a(n),f=new Set([""]);for(const g of d){const m=dI(g.path);m!==null&&f.add(m)}for(const g of d)f.add(g.path);const y=[];for(const g of f){const m=g==="",h=m?null:c.get(g)??g,v=m?t:t.querySelector(`[data-editor-path="${vf(h)}"]`);if(!v&&!m||!m&&hf(g,p))continue;const b=g;if(!m&&s&&!s(b))continue;const x=S=>{const E=c.get(S);if(!E||typeof window>"u")return!1;const C=t.querySelector(`[data-editor-path="${vf(E)}"]`);return C?(window.getComputedStyle(C).display??"").toLowerCase()==="contents":!1},k=d.filter(S=>yf(g,S.path)!==null).filter(S=>!hf(S.path,p)).filter(S=>!x(S.path)).map(S=>({origIndex:yf(g,S.path),rect:lI(S.rect,S.path,d)})).filter(S=>S.rect.width>0||S.rect.height>0).sort((S,E)=>S.origIndex-E.origIndex),w=Ip(m?t:v).kind,_=w==="flex_row_single"||w==="flex_row_wrap"||w==="grid_single_row"||w==="grid_2d";if(k.length>0){if(o(b)){k.forEach(E=>{y.push(bf(b,E.origIndex,E.rect,l,_,"before"))});const S=k[k.length-1];y.push(bf(b,S.origIndex+1,S.rect,l,_,"after"))}}else if(!m&&r(b)&&v){const S=v.getBoundingClientRect();S.width>0&&S.height>0&&y.push({id:`slot:${b}:0`,kind:"nest",containerPath:b,index:0,box:mf(S,l),orientation:"area"})}else m&&y.push({id:"slot::0",kind:"gap",containerPath:"",index:0,box:mf(l,l),orientation:"area"})}return y.filter(g=>ao(g.box,t))}function bf(e,t,n,o,r,s){const a=sI;let l;if(r)l={left:(s==="before"?n.left:n.right)-a/2,top:n.top,width:a,height:n.height};else{const d=s==="before"?n.top:n.bottom;l={left:n.left,top:d-a/2,width:n.width,height:a}}return{id:`slot:${e}:${t}`,kind:"gap",containerPath:e,index:t,box:{left:l.left-o.left,top:l.top-o.top,width:l.width,height:l.height,scale:1},orientation:r?"vertical":"horizontal"}}function lI(e,t,n){if(e.width>0||e.height>0)return e;const o=`${t}.children.`;let r=1/0,s=1/0,a=-1/0,l=-1/0;for(const d of n)d.path.startsWith(o)&&(d.rect.width===0&&d.rect.height===0||(r=Math.min(r,d.rect.left),s=Math.min(s,d.rect.top),a=Math.max(a,d.rect.right),l=Math.max(l,d.rect.bottom)));return r===1/0?e:{left:r,top:s,width:a-r,height:l-s,right:a,bottom:l,x:r,y:s,toJSON:()=>({})}}function mf(e,t){return{left:e.left-t.left,top:e.top-t.top,width:e.width,height:e.height,scale:1}}function dI(e){if(e==="")return null;const t=e.lastIndexOf(".children.");return t<0?"":e.slice(0,t)}function cI(e){if(!e.startsWith("slot:"))return null;const t=e.slice(5),n=t.lastIndexOf(":");if(n<0)return null;const o=t.slice(0,n),r=Number(t.slice(n+1));return Number.isFinite(r)?{containerPath:o,index:r}:null}function vf(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/[^a-zA-Z0-9_\-.]/g,t=>`\\${t}`)}function _a(e){return typeof e=="string"&&e.length>0?e:null}function xa(e,t){return t&&e.startsWith(`${t}.`)?t:e}function _f(e){if(typeof e!="string")return null;const t=cI(e);return t?{containerPath:t.containerPath,index:t.index}:null}function wa(e,t){return t?e.startsWith(`${t}.iteration.`):!1}function ka(e,t,n){return t?n==="iteration_item"?wa(e,t):e===t||e.startsWith(`${t}.`):!1}function uI(e){const{frameEl:t,nesting:n,editMode:o,currentExtensionId:r,editableRootPath:s,components:a,patchLayout:l,pushHistory:d,onMovePath:c,selectedPath:p,showBranchBoundaryHint:f}=e,y=(o==="iteration_item"||o==="modal")&&s&&s.length>0?at(s):null,[g,m]=u.useState(null),[h,v]=u.useState(null),[b,x]=u.useState(null),k=u.useRef({components:a,nesting:n,editMode:o,currentExtensionId:r,selectedPath:p,editableRootSourcePath:y});k.current={components:a,nesting:n,editMode:o,currentExtensionId:r,selectedPath:p,editableRootSourcePath:y};const w=u.useRef(null),_=u.useCallback(M=>({children:M}),[]),S=u.useCallback((M,B)=>{const T=We(_(M),B);return T?typeof T.name=="string"?T.name:typeof T.type=="string"?T.type:null:null},[_]),E=u.useCallback(M=>B=>{const T=k.current;if(B==="")return qo(M,T.nesting);const H=Ze(B),L=We(_(T.components),H);if(!L)return!1;const I=typeof L.name=="string"?L.name:typeof L.type=="string"?L.type:"";if(!I)return!1;const P=!!T.editableRootSourcePath&&(B===T.editableRootSourcePath||B.startsWith(`${T.editableRootSourcePath}.`));if(T.editableRootSourcePath&&!P)return!1;if(!P){const F=Sa(_(T.components),H);if(gn(L,T.editMode,T.currentExtensionId,F)!=="none")return!1}return gf(I,T.nesting)?oI({draggedComponentName:M,targetContainerName:I,nesting:T.nesting}):!1},[_]),C=u.useCallback(M=>{if(M==="")return!0;const B=k.current,T=Ze(M),H=w.current;if(H&&H.length>0){const P=H.slice(0,-1);if(li(T,P))return!0}const L=We(_(B.components),T);return L?(typeof L.name=="string"?L.name:typeof L.type=="string"?L.type:"").length>0:!1},[_]),N=u.useCallback(M=>{const B=E(M),T=k.current,H=w.current,L=H?H.slice(0,-1):null,I=new Set;if(L)for(let V=L.length;V>=0;V--)I.add(di(L.slice(0,V)));const P=di(H??[]),F=V=>!!H&&(V===P||V.startsWith(`${P}.`)),G=(V,Y)=>{for(let Z=0;ZV===""?!0:F(V)?!1:I.has(V),allowsNestSlot:V=>{if(!B(V))return!1;if(L){const Y=Ze(V);if(li(Y,L))return!1}return C(V)}}},[E,C,_]),$=u.useCallback(M=>{const B=_a(M.active.id),T=k.current;if(!B)return;const H=xa(B,T.selectedPath),L=Ze(H),I=We(_(T.components),L),P=I&&typeof I.name=="string"?I.name:I&&typeof I.type=="string"?I.type:null;m(H),v(P),x(null),w.current=I?L:null;let F="allowed";if(!P||!qo(P,T.nesting))F="denied_no_draggable";else if(I){const G=Sa(_(T.components),L),V=gn(I,T.editMode,T.currentExtensionId,G);T.editableRootSourcePath&&!ka(H,T.editableRootSourcePath,T.editMode)||Xi(G)&&!wa(H,T.editableRootSourcePath)?F="denied_data_bound":V==="base"||V==="partial"?F="denied_base_locked":(V==="extension"||V==="extension_point")&&(F="denied_extension_locked")}$n({source:"drag",draggedComponentName:P,targetContainerName:null,targetContainerPath:null,decision:F,result:F==="allowed"?"completed":"denied",timestamp:Date.now()})},[_]),A=u.useCallback(M=>{if(!t)return;const B=_a(M.active.id);if(!B)return;const T=h;if(!T){x(null);return}const H=k.current,L=xa(B,H.selectedPath),I=Ze(L),P=We(_(H.components),I);if(!P||!qo(T,H.nesting)){x(null);return}const F=Sa(_(H.components),I);if(H.editableRootSourcePath&&!ka(L,H.editableRootSourcePath,H.editMode)){x(null);return}const G=gn(P,H.editMode,H.currentExtensionId,F),V=wa(L,H.editableRootSourcePath);if(Xi(F)&&!V||G!=="none"&&G!=="data_bound"&&!V){x(null);return}x(_f(M.over?.id))},[t,h,_]),z=u.useCallback(()=>{m(null),v(null),x(null),w.current=null},[]),D=u.useCallback(M=>{const B=_a(M.active.id),T=h,H=k.current,L=B?xa(B,H.selectedPath):null;if(!t||!L||!T){z();return}const I=_f(M.over?.id),P=Ze(L);if(!I){$n({source:"drag",draggedComponentName:T,targetContainerName:null,targetContainerPath:null,decision:"denied_no_accepts",result:"cancelled",timestamp:Date.now()}),z();return}const F=I.containerPath===""?[]:Ze(I.containerPath),G=I.containerPath===""?null:S(H.components,F);if(!pI(P.slice(0,-1),F)){$n({source:"drag",draggedComponentName:T,targetContainerName:G,targetContainerPath:I.containerPath||null,decision:"denied_responsive_branch_boundary",result:"denied",timestamp:Date.now()}),f?.(),z();return}if(H.editableRootSourcePath&&!ka(I.containerPath,H.editableRootSourcePath,H.editMode)){$n({source:"drag",draggedComponentName:T,targetContainerName:G,targetContainerPath:I.containerPath||null,decision:"denied_data_bound",result:"denied",timestamp:Date.now()}),z();return}const V=P.slice(0,-1),Y=P[P.length-1]??-1;if(li(V,F)&&(I.index===Y||I.index===Y+1)){$n({source:"drag",draggedComponentName:T,targetContainerName:G,targetContainerPath:I.containerPath||null,decision:"allowed",insertionIndex:I.index,result:"cancelled",timestamp:Date.now()}),z();return}const re=li(V,F),U=I.index;let ee=[];l(me=>{const Se=Ib({children:me},P,F,U).children??[];return ee=Se,Se}),d(ee,`move ${T}`);const fe=id(F,P),K=re&&Y{z()},[z]);return{activeDragPath:g,activeDragName:h,activeDropZone:b,onDragStart:$,onDragMove:A,onDragEnd:D,onDragCancel:O,buildSlotPredicates:N}}function Sa(e,t){const n=[];let o=e,r=Array.isArray(e.children)?e.children:[];for(let s=0;s0?at(s):null,{t:m}=tt(),[h,v]=u.useState(!1),b=u.useRef(null),x=u.useCallback(()=>{v(!0),b.current&&clearTimeout(b.current),b.current=setTimeout(()=>v(!1),2600)},[]);u.useEffect(()=>()=>{b.current&&clearTimeout(b.current)},[]);const k=uI({frameEl:t,nesting:n,editMode:o,currentExtensionId:r,editableRootPath:s,components:a,patchLayout:l,pushHistory:d,onMovePath:p,selectedPath:y,showBranchBoundaryHint:x}),w=P7(L7(ha,{activationConstraint:{distance:8}})),[_,S]=u.useState([]),E=u.useCallback(()=>{if(!t){S([]);return}if(k.activeDragPath!==null)return;const L={children:a},I=t.querySelectorAll("[data-editor-path]"),P=[],F=new Map;I.forEach(G=>{const V=G.dataset.editorPath;if(typeof V!="string"||o!=="iteration_item"&&g&&!hI(V,g,o))return;const Y=fI(V);if(Y!==null&&!Go(V,g)){if(/\.iteration\.\d+$/.test(V)){const K=so(G,t);if(K&&ao(K,t)){const ne=F.get(Y)??[];ne.push(K),F.set(Y,ne)}}return}if(Go(V,g)&&/\.iteration\.\d+$/.test(V))return;const Z=Ze(V),se=We(L,Z);if(!se||se.iteration&&se.iteration.source!==void 0)return;const re=typeof se.name=="string"?se.name:typeof se.type=="string"?se.type:null;if(!re||!qo(re,n))return;const U=wf(L,Z);if(Xi(U)&&!Go(V,g))return;const ee=gn(se,o,r,U);if(ee!=="none"&&ee!=="data_bound"&&!Go(V,g))return;const fe=so(G,t);fe&&ao(fe,t)&&P.push({path:V,name:re,box:fe})});for(const[G,V]of F){const Y=Ze(G),Z=We(L,Y);if(!Z)continue;const se=typeof Z.name=="string"?Z.name:typeof Z.type=="string"?Z.type:null;if(!se)continue;const re=wf(L,Y),U=gn(Z,o,r,re);if(U!=="none"&&U!=="data_bound")continue;const ee=yI(V);ee&&ao(ee,t)&&P.push({path:G,name:se,box:ee,isIterationGroup:!0})}S(P)},[t,a,n,o,r,g,k.activeDragPath]);u.useEffect(()=>{E()},[E]),u.useEffect(()=>{if(t)return kp(E,t)},[t,E]);const C=k.activeDragPath!==null,N=k.activeDragName,$=k.activeDragPath,[A,z]=u.useState(null),D=u.useRef(null);u.useEffect(()=>{if(!$||!t){$||(D.current=null,z(null));return}if(D.current===$)return;D.current=$;const L=t.querySelector(`[data-editor-path="${xf($)}"]`);if(L){const re=L.getBoundingClientRect();z({node:L.cloneNode(!0),width:re.width,height:re.height});return}const I=Array.from(t.querySelectorAll(`[data-editor-path^="${xf($)}.iteration."]`)).filter(re=>/\.iteration\.\d+$/.test(re.dataset.editorPath??""));if(I.length===0){z(null);return}let P=1/0,F=1/0,G=-1/0,V=-1/0;for(const re of I){const U=re.getBoundingClientRect();P=Math.min(P,U.left),F=Math.min(F,U.top),G=Math.max(G,U.right),V=Math.max(V,U.bottom)}const Y=G-P,Z=V-F,se=document.createElement("div");se.style.position="relative",se.style.width=`${Y}px`,se.style.height=`${Z}px`;for(const re of I){const U=re.getBoundingClientRect(),ee=re.cloneNode(!0);ee.style.position="absolute",ee.style.left=`${U.left-P}px`,ee.style.top=`${U.top-F}px`,ee.style.width=`${U.width}px`,ee.style.height=`${U.height}px`,ee.style.margin="0",se.appendChild(ee)}z({node:se,width:Y,height:Z})},[$,t]);const[O,M]=u.useState([]),B=u.useRef(null),T=u.useRef(k.buildSlotPredicates);if(T.current=k.buildSlotPredicates,u.useEffect(()=>{if(!$||!N||!t){B.current=null,M(F=>F.length===0?F:[]);return}if(B.current===$)return;B.current=$;const{acceptsContainer:L,allowsNestSlot:I,includeContainer:P}=T.current(N);M(aI({frameEl:t,draggedPath:$,acceptsContainer:L,allowsNestSlot:I,includeContainer:P,normalizeContainerPath:F=>gI(F)}))},[$,N,t]),!t)return null;const H=k.activeDropZone?`slot:${k.activeDropZone.containerPath}:${k.activeDropZone.index}`:null;return i.jsxs(B2,{sensors:w,collisionDetection:q7,onDragStart:k.onDragStart,onDragMove:k.onDragMove,onDragEnd:k.onDragEnd,onDragCancel:k.onDragCancel,children:[_.map(L=>i.jsx(_I,{path:L.path,name:L.name,box:L.box,dimmed:C&&k.activeDragPath!==L.path,isIterationGroup:L.isIterationGroup,onSelect:c,onRequestInlineEdit:f},L.path)),C&&O.map(L=>i.jsx(vI,{slot:L,active:L.id===H},L.id)),Cn.createPortal(i.jsx(nI,{dropAnimation:null,zIndex:zp,children:N?A?i.jsx(mI,{name:N,node:A.node,width:A.width,height:A.height}):i.jsx("div",{className:"g7le-dnd-drag-ghost","data-testid":"g7le-dnd-drag-ghost",style:{padding:"4px 10px",background:"rgba(79,70,229,0.95)",color:"#fff",fontSize:12,fontWeight:600,borderRadius:4,pointerEvents:"none",whiteSpace:"nowrap"},children:`<${N}>`}):null}),document.body),h&&Cn.createPortal(i.jsxs("div",{"data-testid":"g7le-branch-boundary-hint",role:"status",style:{position:"absolute",left:"50%",top:12,transform:"translateX(-50%)",background:"rgba(245,158,11,0.97)",color:"#fff",fontSize:13,fontWeight:600,padding:"8px 16px",borderRadius:8,boxShadow:"0 4px 14px rgba(0,0,0,0.2)",pointerEvents:"none",whiteSpace:"nowrap",zIndex:zp},children:["⚠️ ",m("layout_editor.overlay.branch_boundary_denied")]}),t)]})}function mI(e){const{node:t,width:n,height:o}=e,r=u.useRef(null);return u.useEffect(()=>{const s=r.current;if(s)return s.replaceChildren(),s.appendChild(t.cloneNode(!0)),()=>{s.replaceChildren()}},[t]),i.jsx("div",{ref:r,className:"g7le-dnd-drag-ghost","data-testid":"g7le-dnd-drag-ghost",style:{width:n,height:o,opacity:.7,pointerEvents:"none",boxShadow:"0 6px 18px rgba(0,0,0,0.25)",borderRadius:4,overflow:"hidden",cursor:"grabbing"}})}function vI(e){const{slot:t,active:n}=e,{setNodeRef:o}=U2({id:t.id}),r=t.orientation!=="area";return i.jsx("div",{ref:o,"data-testid":`g7le-dnd-slot-${t.id}`,"data-dnd-slot-id":t.id,style:{position:"absolute",left:t.box.left,top:t.box.top,width:t.box.width,height:t.box.height,pointerEvents:"auto",zIndex:u7,boxSizing:"border-box",...r?{background:n?"rgba(79,70,229,0.15)":"transparent",...n?t.orientation==="vertical"?{borderLeft:"2px solid #4f46e5"}:{borderTop:"2px solid #4f46e5"}:{}}:{border:n?"2px dashed #4f46e5":"1px dashed transparent",background:n?"rgba(79,70,229,0.08)":"transparent",borderRadius:4}}})}function xf(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/[^a-zA-Z0-9_\-.]/g,t=>`\\${t}`)}function _I(e){const{path:t,box:n,dimmed:o,isIterationGroup:r,onSelect:s,onRequestInlineEdit:a}=e,{attributes:l,listeners:d,setNodeRef:c,isDragging:p}=H2({id:t}),f=(t.match(/\.children\./g)||[]).length,y=p7(f);return i.jsx("div",{ref:c,"data-testid":`g7le-dnd-handle-${t}`,"data-dnd-handle-path":t,"data-dnd-iteration-group":r?"true":void 0,...d,...l,onClick:g=>{if(g.stopPropagation(),!r&&typeof document<"u"&&typeof document.elementsFromPoint=="function"){const m=document.elementsFromPoint(g.clientX,g.clientY);for(const h of m){const b=h.closest?.("[data-editor-path]")?.dataset?.editorPath;if(typeof b=="string"&&(b===t||b.startsWith(`${t}.`))){s(b);return}}}s(t)},onDoubleClick:g=>{g.stopPropagation(),g.preventDefault(),a?.(t)},style:{position:"absolute",left:n.left,top:n.top,width:n.width,height:n.height,cursor:"grab",pointerEvents:"auto",background:p?"rgba(79,70,229,0.06)":"transparent",...r?{border:"1px dashed rgba(79,70,229,0.5)",borderRadius:4}:{},opacity:o?.6:1,zIndex:y,touchAction:"none"}})}function wf(e,t){const n=[];let o=e,r=Array.isArray(e.children)?e.children:[];for(let s=0;s0?[o]:[];const r=[],s=(a,l)=>{a.forEach((d,c)=>{const p=[...l,c];if(!Ji(d,t,n)){r.push(p);return}const y=Array.isArray(d.children)?d.children:[];y.length>0&&s(y,p)})};return s(e,[]),r}function wI(e){return at(e)}function ci(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/["\\]/g,"\\$&")}function kI({frameEl:e,components:t,editMode:n,currentExtensionId:o,editableRootPath:r}){const[s,a]=u.useState(null),[l]=u.useState(()=>`g7le-dim-mask-${Math.floor(Math.random()*1e9)}`);if(u.useEffect(()=>{if(!e){a(null);return}let g=0;const m=()=>{const x=xI(t,n,o,r);if(x.length===0){a(null);return}const k=e.getBoundingClientRect(),w={left:0,top:0,width:k.width,height:k.height},_=[];for(const S of x){const E=wI(S),C=e.querySelector(`[data-editor-path="${ci(E)}"]`);let N=null;if(C){const $=C.getBoundingClientRect();$.width>0&&$.height>0&&(N={left:$.left,top:$.top,width:$.width,height:$.height})}if(!N){const $=Array.from(e.querySelectorAll(`[data-editor-path^="${ci(E)}.iteration."], [data-editor-path^="${ci(E)}.sortable."], [data-editor-path^="${ci(E)}.children."]`));let A=1/0,z=1/0,D=-1/0,O=-1/0;for(const M of $){const B=M.getBoundingClientRect();B.width<=0||B.height<=0||(A=Math.min(A,B.left),z=Math.min(z,B.top),D=Math.max(D,B.right),O=Math.max(O,B.bottom))}if(D>A&&O>z&&(N={left:A,top:z,width:D-A,height:O-z}),N&&$.length>0){const M=$[0].closest('[role="dialog"]');if(M&&e.contains(M)){const B=M.getBoundingClientRect();B.width>0&&B.height>0&&(N={left:B.left,top:B.top,width:B.width,height:B.height})}}}N&&_.push({left:N.left-k.left,top:N.top-k.top,width:N.width,height:N.height})}if(_.length===0){a(null);return}a({frame:w,holes:_})},h=()=>{g&&cancelAnimationFrame(g),g=requestAnimationFrame(m)};h();const v=typeof ResizeObserver<"u"?new ResizeObserver(h):null;v?.observe(e);const b=typeof MutationObserver<"u"?new MutationObserver(h):null;return b?.observe(e,{childList:!0,subtree:!0,attributes:!0}),window.addEventListener("scroll",h,!0),window.addEventListener("resize",h),()=>{g&&cancelAnimationFrame(g),v?.disconnect(),b?.disconnect(),window.removeEventListener("scroll",h,!0),window.removeEventListener("resize",h)}},[e,t,n,o,r?.join(".")??""]),!s||s.holes.length===0)return null;const{frame:d,holes:c}=s,p=n==="modal"||n==="iteration_item";let f=[];if(p){let g=1/0,m=1/0,h=-1/0,v=-1/0;for(const S of c)g=Math.min(g,S.left),m=Math.min(m,S.top),h=Math.max(h,S.left+S.width),v=Math.max(v,S.top+S.height);const b=(S,E,C)=>Math.max(E,Math.min(C,S)),x=b(g,0,d.width),k=b(m,0,d.height),w=b(h,0,d.width),_=b(v,0,d.height);f=[{left:0,top:0,width:d.width,height:k},{left:0,top:_,width:d.width,height:d.height-_},{left:0,top:k,width:x,height:_-k},{left:w,top:k,width:d.width-w,height:_-k}].filter(S=>S.width>0&&S.height>0)}const y=g=>{g.preventDefault(),g.stopPropagation()};return i.jsxs(i.Fragment,{children:[f.map((g,m)=>i.jsx("div",{className:"g7le-source-lock-block","data-testid":"g7le-source-lock-block",onClickCapture:y,onPointerDownCapture:y,onMouseDownCapture:y,onDragStartCapture:y,style:{position:"absolute",left:g.left,top:g.top,width:g.width,height:g.height,zIndex:Np,pointerEvents:"auto",cursor:"not-allowed",background:"transparent"}},m)),i.jsxs("svg",{className:"g7le-source-lock-dim","data-testid":"g7le-source-lock-dim",width:d.width,height:d.height,style:{position:"absolute",left:0,top:0,width:d.width,height:d.height,zIndex:Np,pointerEvents:"none"},children:[i.jsx("defs",{children:i.jsxs("mask",{id:l,children:[i.jsx("rect",{x:0,y:0,width:d.width,height:d.height,fill:"white"}),c.map((g,m)=>i.jsx("rect",{"data-testid":"g7le-source-lock-dim-hole",x:g.left,y:g.top,width:g.width,height:g.height,rx:4,fill:"black"},m))]})}),i.jsx("rect",{"data-testid":"g7le-source-lock-dim-box",x:0,y:0,width:d.width,height:d.height,fill:"rgba(15, 23, 42, 0.45)",mask:`url(#${l})`})]})]})}function kf(e){const t={type:e.type??"basic",name:e.name},n={};if(e.props)for(const[o,r]of Object.entries(e.props))o!=="children"&&r?.default!==void 0&&(n[o]=r.default);return Object.keys(n).length>0&&(t.props=n),t}function SI(e){if(!e?.components)return[];const t=[];for(const[n,o]of Object.entries(e.components))if(Array.isArray(o))for(const r of o)t.push({...r,type:r.type??n});return t}function CI(e,t,n,o,r){const s=SI(e);let a=null;if(n&&t?.containers){const l=t.containers[n];l&&Array.isArray(l.accepts)?a=new Set(l.accepts):a=new Set}else!n&&t?.draggable&&(a=new Set(t.draggable));return s.filter(l=>{if(a&&!a.has(l.name))return!1;if(o){const d=o.toLowerCase(),c=r(l).toLowerCase(),p=l.name.toLowerCase();if(!c.includes(d)&&!p.includes(d)&&!`<${p}>`.includes(d)&&!(l.description??"").toLowerCase().includes(d))return!1}return!0})}function $I(e,t){const n={key:"all",label:"layout_editor.palette.category.all",entries:e,isI18nKey:!0};if(t?.groups&&t.groups.length>0){const a=new Map(e.map(p=>[p.name,p])),l=new Set,d=[];for(const p of t.groups){const f=[];for(const y of p.components??[]){const g=a.get(y);g&&(f.push(g),l.add(y))}f.length!==0&&d.push({key:p.kind??p.label,label:p.label,entries:f,isI18nKey:p.label.startsWith("$t:")||/^[a-z_.]+$/i.test(p.label)})}const c=e.filter(p=>!l.has(p.name));return c.length>0&&d.push({key:"other",label:"layout_editor.palette.category.other",entries:c,isI18nKey:!0}),[n,...d]}const o=new Map;for(const a of e){const l=(a.type??"basic").toLowerCase(),d=o.get(l)??[];d.push(a),o.set(l,d)}const r=["basic","composite","layout"],s=[];for(const a of r){const l=o.get(a);l&&l.length>0&&(s.push({key:a,label:`layout_editor.palette.category.fallback.${a}`,entries:l,isI18nKey:!0}),o.delete(a))}for(const[a,l]of o.entries())s.push({key:a,label:a,entries:l,isI18nKey:!1});return[n,...s]}function Sf(e){const{manifest:t,nesting:n,componentPalette:o,targetParentPath:r,targetContainerName:s,onInsert:a,insertionIndex:l,onClose:d,editorTemplateId:c,editorLocale:p}=e,{t:f,translationEngine:y}=tt(),g=u.useMemo(()=>{if(!c||!y)return f;const A=p??null;return z=>{const D={templateId:c,locale:A??"ko"},O=y.translate(z,D);return O!==z?O:f(z)}},[c,p,y,f]),[m,h]=u.useState(""),[v,b]=u.useState("all"),x=o?.entries??null,k=u.useMemo(()=>A=>{const z=x?.[A.name];return z?.label?ui(z.label,g):A.description??A.name},[x,g]),w=u.useMemo(()=>CI(t,n,s,m,k),[t,n,s,m,k]),_=u.useMemo(()=>$I(w,o??null),[w,o]),S=_.find(A=>A.key===v)??_[0]??null,E=!n||!n.draggable&&!n.containers,C=w.length===0,N=S?.entries??[],$=A=>{const z=x?.[A.name],D=!!z?.defaultNode&&typeof z.defaultNode=="object";if(z?.requiresDefaultNode&&!D)return;const O=D?JSON.parse(JSON.stringify(z.defaultNode)):kf(A),M=r??[];a(O,M,l),$n({source:"palette",draggedComponentName:A.name,targetContainerName:s,targetContainerPath:M.length===0?null:M.join("/"),decision:"allowed",insertionIndex:l,result:"completed",timestamp:Date.now()}),d()};return i.jsxs("div",{className:"g7le-palette","data-testid":"g7le-palette",style:TI,children:[i.jsxs("div",{style:DI,children:[i.jsx("strong",{style:{fontSize:16},children:f("layout_editor.palette.title")}),i.jsx("button",{type:"button",onClick:d,"aria-label":"close","data-testid":"g7le-palette-close",style:NI,children:"×"})]}),i.jsxs("div",{style:zI,children:[i.jsx("aside",{style:MI,"data-testid":"g7le-palette-sidebar",children:i.jsx("nav",{children:i.jsx("ul",{style:LI,children:_.map(A=>{const z=S?.key===A.key,D=A.isI18nKey?ui(A.label,g):A.label;return i.jsx("li",{children:i.jsxs("button",{type:"button","data-testid":`g7le-palette-category-${A.key}`,"data-active":z?"true":"false",onClick:()=>b(A.key),style:{...PI,background:z?"#eff6ff":"transparent",color:z?"#1d4ed8":"#334155",fontWeight:z?600:500},children:[i.jsx("span",{children:D}),i.jsx("span",{style:jI,children:A.entries.length})]})},A.key)})})})}),i.jsxs("main",{style:OI,children:[i.jsx("input",{type:"text",placeholder:f("layout_editor.palette.search_placeholder"),value:m,onChange:A=>h(A.target.value),"data-testid":"g7le-palette-search",style:BI}),i.jsx("div",{style:WI,children:E?i.jsx("div",{style:Cf,"data-testid":"g7le-palette-spec-missing",children:f("layout_editor.palette.spec_missing")}):C||N.length===0?i.jsx("div",{style:Cf,"data-testid":"g7le-palette-empty",children:f("layout_editor.palette.empty")}):i.jsx("div",{"data-testid":`g7le-palette-group-${S?.key??"all"}`,style:{marginBottom:16},children:i.jsx("div",{style:HI,children:N.map(A=>i.jsx(EI,{entry:A,entrySpec:x?.[A.name]??null,onClick:$,t:f,entryT:g},A.name))})})})]})]})]})}function EI(e){const{entry:t,entrySpec:n,onClick:o,t:r,entryT:s}=e,a=n?.label?ui(n.label,s):t.description??t.name,l=(t.type??"").toLowerCase(),d=l==="basic"||l==="composite"||l==="layout",c=!!n?.defaultNode&&typeof n.defaultNode=="object",p=!!n?.requiresDefaultNode&&!c,f=!c,y=p?r("layout_editor.palette.requires_default_node_missing"):n?.label?ui(n.label,s):t.name;return i.jsxs("button",{type:"button",onClick:()=>o(t),disabled:p,"aria-disabled":p||void 0,"data-testid":`g7le-palette-item-${t.name}`,"data-component-type":l||void 0,"data-blocked":p?"true":void 0,"data-default-node-missing":f?"true":void 0,title:y,style:p?KI:FI,children:[i.jsx("div",{style:UI,"aria-hidden":"true",children:AI(t)}),i.jsx("div",{style:qI,children:a}),i.jsx("div",{"data-testid":`g7le-palette-item-${t.name}-tag`,style:GI,children:`<${t.name}>`}),d&&i.jsx("div",{"data-testid":`g7le-palette-item-${t.name}-badge`,style:II(l),children:l}),f&&i.jsx("div",{"data-testid":`g7le-palette-item-${t.name}-default-missing-badge`,style:VI,children:r("layout_editor.palette.default_node_missing_badge")})]})}function ui(e,t){return e.startsWith("$t:")?t(e.slice(3)):t(e)}function II(e){const n={basic:{bg:"#dbeafe",fg:"#1e40af"},composite:{bg:"#dcfce7",fg:"#14532d"},layout:{bg:"#fef3c7",fg:"#854d0e"}}[e]??{bg:"#e2e8f0",fg:"#334155"};return{fontSize:9,fontWeight:600,color:n.fg,background:n.bg,padding:"1px 6px",borderRadius:999,textTransform:"uppercase",letterSpacing:.4,lineHeight:1.6}}function AI(e){const t=e.name;return{Button:"🔘",A:"🔗",Img:"🖼",Icon:"✨",Hr:"➖",P:"📄",Span:"T",H1:"H₁",H2:"H₂",H3:"H₃",H4:"H₄",Ul:"☰",Li:"•",Nav:"🧭",Div:"▢",Container:"▢",Flex:"⇆",Grid:"▦",SectionLayout:"▤",ThreeColumnLayout:"⫼",Form:"📝",Input:"⎕",Textarea:"▭",Select:"⏷",Checkbox:"☑",PasswordInput:"🔒",Label:"🏷",DataGrid:"▦",Pagination:"↔",SearchBar:"🔍",ProductCard:"🛍",ImageGallery:"🖼",Avatar:"👤",UserInfo:"👥",HtmlContent:"⟨/⟩",HtmlEditor:"✏",RichTextEditor:"✏",TabNavigation:"◰",QuantitySelector:"#",ProductImageViewer:"🖼",FileUploader:"📎",AvatarUploader:"📷",SocialLoginButtons:"🌐",PostReactions:"❤"}[t]??"◻"}const TI={display:"flex",flexDirection:"column",width:"100%",height:"100%",minHeight:0,fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Apple SD Gothic Neo", "Noto Sans KR", sans-serif'},DI={display:"flex",justifyContent:"space-between",alignItems:"center",padding:"14px 20px",borderBottom:"1px solid #e2e8f0",flexShrink:0},NI={background:"transparent",border:"none",fontSize:24,cursor:"pointer",lineHeight:1,color:"#64748b",padding:"0 4px"},zI={display:"flex",flex:1,minHeight:0},MI={width:180,flexShrink:0,borderRight:"1px solid #e2e8f0",padding:"14px 8px",background:"#f8fafc",overflowY:"auto"},LI={listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:4},PI={display:"flex",width:"100%",alignItems:"center",justifyContent:"space-between",textAlign:"left",padding:"8px 12px",border:"none",borderRadius:6,fontSize:13,cursor:"pointer",transition:"background-color 120ms"},OI={flex:1,display:"flex",flexDirection:"column",minHeight:0,padding:"14px 20px"},BI={width:"100%",padding:"8px 10px",border:"1px solid #cbd5e1",borderRadius:6,marginBottom:12,fontSize:13,flexShrink:0,boxSizing:"border-box"},WI={flex:1,overflowY:"auto",minHeight:0},jI={fontSize:11,color:"#94a3b8",marginLeft:8,fontWeight:500},HI={display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(96px, 1fr))",gap:10},FI={display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:6,padding:"14px 6px",background:"#fff",border:"1px solid #e2e8f0",borderRadius:8,cursor:"pointer",fontSize:12,minHeight:84,transition:"border-color 120ms, box-shadow 120ms"},KI={display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:6,padding:"14px 6px",background:"#f8fafc",border:"1px dashed #cbd5e1",borderRadius:8,cursor:"not-allowed",fontSize:12,minHeight:84,color:"#94a3b8",opacity:.65},VI={fontSize:9,fontWeight:600,color:"#92400e",background:"#fef3c7",padding:"1px 6px",borderRadius:999,textTransform:"none",letterSpacing:0,lineHeight:1.6},UI={fontSize:22,lineHeight:1,color:"#475569"},qI={fontSize:12,fontWeight:500,color:"#0f172a",textAlign:"center",wordBreak:"break-word"},GI={fontFamily:'ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace',fontSize:10,color:"#64748b",textAlign:"center",wordBreak:"break-all"},Cf={padding:24,color:"#64748b",fontSize:13,textAlign:"center"};function YI(e){const t=[],n=r=>{if(Array.isArray(r))for(const s of r)s&&typeof s=="object"&&t.push(s)};n(e.children);const o=e.responsive;if(o&&typeof o=="object")for(const r of Object.values(o))r&&typeof r=="object"&&n(r.children);return t}function $f(e){const t=[],n=o=>{const r="isolatedState"in o&&o.isolatedState!=null,s=o.isolatedScopeId;(r||typeof s=="string"&&s.length>0)&&t.push({scopeId:typeof s=="string"?s:void 0,initialState:o.isolatedState&&typeof o.isolatedState=="object"?o.isolatedState:void 0});for(const a of YI(o))n(a)};if(Array.isArray(e))for(const o of e)o&&typeof o=="object"&&n(o);return t}const XI=["scroll","selector","wizard","slider"];function JI(e,t){const n=new Set;for(const o of e)o.scopeId&&n.add(o.scopeId);for(const o of t){n.add(o);for(const r of XI)n.add(`${o}-${r}`)}return Array.from(n)}function ZI(e,t,n){const o=t.label;return typeof o=="string"?o.startsWith("$t:")?n(o.slice(3)):o:e}function pi({controlKey:e,control:t,node:n,t:o,onPatch:r,candidates:s,bindingCandidates:a,scope:l=Wt}){const d=Tn(t.widget),c=ZI(e,t,o),p=u.useMemo(()=>To(n,t,l),[n,t,l]),f=t.widget==="i18n-text"&&t.apply?.type==="propValue",y=t.widget==="text"&&t.apply?.type==="propValue",g=p.darkReadonly===!0||l.colorScheme==="dark"&&t.apply!==void 0&&!Us(t.apply),m=t.apply,h=l.colorScheme==="dark"&&!g&&m?.type==="classToken"&&typeof m.tokenTemplate=="string"&&m.tokenTemplate.includes("{value}"),v=p.scopedValue===void 0&&p.baseFallback!==void 0,b=u.useCallback(x=>{if(g)return;const k=fn(n,t,x,l);r(k)},[n,t,r,l,g]);return i.jsxs("div",{className:"g7le-control-row","data-testid":`g7le-control-${e}`,style:QI,children:[i.jsxs("span",{className:"g7le-control-label",style:RI,children:[c,p.conflict&&i.jsx("span",{"data-testid":`g7le-control-conflict-${e}`,title:o("layout_editor.property_modal.value_conflict"),style:eA,children:"!"})]}),i.jsx("div",{className:"g7le-control-widget",style:{flex:1,minWidth:0,opacity:v?.45:1},"data-placeholder":v?"true":void 0,children:f?i.jsx(vt,{value:typeof p.value=="string"?p.value:"",onChange:x=>b(x),t:o,testidPrefix:`g7le-prop-i18n-${e}`,candidates:a,enableExpressionTree:!0,expressionTreeCollapsible:!0}):y?i.jsx(Ve,{value:typeof p.value=="string"?p.value:"",onChange:x=>b(x===""?void 0:x),t:o,testidPrefix:`g7le-prop-value-${e}`,candidates:a}):g?i.jsx("span",{"data-testid":`g7le-control-dark-readonly-${e}`,style:nA,children:o("layout_editor.property_modal.dark_code_only")}):d?i.jsx(d,{control:t,value:p.value,onChange:b,t:o,candidates:s,bindingCandidates:a,freeValueDisabled:h}):i.jsx("span",{"data-testid":`g7le-control-unsupported-${e}`,style:tA,children:o("layout_editor.property_modal.unsupported_widget")})})]})}const QI={display:"flex",alignItems:"center",gap:12,padding:"6px 0",minHeight:32,minWidth:0},RI={fontSize:12,color:"#475569",minWidth:88,display:"inline-flex",alignItems:"center",gap:4},eA={display:"inline-flex",width:14,height:14,borderRadius:7,background:"#f59e0b",color:"#fff",fontSize:10,alignItems:"center",justifyContent:"center",fontWeight:700},tA={fontSize:11,color:"#94a3b8",fontStyle:"italic"},nA={fontSize:11,color:"#94a3b8",fontStyle:"italic"};function fi(e,t,n){return typeof e=="string"?e.startsWith("$t:")?n(e.slice(3)):e:t}function oA(e,t){const n=e.props??{};return t.key in n?n[t.key]:t.default}function rA({spec:e,node:t,t:n,onPatchProp:o}){const r=e.groups??[];return i.jsx("div",{className:"g7le-composite-settings","data-testid":"g7le-composite-settings",style:sA,children:r.map((s,a)=>i.jsxs("div",{className:"g7le-settings-group",style:aA,children:[i.jsx("div",{style:lA,children:fi(s.label,n("layout_editor.property_modal.settings_group",{index:a+1}),n)}),(s.fields??[]).map(l=>i.jsxs("div",{className:"g7le-settings-field","data-testid":`g7le-setting-${l.key}`,style:dA,children:[i.jsx("span",{style:cA,children:fi(l.label,l.key,n)}),i.jsx("div",{style:{flex:1},children:iA(l,t,n,o)})]},l.key))]},a))})}function iA(e,t,n,o){const r=oA(t,e);switch(e.type){case"number":return i.jsx("input",{type:"number","data-testid":`g7le-setting-input-${e.key}`,value:typeof r=="number"?r:"",min:e.min,max:e.max,onChange:s=>o(e.key,s.target.value===""?void 0:Number(s.target.value)),style:Ca});case"text":return i.jsx("input",{type:"text","data-testid":`g7le-setting-input-${e.key}`,value:typeof r=="string"?r:"",onChange:s=>o(e.key,s.target.value===""?void 0:s.target.value),style:Ca});case"toggle":return i.jsx("input",{type:"checkbox","data-testid":`g7le-setting-input-${e.key}`,checked:r===!0,onChange:s=>o(e.key,s.target.checked)});case"checkbox-group":{const s=Array.isArray(r)?r:[];return i.jsx("div",{style:uA,"data-testid":`g7le-setting-input-${e.key}`,children:(e.options??[]).map(a=>{const l=s.includes(a.value);return i.jsxs("label",{style:pA,children:[i.jsx("input",{type:"checkbox",checked:l,onChange:d=>{const c=d.target.checked?[...s,a.value]:s.filter(p=>p!==a.value);o(e.key,c)}}),fi(a.label,String(a.value),n)]},String(a.value))})})}default:return i.jsxs("select",{"data-testid":`g7le-setting-input-${e.key}`,value:r==null?"":String(r),onChange:s=>{const a=s.target.value;if(a===""){o(e.key,void 0);return}const l=(e.options??[]).find(d=>String(d.value)===a);o(e.key,l?l.value:a)},style:Ca,children:[i.jsx("option",{value:"",children:"—"}),(e.options??[]).map(s=>i.jsx("option",{value:String(s.value),children:fi(s.label,String(s.value),n)},String(s.value)))]})}}const sA={display:"flex",flexDirection:"column",gap:16},aA={display:"flex",flexDirection:"column",gap:6},lA={fontSize:12,fontWeight:700,color:"#0f172a",borderBottom:"1px solid #e2e8f0",paddingBottom:4},dA={display:"flex",alignItems:"center",gap:12,minHeight:30},cA={fontSize:12,color:"#475569",minWidth:96},Ca={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,width:"100%",boxSizing:"border-box"},uA={display:"flex",flexWrap:"wrap",gap:10},pA={display:"inline-flex",alignItems:"center",gap:4,fontSize:12,color:"#0f172a"},fA=["data_binding","isolatedScopeId","parentFormContextProp","skipBindingKeys","isolatedState","component_layout","sortable","itemTemplate"],gA=/\{\{|\$switch|\$get|\|\s*(date|number|truncate|currency|relative)\b/;function gi(e,t=0){return t>6?!1:typeof e=="string"?gA.test(e):Array.isArray(e)?e.some(n=>gi(n,t+1)):e&&typeof e=="object"?Object.values(e).some(n=>gi(n,t+1)):!1}function hA(e){if(Zl(e))return!1;const t=Fl(e);return t.length===0?!1:t.some(n=>n.isComplex)}function Ef(e){const t=[],n=e.props??{};for(const o of fA)o in e&&e[o]!==void 0?t.push({key:o,kind:"developer_prop"}):o in n&&n[o]!==void 0&&t.push({key:`props.${o}`,kind:"developer_prop"});typeof e.text=="string"?hA(e.text)&&t.push({key:"text",kind:"complex_expression"}):gi(e.text)&&t.push({key:"text",kind:"complex_expression"});for(const[o,r]of Object.entries(n))o==="style"||o==="className"||gi(r)&&t.push({key:`props.${o}`,kind:"complex_expression"});return t}function yA(e){return Ef(e).length>0}const bA=new Set(["permissions","blur_until_loaded","comment"]);function mA({node:e,advanced:t,t:n,onPatch:o,permissionCandidates:r}){const s=u.useMemo(()=>Ef(e),[e]),a=(l,d)=>{const c={...e};d===void 0?delete c[l]:c[l]=d,o(c)};return i.jsxs("div",{className:"g7le-advanced-props","data-testid":"g7le-advanced-props",style:vA,children:[t.map(l=>{if(!bA.has(l))return i.jsxs("div",{"data-testid":`g7le-advanced-deferred-${l}`,style:xA,children:[n("layout_editor.property_modal.advanced_deferred"),":",l]},l);if(l==="permissions")return i.jsxs("div",{className:"g7le-advanced-group","data-testid":"g7le-advanced-permissions",style:$a,children:[i.jsx("div",{style:Ea,children:n("layout_editor.property_modal.advanced.permissions")}),i.jsx(ys,{control:{widget:"tag-input"},value:e.permissions,onChange:d=>a("permissions",d),t:n,candidates:r})]},l);if(l==="blur_until_loaded"){const d=e.blur_until_loaded===!0||e.blur_until_loaded!=null&&e.blur_until_loaded!==!1;return i.jsxs("div",{className:"g7le-advanced-group","data-testid":"g7le-advanced-blur",style:$a,children:[i.jsx("div",{style:Ea,children:n("layout_editor.property_modal.advanced.blur_until_loaded")}),i.jsxs("label",{style:{display:"inline-flex",alignItems:"center",gap:6,fontSize:12},children:[i.jsx("input",{type:"checkbox","data-testid":"g7le-advanced-blur-toggle",checked:!!d,onChange:c=>a("blur_until_loaded",c.target.checked?!0:void 0)}),n("layout_editor.property_modal.advanced.blur_hint")]})]},l)}return i.jsxs("div",{className:"g7le-advanced-group","data-testid":"g7le-advanced-comment",style:$a,children:[i.jsx("div",{style:Ea,children:n("layout_editor.property_modal.advanced.comment")}),i.jsx("input",{type:"text","data-testid":"g7le-advanced-comment-input",value:typeof e.comment=="string"?e.comment:"",onChange:d=>a("comment",d.target.value===""?void 0:d.target.value),style:_A})]},l)}),s.length>0&&i.jsxs("div",{className:"g7le-advanced-preserved","data-testid":"g7le-advanced-preserved",style:wA,children:[i.jsx("div",{style:kA,children:n("layout_editor.property_modal.advanced_preserved_title",{count:s.length})}),i.jsx("ul",{style:SA,children:s.map(l=>i.jsxs("li",{"data-testid":`g7le-advanced-preserved-${l.key}`,style:CA,children:[i.jsx("code",{style:{fontSize:11},children:l.key}),i.jsx("span",{style:{fontSize:11,color:"#94a3b8"},children:l.kind==="developer_prop"?n("layout_editor.property_modal.advanced_kind_developer"):n("layout_editor.property_modal.advanced_kind_expression")})]},l.key))})]})]})}const vA={display:"flex",flexDirection:"column",gap:14},$a={display:"flex",flexDirection:"column",gap:6},Ea={fontSize:12,fontWeight:700,color:"#0f172a"},_A={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,width:"100%",boxSizing:"border-box"},xA={fontSize:11,color:"#94a3b8",fontStyle:"italic"},wA={borderTop:"1px dashed #cbd5e1",paddingTop:10,marginTop:4},kA={fontSize:11,color:"#b45309",marginBottom:6},SA={listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:4},CA={display:"flex",justifyContent:"space-between",gap:8,padding:"3px 0"},$A={onClick:"click",onHover:"mouseenter",onChange:"change",onSubmit:"submit",onMount:"mount",onUnmount:"unmount",onFocus:"focus",onBlur:"blur"};function Ia(e){return $A[e]??e.replace(/^on/,"").toLowerCase()}function If(e){const t=e.actions;if(Array.isArray(t))return t.filter(r=>!!r&&typeof r=="object");const n=e.props??{};if(Array.isArray(n.actions))return n.actions.filter(r=>!!r&&typeof r=="object");const o=n.events;if(o&&typeof o=="object"){const r=[];for(const[s,a]of Object.entries(o)){if(!Array.isArray(a))continue;const l=Ia(s);for(const d of a)d&&typeof d=="object"&&r.push("type"in d?d:{type:l,...d})}return r}return[]}function EA(e,t){const n=Ia(t);return If(e).filter(o=>o.type===n||t==="onClick"&&o.type===void 0)}function IA(e,t,n){const o=Ia(t),r=If(e).filter(d=>!(d.type===o||t==="onClick"&&d.type===void 0)),s=n.map(d=>"type"in d?d:{type:o,...d}),a={...e};if(a.props&&typeof a.props=="object"){const d={...a.props};let c=!1;"actions"in d&&(delete d.actions,c=!0),"events"in d&&(delete d.events,c=!0),c&&(a.props=d)}const l=[...r,...s];return l.length===0?delete a.actions:a.actions=l,a}function AA({node:e,spec:t,capability:n,t:o,onPatchNode:r,pageCandidates:s,dataSourceCandidates:a,stateKeyCandidates:l,bindingCandidates:d}){const c=t?.actionRecipes,p=u.useMemo(()=>({pageCandidates:s,dataSourceCandidates:a,stateKeyCandidates:l,bindingCandidates:d}),[s,a,l,d]),f=Array.isArray(n?.events)?n.events:[];return f.length===0?i.jsx("div",{"data-testid":"g7le-action-no-events",style:Af,children:o("layout_editor.action.no_events")}):!c||Object.keys(c).length===0?i.jsx("div",{"data-testid":"g7le-action-no-recipes",style:Af,children:o("layout_editor.action.no_recipes")}):i.jsx("div",{className:"g7le-action-editor","data-testid":"g7le-action-editor",style:{display:"flex",flexDirection:"column",gap:14},children:f.map(y=>i.jsxs("div",{className:"g7le-action-event-slot","data-testid":`g7le-action-event-${y}`,children:[i.jsx("div",{style:TA,children:o(`layout_editor.action.event.${y}`)}),i.jsx(Gt,{actions:EA(e,y),onChange:g=>r(IA(e,y,g)),t:o,recipes:c,candidatePools:p,actionChipCandidates:t?.actionChipCandidates??null,addContext:"component",showSourceBadge:!0,testIdPrefix:`g7le-action-slot-${y}`})]},y))})}const Af={fontSize:12,color:"#94a3b8",padding:"16px 0",textAlign:"center"},TA={fontSize:12,fontWeight:700,color:"#475569",marginBottom:6};function Aa(e,t,n){if(!t)return n;const o=e(t);return!o||o===t||o.startsWith("$t:")?n:o}function DA(e,t){return Aa(t,e.labelKey,e.path||e.sourceId)}function NA({node:e,spec:t,candidates:n,t:o,onPatchNode:r}){const a=(e.props??{})[t.propKey],l=typeof a=="string"?a:void 0,d=u.useMemo(()=>Kt(a),[a]),c=l!==void 0&&l!==""&&d===null,[p,f]=u.useState(!1),[y,g]=u.useState(""),m=Aa(o,t.label,t.propKey),h=o(t.shape==="array"?"layout_editor.binding.shape_array":t.shape==="object"?"layout_editor.binding.shape_object":"layout_editor.binding.shape_scalar"),v=u.useMemo(()=>Fi(n,t.shape).map(_=>({..._,resolvedLabel:DA(_,o)})),[n,t.shape,o]),b=u.useMemo(()=>Ki(v,y),[v,y]),x=w=>{const _={...e.props??{}};w===void 0?delete _[t.propKey]:_[t.propKey]=w,r({...e,props:_})},k=w=>{x(En(w.sourceId,w.path,t.shape)),f(!1),g("")};return i.jsxs("div",{"data-testid":`g7le-binding-row-${t.propKey}`,style:PA,children:[i.jsxs("div",{style:OA,children:[i.jsx("span",{style:{fontWeight:600,fontSize:12},children:m}),i.jsx("span",{style:BA,children:h}),t.required&&i.jsx("span",{"data-testid":`g7le-binding-required-${t.propKey}`,style:WA,children:o("layout_editor.binding.required")})]}),c?i.jsxs("div",{"data-testid":`g7le-binding-complex-${t.propKey}`,style:KA,children:[o("layout_editor.binding.complex"),i.jsx("code",{style:Tf,children:l})]}):d?i.jsxs("div",{style:jA,children:[i.jsx("code",{"data-testid":`g7le-binding-expr-${t.propKey}`,style:Tf,children:l}),i.jsx("button",{type:"button","data-testid":`g7le-binding-clear-${t.propKey}`,onClick:()=>x(void 0),style:FA,children:o("layout_editor.binding.clear")})]}):i.jsx("div",{"data-testid":`g7le-binding-empty-${t.propKey}`,style:HA,children:o("layout_editor.binding.not_connected")}),d&&(t.shape==="array"||t.shape==="object")&&t.itemFields&&t.itemFields.length>0&&i.jsxs("div",{style:VA,children:[o("layout_editor.binding.item_fields"),": ",t.itemFields.join(", ")]}),!c&&i.jsxs("div",{style:{marginTop:4},children:[i.jsxs("button",{type:"button","data-testid":`g7le-binding-search-toggle-${t.propKey}`,onClick:()=>f(w=>!w),style:UA,children:["🔍 ",o("layout_editor.binding.search")]}),p&&i.jsxs("div",{"data-testid":`g7le-binding-picker-${t.propKey}`,style:qA,children:[i.jsx("input",{type:"text",autoFocus:!0,"data-testid":`g7le-binding-search-input-${t.propKey}`,value:y,placeholder:o("layout_editor.binding.search_placeholder"),onChange:w=>g(w.target.value),style:GA}),i.jsx("div",{style:YA,children:b.length===0?i.jsx("div",{style:XA,children:o("layout_editor.binding.no_results")}):b.map(w=>i.jsxs("button",{type:"button","data-testid":`g7le-binding-candidate-${w.expression}`,onClick:()=>k(w),style:JA,children:[i.jsxs("span",{style:{display:"flex",flexDirection:"column",alignItems:"flex-start"},children:[i.jsx("span",{style:{fontSize:12},children:w.resolvedLabel}),i.jsxs("span",{style:ZA,children:[Aa(o,w.groupLabelKey,w.sourceId)," · ",w.path||w.sourceId]})]}),i.jsx("span",{style:QA,children:w.preview})]},w.expression))})]})]})]})}function zA({node:e,dataProps:t,candidates:n,t:o,onPatchNode:r}){return!Array.isArray(t)||t.length===0?null:i.jsxs("div",{"data-testid":"g7le-data-binding-section",style:MA,children:[i.jsxs("div",{style:LA,children:["🔗 ",o("layout_editor.binding.section_title")]}),t.map(s=>i.jsx(NA,{node:e,spec:s,candidates:n,t:o,onPatchNode:r},s.propKey)),i.jsx("div",{style:RA})]})}const MA={display:"flex",flexDirection:"column",marginBottom:8},LA={fontSize:12,fontWeight:700,color:"#0f172a",marginBottom:6},PA={display:"flex",flexDirection:"column",gap:4,padding:"8px 0"},OA={display:"flex",alignItems:"center",gap:6},BA={fontSize:10,padding:"1px 6px",borderRadius:4,background:"#e0e7ff",color:"#3730a3"},WA={fontSize:10,padding:"1px 6px",borderRadius:4,background:"#fef3c7",color:"#92400e"},jA={display:"flex",alignItems:"center",gap:6},HA={fontSize:11,color:"#94a3b8"},Tf={fontSize:11,fontFamily:"monospace",background:"#f1f5f9",padding:"2px 6px",borderRadius:4,color:"#0f172a",wordBreak:"break-all"},FA={fontSize:11,border:"1px solid #e2e8f0",borderRadius:4,background:"#fff",color:"#dc2626",padding:"2px 8px",cursor:"pointer"},KA={display:"flex",flexDirection:"column",gap:2,fontSize:11,color:"#64748b"},VA={fontSize:10,color:"#94a3b8"},UA={fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#334155",padding:"4px 10px",cursor:"pointer",textAlign:"left",width:"100%"},qA={marginTop:4,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",padding:6},GA={width:"100%",padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,boxSizing:"border-box"},YA={marginTop:4,maxHeight:200,overflowY:"auto",display:"flex",flexDirection:"column",gap:2},XA={fontSize:11,color:"#94a3b8",padding:"8px 0",textAlign:"center"},JA={display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,border:"none",background:"transparent",cursor:"pointer",padding:"6px 8px",borderRadius:4,textAlign:"left"},ZA={fontSize:10,color:"#94a3b8"},QA={fontSize:10,color:"#64748b",fontFamily:"monospace",whiteSpace:"nowrap"},RA={borderTop:"1px solid #e2e8f0",marginTop:4};function e6({node:e,candidates:t,t:n,onPatchNode:o,templateIdentifier:r}){const s=typeof e.text=="string"?e.text:"",{state:a}=Je(),l=r??a.templateIdentifier,d=a.selectedRoute?.layoutName??null,c=a.locale,[p,f]=u.useState(!1),y=/^\s*\$t:custom\.[A-Za-z0-9._-]+\s*$/.test(s),m=Zl(s)&&(mt(s)?.key.startsWith("custom.")??!1)||y,h=u.useMemo(()=>m?mt(s):null,[m,s]),v=u.useMemo(()=>m?[]:Fl(s),[m,s]),b=N=>{o({...e,text:N})},x=()=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(kt,{detail:{templateIdentifier:l,locale:c}}))}catch{}},k=(N,$)=>{const A=En($.sourceId,$.path,"scalar");b(vb(s,N,A))},w=N=>{const $=mt(s);b(bo(s,N));const A=$?.key;l&&A&&Hd(l,A,N).then(x)},_=N=>{const $=n(N);return $&&$!==N&&!$.startsWith("$t:")?$:""},S=N=>N.replace(/\$t:[a-zA-Z0-9._-]+/g,$=>_($.slice(3))).replace(/\s+/g," ").trim(),E=N=>{p||(f(!0),ls(l,d,c,s,s.length,N.sourceId,N.path,"scalar",S,$=>n($)).then($=>{$.kind==="ok"&&(b($.text),x())}).finally(()=>f(!1)))},C=N=>{p||!h&&!y||(f(!0),wr(l,c,s,Number.MAX_SAFE_INTEGER,N.sourceId,N.path,"scalar").then($=>{$.kind==="ok"&&(b($.text),x())}).finally(()=>f(!1)))};if(m){const N=h?.params??[];return i.jsxs("div",{"data-testid":"g7le-inline-binding-section",style:Df,children:[i.jsxs("div",{style:Nf,children:["🔗 ",n("layout_editor.inline_binding.section_title")]}),N.length===0?i.jsx("div",{"data-testid":"g7le-inline-binding-none",style:Lf,children:n("layout_editor.inline_binding.none")}):N.map($=>i.jsx("div",{"data-testid":`g7le-inline-binding-param-${$.name}`,style:zf,children:$.parsed===null?i.jsxs("div",{"data-testid":`g7le-inline-binding-param-complex-${$.name}`,style:n6,children:[n("layout_editor.inline_binding.complex"),i.jsx("code",{style:Ta,children:$.expression})]}):i.jsxs(i.Fragment,{children:[i.jsxs("div",{style:Mf,children:[i.jsx("code",{"data-testid":`g7le-inline-binding-param-expr-${$.name}`,style:Ta,children:$.expression}),i.jsx("button",{type:"button","data-testid":`g7le-inline-binding-param-clear-${$.name}`,onClick:()=>w($.name),style:t6,children:n("layout_editor.inline_binding.clear")})]}),i.jsx($t,{candidates:t,t:n,onSelect:A=>k($.name,A),testIdSuffix:`param-${$.name}`})]})},$.name)),i.jsxs("div",{"data-testid":"g7le-inline-binding-param-append",style:Pf,children:[i.jsx("div",{style:Da,children:n("layout_editor.inline_binding.append_hint")}),i.jsx($t,{candidates:t,t:n,onSelect:C,testIdSuffix:"param-append"})]}),i.jsx("div",{"data-testid":"g7le-inline-binding-param-hint",style:Da,children:n("layout_editor.inline_binding.param_hint")}),i.jsx("div",{style:Of})]})}return i.jsxs("div",{"data-testid":"g7le-inline-binding-section",style:Df,children:[i.jsxs("div",{style:Nf,children:["🔗 ",n("layout_editor.inline_binding.section_title")]}),v.length===0?i.jsx("div",{"data-testid":"g7le-inline-binding-none",style:Lf,children:n("layout_editor.inline_binding.none")}):v.map(N=>i.jsx("div",{"data-testid":`g7le-inline-binding-row-${N.bindingIndex}`,style:zf,children:i.jsx("div",{style:Mf,children:i.jsx("code",{"data-testid":`g7le-inline-binding-expr-${N.bindingIndex}`,style:Ta,children:N.expression})})},N.bindingIndex)),i.jsxs("div",{"data-testid":"g7le-inline-binding-append",style:Pf,children:[i.jsx("div",{style:Da,children:n("layout_editor.inline_binding.append_hint")}),i.jsx($t,{candidates:t,t:n,onSelect:E,testIdSuffix:"append"})]}),i.jsx("div",{style:Of})]})}const Df={display:"flex",flexDirection:"column",marginBottom:8},Nf={fontSize:12,fontWeight:700,color:"#0f172a",marginBottom:6},zf={display:"flex",flexDirection:"column",gap:4,padding:"8px 0"},Mf={display:"flex",alignItems:"center",gap:6},Lf={fontSize:11,color:"#94a3b8"},Ta={fontSize:11,fontFamily:"monospace",background:"#f1f5f9",padding:"2px 6px",borderRadius:4,color:"#0f172a",wordBreak:"break-all"},t6={fontSize:11,border:"1px solid #e2e8f0",borderRadius:4,background:"#fff",color:"#dc2626",padding:"2px 8px",cursor:"pointer"},n6={display:"flex",flexDirection:"column",gap:2,fontSize:11,color:"#64748b"},Pf={display:"flex",flexDirection:"column",gap:2,padding:"8px 0 0"},Da={fontSize:11,color:"#475569",fontWeight:600},Of={borderTop:"1px solid #e2e8f0",marginTop:4};function Bf(e,t,n){if(!t)return n;const o=e(t);return!o||o===t||o.startsWith("$t:")?n:o}function o6(e,t){return Bf(t,e.labelKey,e.path||e.sourceId)}function r6(e){const t=e.iteration;return t&&typeof t=="object"?t:null}function i6({node:e,candidates:t,t:n,onPatchNode:o}){const r=r6(e),s=r?.source,a=typeof s=="string"?s:void 0,l=u.useMemo(()=>Kt(s),[s]),d=a!==void 0&&a!==""&&l===null,[c,p]=u.useState(!1),[f,y]=u.useState(""),g=u.useMemo(()=>Fi(t,"array").map(w=>({...w,resolvedLabel:o6(w,n)})),[t,n]),m=u.useMemo(()=>Ki(g,f),[g,f]);if(!r)return null;const h=typeof r.item_var=="string"?r.item_var:void 0,v=typeof r.index_var=="string"?r.index_var:void 0,b=k=>{const w={...r};k===void 0?delete w.source:w.source=k,o({...e,iteration:w})},x=k=>{b(En(k.sourceId,k.path,"array")),p(!1),y("")};return i.jsxs("div",{"data-testid":"g7le-iteration-binding-section",style:s6,children:[i.jsxs("div",{style:a6,children:["🔁 ",n("layout_editor.binding.iteration_title")]}),i.jsx("div",{style:l6,children:n("layout_editor.binding.iteration_hint")}),i.jsxs("div",{style:d6,children:[i.jsxs("div",{style:c6,children:[i.jsx("span",{style:{fontWeight:600,fontSize:12},children:n("layout_editor.binding.iteration_label")}),i.jsx("span",{style:u6,children:n("layout_editor.binding.shape_array")})]}),d?i.jsxs("div",{"data-testid":"g7le-iteration-binding-complex",style:h6,children:[n("layout_editor.binding.complex"),i.jsx("code",{style:Wf,children:a})]}):l?i.jsxs("div",{style:p6,children:[i.jsx("code",{"data-testid":"g7le-iteration-binding-expr",style:Wf,children:a}),i.jsx("button",{type:"button","data-testid":"g7le-iteration-binding-clear",onClick:()=>b(void 0),style:g6,children:n("layout_editor.binding.clear")})]}):i.jsx("div",{"data-testid":"g7le-iteration-binding-empty",style:f6,children:n("layout_editor.binding.not_connected")}),(h||v)&&i.jsxs("div",{"data-testid":"g7le-iteration-vars",style:y6,children:[h&&i.jsxs("span",{children:[n("layout_editor.binding.iteration_item_var"),": ",i.jsx("code",{style:jf,children:h})]}),v&&i.jsxs("span",{children:[n("layout_editor.binding.iteration_index_var"),": ",i.jsx("code",{style:jf,children:v})]})]}),!d&&i.jsxs("div",{style:{marginTop:4},children:[i.jsxs("button",{type:"button","data-testid":"g7le-iteration-binding-search-toggle",onClick:()=>p(k=>!k),style:b6,children:["🔍 ",n("layout_editor.binding.search")]}),c&&i.jsxs("div",{"data-testid":"g7le-iteration-binding-picker",style:m6,children:[i.jsx("input",{type:"text",autoFocus:!0,"data-testid":"g7le-iteration-binding-search-input",value:f,placeholder:n("layout_editor.binding.search_placeholder"),onChange:k=>y(k.target.value),style:v6}),i.jsx("div",{style:_6,children:m.length===0?i.jsx("div",{style:x6,children:n("layout_editor.binding.no_results")}):m.map(k=>i.jsxs("button",{type:"button","data-testid":`g7le-iteration-binding-candidate-${k.expression}`,onClick:()=>x(k),style:w6,children:[i.jsxs("span",{style:{display:"flex",flexDirection:"column",alignItems:"flex-start"},children:[i.jsx("span",{style:{fontSize:12},children:k.resolvedLabel}),i.jsxs("span",{style:k6,children:[Bf(n,k.groupLabelKey,k.sourceId)," · ",k.path||k.sourceId]})]}),i.jsx("span",{style:S6,children:k.preview})]},k.expression))})]})]})]}),i.jsx("div",{style:C6})]})}const s6={display:"flex",flexDirection:"column",marginBottom:8},a6={fontSize:12,fontWeight:700,color:"#0f172a",marginBottom:4},l6={fontSize:10,color:"#94a3b8",marginBottom:6,lineHeight:1.4},d6={display:"flex",flexDirection:"column",gap:4,padding:"8px 0"},c6={display:"flex",alignItems:"center",gap:6},u6={fontSize:10,padding:"1px 6px",borderRadius:4,background:"#e0e7ff",color:"#3730a3"},p6={display:"flex",alignItems:"center",gap:6},f6={fontSize:11,color:"#94a3b8"},Wf={fontSize:11,fontFamily:"monospace",background:"#f1f5f9",padding:"2px 6px",borderRadius:4,color:"#0f172a",wordBreak:"break-all"},g6={fontSize:11,border:"1px solid #e2e8f0",borderRadius:4,background:"#fff",color:"#dc2626",padding:"2px 8px",cursor:"pointer"},h6={display:"flex",flexDirection:"column",gap:2,fontSize:11,color:"#64748b"},y6={display:"flex",gap:12,fontSize:10,color:"#94a3b8",marginTop:2},jf={fontSize:10,fontFamily:"monospace",background:"#f1f5f9",padding:"1px 4px",borderRadius:3,color:"#475569"},b6={fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#334155",padding:"4px 10px",cursor:"pointer",textAlign:"left",width:"100%"},m6={marginTop:4,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",padding:6},v6={width:"100%",padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,boxSizing:"border-box"},_6={marginTop:4,maxHeight:200,overflowY:"auto",display:"flex",flexDirection:"column",gap:2},x6={fontSize:11,color:"#94a3b8",padding:"8px 0",textAlign:"center"},w6={display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,border:"none",background:"transparent",cursor:"pointer",padding:"6px 8px",borderRadius:4,textAlign:"left"},k6={fontSize:10,color:"#94a3b8"},S6={fontSize:10,color:"#64748b",fontFamily:"monospace",whiteSpace:"nowrap"},C6={borderTop:"1px solid #e2e8f0",marginTop:4},$6=new Set(["Span","P","H1","H2","H3","H4","H5","H6","A","Button","Li","Label"]);function E6(e,t){if(!e||e.iteration&&typeof e.iteration=="object")return!1;const n=t?.textBinding;if(n===!1)return!1;if(n===!0)return!0;const o=typeof e.name=="string"?e.name:"";return $6.has(o)?!0:typeof e.text=="string"}const yn={direction:"flexDirection",justify:"flexJustify",align:"flexAlign",wrap:"flexWrap",gap:"flexGap",enable:"flexEnable"},hi={grow:"flexItemGrow",selfAlign:"flexItemAlign",order:"flexItemOrder"};function Hf(e){const t=e?.flexEditor;return t==="container"||t==="item"||t==="auto"?t:null}function I6(e){if(!e||typeof window>"u"||typeof window.getComputedStyle!="function")return!1;const t=(window.getComputedStyle(e).display??"").toLowerCase();return t==="flex"||t==="inline-flex"}function A6(e,t,n=Wt){if(!e||!t)return!1;const o=To(e,t,n),r=t.options,s=Array.isArray(r)?t.onValue??r[0]?.value:void 0,a=l=>s!==void 0?l===s:l!==void 0&&l!==!1;return n.breakpoint!=="base"?a(o.scopedRawValue):o.matched&&a(o.value)}function T6(e,t,n=!1,o=!1,r=Wt){if(e==="container")return{showContainer:!0,showEnableButton:!1,showDisableButton:!1};if(e==="item")return{showContainer:!1,showEnableButton:!1,showDisableButton:!1};if(e==="auto"){const s=r.breakpoint==="base";return!o&&!s?{showContainer:!1,showEnableButton:!1,showDisableButton:!1}:(o?n:I6(t))?{showContainer:!0,showEnableButton:!1,showDisableButton:o}:{showContainer:!1,showEnableButton:!0,showDisableButton:!1}}return{showContainer:!1,showEnableButton:!1,showDisableButton:!1}}const D6={[yn.direction]:"layout_editor.flex.direction",[yn.justify]:"layout_editor.flex.justify",[yn.align]:"layout_editor.flex.align",[yn.wrap]:"layout_editor.flex.wrap",[yn.gap]:"layout_editor.flex.gap"},N6={[hi.grow]:"layout_editor.flex.item_grow",[hi.selfAlign]:"layout_editor.flex.item_align",[hi.order]:"layout_editor.flex.item_order"};function z6({node:e,spec:t,capability:n,t:o,onPatchNode:r,liveElement:s,scope:a=Wt}){const l=Hf(n),d=Ct(t,yn.enable),c=A6(e,d,a),{showContainer:p,showEnableButton:f,showDisableButton:y}=T6(l,s,c,!!d,a),g=Object.values(yn).filter(_=>_!==yn.enable&&Ct(t,_)),m=Object.values(hi).filter(_=>Ct(t,_)),h=d?.options,v=d?.onValue??h?.[0]?.value??!0,b=Array.isArray(h)&&h.length>=2?h[1].value:void 0,x=()=>{if(!d)return;const _=fn(e,d,v,a);r(_)},k=()=>{if(!d)return;const _=a.breakpoint!=="base"&&b!==void 0?b:void 0,S=fn(e,d,_,a);r(S)},w=(_,S,E)=>i.jsx("div",{"data-testid":E,style:{display:"flex",flexDirection:"column"},children:_.map(C=>{const N=Ct(t,C);if(!N)return null;const $=N.label?N:{...N,label:`$t:${S[C]}`};return i.jsx(pi,{controlKey:C,control:$,node:e,t:o,onPatch:r,scope:a},C)})});return i.jsxs("div",{className:"g7le-flex-editor","data-testid":"g7le-flex-editor",style:{display:"flex",flexDirection:"column",gap:12},children:[f&&i.jsx("button",{type:"button","data-testid":"g7le-flex-enable",onClick:x,style:M6,children:o("layout_editor.flex.make_flex")}),p&&g.length>0&&i.jsxs("div",{className:"g7le-flex-container-section","data-testid":"g7le-flex-container-section",children:[i.jsx("div",{style:Ff,children:o("layout_editor.flex.container_title")}),w(g,D6,"g7le-flex-container-controls"),y&&i.jsx("button",{type:"button","data-testid":"g7le-flex-disable",onClick:k,style:L6,children:o("layout_editor.flex.unmake_flex")})]}),l==="item"&&m.length>0&&i.jsxs("div",{className:"g7le-flex-item-section","data-testid":"g7le-flex-item-section",children:[i.jsx("div",{style:Ff,children:o("layout_editor.flex.item_title")}),w(m,N6,"g7le-flex-item-controls")]}),!p&&!f&&l!=="item"&&i.jsx("div",{"data-testid":"g7le-flex-empty",style:P6,children:o("layout_editor.flex.not_flex")})]})}const Ff={fontSize:12,fontWeight:700,color:"#0f172a",marginBottom:6},M6={padding:"8px 12px",fontSize:12,border:"1px dashed #2563eb",borderRadius:6,background:"#eff6ff",color:"#2563eb",cursor:"pointer"},L6={marginTop:8,padding:"6px 10px",fontSize:12,border:"1px solid #e2e8f0",borderRadius:6,background:"#f8fafc",color:"#64748b",cursor:"pointer"},P6={fontSize:12,color:"#94a3b8",padding:"16px 0",textAlign:"center"},Kf=["desktop","tablet","mobile","portable"],Na=1280,O6=820,B6=390,W6=1920,j6=320;function H6(e){const t=[],n=new Set,o=r=>{if(!r||typeof r!="object")return;const s=r.responsive;if(s&&typeof s=="object")for(const a of Object.keys(s)){n.has(a)||(n.add(a),t.push(a));const l=s[a]?.children;if(Array.isArray(l))for(const d of l)o(d)}if(Array.isArray(r.children))for(const a of r.children)o(a)};if(Array.isArray(e))for(const r of e)o(r);return t}function F6(e){const t=[...Kf],n=new Set(Kf);for(const o of H6(e))!n.has(o)&&!t.includes(o)&&t.push(o);return t}function K6(e,t){const n=e?.responsive;if(!n||typeof n!="object")return[];const o=[];for(const r of Object.keys(n)){const s=n[r];!s||!Array.isArray(s.children)||r!==t&&o.push(r)}return o}function V6(e){switch(e){case"desktop":return Na;case"tablet":return O6;case"mobile":return B6}const t=e in Ao?Ao[e]:Mn.parseRange(e);return!t||!Number.isFinite(t.max)?Na:Math.round(Math.max(j6,Math.min(W6,t.max)))}function Vf(){const t=Ft()?.document?.raw?.components;return u.useMemo(()=>F6(t??null),[t])}const U6={desktop:"layout_editor.property_modal.scope.device_desktop",tablet:"layout_editor.property_modal.scope.device_tablet",mobile:"layout_editor.property_modal.scope.device_mobile",portable:"layout_editor.property_modal.scope.device_portable"},q6=[{key:"base",labelKey:"layout_editor.property_modal.scope.scheme_light"},{key:"dark",labelKey:"layout_editor.property_modal.scope.scheme_dark"}];function Uf({scope:e,onChange:t,node:n,t:o,showColorScheme:r=!0,onClearScope:s}){const[a,l]=u.useState(!1),[d,c]=u.useState(""),[p,f]=u.useState(""),[y,g]=u.useState(null),m=Vf(),h=u.useMemo(()=>{const k=["base",...m],w=new Set(k);for(const _ of Object.keys(n.responsive??{}))_!=="base"&&!w.has(_)&&(w.add(_),k.push(_));return e.breakpoint!=="base"&&!w.has(e.breakpoint)&&k.push(e.breakpoint),k},[m,n.responsive,e.breakpoint]),v=k=>t({...e,colorScheme:k}),b=k=>t({...e,breakpoint:k}),x=()=>{const k=d.trim(),w=p.trim();if(k===""&&w===""){g(o("layout_editor.property_modal.scope.custom_invalid"));return}const _=`${k}-${w}`;if(!uC(_)){g(o("layout_editor.property_modal.scope.custom_invalid"));return}g(null),l(!1),c(""),f(""),b(_)};return i.jsxs("div",{className:"g7le-style-scope-tabs","data-testid":"g7le-style-scope-tabs",style:G6,children:[r&&i.jsx("div",{className:"g7le-style-scope-scheme","data-testid":"g7le-style-scope-scheme",role:"tablist","aria-label":o("layout_editor.property_modal.scope.scheme_light"),style:qf,children:q6.map(k=>{const w=e.colorScheme===k.key;return i.jsxs("button",{type:"button",role:"tab","aria-selected":w,"data-testid":`g7le-style-scheme-${k.key}`,"data-active":w?"true":"false",onClick:()=>v(k.key),style:Gf(w),children:[o(k.labelKey),k.key==="dark"&&Gs(n,{colorScheme:"dark",breakpoint:e.breakpoint})&&i.jsx("span",{"data-testid":"g7le-style-scheme-dark-dot",style:Yf})]},k.key)})}),i.jsxs("div",{className:"g7le-style-scope-device","data-testid":"g7le-style-scope-device",role:"tablist","aria-label":o("layout_editor.property_modal.scope.device_base"),style:qf,children:[h.map(k=>{const w=e.breakpoint===k,_=k==="base"||xu(k),S=k==="base"?"layout_editor.property_modal.scope.device_base":U6[k],E=S?o(S):k,C=_?`g7le-style-bp-${k}`:`g7le-style-bp-custom-${k}`;return i.jsxs("button",{type:"button",role:"tab","aria-selected":w,"data-testid":C,"data-active":w?"true":"false",onClick:()=>b(k),style:Gf(w),children:[E,Gs(n,{colorScheme:"base",breakpoint:k})&&i.jsx("span",{"data-testid":`${C}-dot`,style:Yf})]},String(k))}),i.jsxs("button",{type:"button","data-testid":"g7le-style-bp-add-custom",onClick:()=>l(k=>!k),style:J6,children:["+ ",o("layout_editor.property_modal.scope.add_custom")]})]}),a&&i.jsxs("div",{className:"g7le-style-scope-custom-input","data-testid":"g7le-style-scope-custom-input",style:Y6,children:[i.jsx("input",{type:"number","data-testid":"g7le-style-custom-min",placeholder:o("layout_editor.property_modal.scope.custom_min"),value:d,onChange:k=>c(k.target.value),style:Xf}),i.jsx("span",{style:{color:"#94a3b8"},children:"—"}),i.jsx("input",{type:"number","data-testid":"g7le-style-custom-max",placeholder:o("layout_editor.property_modal.scope.custom_max"),value:p,onChange:k=>f(k.target.value),style:Xf}),i.jsx("button",{type:"button","data-testid":"g7le-style-custom-confirm",onClick:x,style:Z6,children:o("layout_editor.property_modal.scope.add_custom")})]}),y&&i.jsx("div",{"data-testid":"g7le-style-custom-error",style:Q6,children:y}),e.breakpoint!=="base"&&!xu(e.breakpoint)&&i.jsx("div",{"data-testid":"g7le-style-custom-priority-note",style:R6,children:o("layout_editor.property_modal.scope.custom_priority_note")}),s&&Gs(n,e)&&i.jsxs("button",{type:"button","data-testid":"g7le-style-scope-reset",onClick:s,style:X6,children:["↺ ",o("layout_editor.property_modal.scope.reset_to_base")]})]})}const G6={display:"flex",flexDirection:"column",gap:0,padding:"0 0 8px",borderBottom:"1px solid #e2e8f0",marginBottom:8},Y6={display:"flex",gap:6,alignItems:"center",marginTop:4},qf={display:"flex",gap:2,flexWrap:"wrap",borderBottom:"1px solid #e2e8f0",margin:"0 -16px",padding:"0 12px"};function Gf(e){return{display:"inline-flex",alignItems:"center",gap:4,padding:"6px 12px",fontSize:12,border:"none",borderBottom:`2px solid ${e?"#2563eb":"transparent"}`,background:"transparent",color:e?"#2563eb":"#64748b",cursor:"pointer",fontWeight:e?700:500,marginBottom:-1}}const Yf={display:"inline-block",width:5,height:5,borderRadius:3,background:"#f59e0b"},X6={alignSelf:"flex-start",marginTop:2,padding:"3px 8px",fontSize:10,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer"},J6={padding:"6px 12px",fontSize:11,border:"none",borderBottom:"2px dashed #cbd5e1",background:"transparent",color:"#475569",cursor:"pointer",marginBottom:-1},Xf={width:70,padding:"4px 6px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6},Z6={padding:"4px 10px",fontSize:11,border:"none",borderRadius:6,background:"#2563eb",color:"#fff",cursor:"pointer"},Q6={fontSize:11,color:"#dc2626"},R6={fontSize:10,color:"#94a3b8"},Jf=new Map;function Pn(e,t){Jf.set(e,t)}function eT(e){return e?Jf.get(e)??null:null}const za={id:{label:"$t:layout_editor.core_props.id.label",widget:"core-id",placeholder:"$t:layout_editor.core_props.id.placeholder",apply:{type:"propValue",propKey:"id"}},dataKey:{label:"$t:layout_editor.core_props.dataKey.label",widget:"core-datakey",placeholder:"$t:layout_editor.core_props.dataKey.placeholder",apply:{type:"nodeKey",nodeKey:"dataKey"}},isolatedState:{label:"$t:layout_editor.core_props.isolatedState.label",widget:"toggle",apply:{type:"nodeKey",nodeKey:"isolatedState"}},isolatedScopeId:{label:"$t:layout_editor.core_props.isolatedScopeId.label",widget:"core-scopeid",placeholder:"$t:layout_editor.core_props.isolatedScopeId.placeholder",apply:{type:"nodeKey",nodeKey:"isolatedScopeId"}}},tT=["id"];function nT(e){return e===!1?[]:Array.isArray(e)?e.filter(t=>t in za):[...tT]}function Zf(e){const t=e.props?.id??e.id;return typeof t=="string"&&t.length>0?`${t}-scope`:"scope"}function oT({node:e,onPatchNode:t,t:n,scopeIdCandidates:o=[],usedScopeIds:r=[]}){const s=e,a="isolatedState"in s&&s.isolatedState!=null,l=typeof s.isolatedScopeId=="string"?s.isolatedScopeId:"",[d,c]=u.useState(""),p=()=>{const h={...e};a?(delete h.isolatedState,delete h.isolatedScopeId):(h.isolatedState={},h.isolatedScopeId=Zf(e)),t(h)},f=h=>{const v={...e};v.isolatedScopeId=h.trim()===""?Zf(e):h,t(v)},y=h=>{const v={...e};v.isolatedState=h,t(v)},g=u.useMemo(()=>{const h=d.trim().toLowerCase();return o.filter(v=>!h||v.toLowerCase().includes(h))},[o,d]),m=l!==""&&r.includes(l);return i.jsxs("div",{className:"g7le-isolated-scope","data-testid":"g7le-isolated-scope-control",style:rT,children:[i.jsx("div",{style:iT,children:n("layout_editor.core_props.isolatedState.label")}),i.jsxs("div",{style:sT,children:[i.jsx("button",{type:"button","data-testid":"g7le-isolated-toggle",role:"switch","aria-checked":a,onClick:p,style:aT(a),children:n(a?"layout_editor.overlay.on":"layout_editor.overlay.off")}),a?null:i.jsx("span",{"data-testid":"g7le-isolated-off-hint",style:lT,children:n("layout_editor.core_props.isolatedState.off_hint")})]}),a?i.jsxs(i.Fragment,{children:[i.jsxs("div",{style:Qf,children:[i.jsx("label",{style:Rf,children:n("layout_editor.core_props.isolatedScopeId.label")}),i.jsx("input",{type:"text","data-testid":"g7le-isolated-scopeid-input",value:l,placeholder:n("layout_editor.core_props.isolatedScopeId.placeholder"),onChange:h=>f(h.target.value),style:dT}),g.length>0?i.jsxs("div",{"data-testid":"g7le-isolated-scopeid-picker",style:cT,children:[i.jsx("input",{type:"text","data-testid":"g7le-isolated-scopeid-search",value:d,placeholder:n("layout_editor.core_props.isolatedScopeId.search"),onChange:h=>c(h.target.value),style:uT}),i.jsx("div",{style:pT,children:g.map(h=>i.jsx("button",{type:"button","data-testid":`g7le-isolated-scopeid-candidate-${h}`,onClick:()=>{f(h),c("")},style:fT,children:h},h))})]}):null,m?i.jsxs("p",{"data-testid":"g7le-isolated-scopeid-dup",style:gT,children:["ⓘ ",n("layout_editor.core_props.isolatedScopeId.duplicate")]}):null]}),i.jsxs("div",{style:Qf,children:[i.jsx("label",{style:Rf,children:n("layout_editor.core_props.isolatedState.initial_label")}),i.jsx("div",{"data-testid":"g7le-isolated-initial-value",children:i.jsx(Nn,{value:s.isolatedState??{},onChange:y,t:n,path:"isolatedState",scope:"isolated-node"})})]})]}):null]})}const rT={display:"flex",flexDirection:"column",gap:8,padding:10,border:"1px solid #e2e8f0",borderRadius:8,minWidth:0},iT={fontSize:12,fontWeight:700,color:"#0f172a"},sT={display:"flex",gap:8,alignItems:"center"},aT=e=>({padding:"4px 12px",fontSize:11,border:`1px solid ${e?"#3b82f6":"#cbd5e1"}`,borderRadius:14,background:e?"#eff6ff":"#fff",color:e?"#1d4ed8":"#64748b",cursor:"pointer"}),lT={fontSize:11,color:"#94a3b8"},Qf={display:"flex",flexDirection:"column",gap:4,minWidth:0},Rf={fontSize:11,color:"#64748b"},dT={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,boxSizing:"border-box",width:"100%"},cT={border:"1px solid #e2e8f0",borderRadius:6,padding:4,background:"#fff"},uT={width:"100%",padding:"4px 6px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,marginBottom:4,boxSizing:"border-box"},pT={display:"flex",flexDirection:"column",maxHeight:120,overflowY:"auto"},fT={textAlign:"left",padding:"4px 6px",fontSize:12,border:"none",background:"transparent",cursor:"pointer",borderRadius:4,color:"#0f172a"},gT={margin:0,fontSize:11,color:"#64748b"},hT={borderTop:"2px solid #c7d2fe",background:"#eef2ff",padding:"10px 12px",display:"flex",flexDirection:"column",gap:8},eg={fontSize:13,fontWeight:700,color:"#3730a3",display:"flex",alignItems:"center",gap:6},yT={fontSize:11,fontWeight:600,color:"#4338ca",background:"#e0e7ff",border:"1px solid #c7d2fe",borderRadius:4,padding:"1px 6px"},Ma={fontSize:11,color:"#6366f1"},bT={alignSelf:"flex-start",fontSize:12,fontWeight:600,color:"#fff",background:"#4f46e5",border:"none",borderRadius:4,padding:"4px 10px",cursor:"pointer"},mT={opacity:.5,cursor:"not-allowed"},vT={fontSize:11,color:"#dc2626"};function _T({entry:e,t,onSave:n}){const[o,r]=u.useState(()=>e.props),[s,a]=u.useState(!0),[l,d]=u.useState(null),[c,p]=u.useState(!1),[f,y]=u.useState(!1),g=e.extensionName??e.extensionIdentifier??`#${e.extensionId}`,m=async()=>{if(!s){d(t("layout_editor.property_modal.injected_props.invalid_json"));return}d(null),p(!0),y(!1);try{await n(o),y(!0)}catch(h){d(h instanceof Error?h.message:String(h))}finally{p(!1)}};return i.jsxs("div",{"data-testid":`g7le-injected-props-entry-${e.extensionId}`,style:{display:"flex",flexDirection:"column",gap:6},children:[i.jsx("div",{style:eg,children:i.jsx("span",{style:yT,"data-testid":"g7le-injected-props-origin-badge",children:t("layout_editor.property_modal.injected_props.origin",{source:g})})}),i.jsx(Bs,{value:o,shape:"object",emptyValue:{},testidPrefix:"g7le-injected-props-json",minHeight:80,invalidErrorKey:"layout_editor.property_modal.injected_props.invalid_json",shapeErrorKey:"layout_editor.property_modal.injected_props.invalid_json",t,onChange:h=>{r(h??{}),y(!1)},onValidityChange:h=>{a(h),h&&d(null),y(!1)}}),l&&i.jsx("div",{style:vT,"data-testid":"g7le-injected-props-error",children:l}),f&&i.jsx("div",{style:{...Ma,color:"#16a34a"},"data-testid":"g7le-injected-props-saved",children:t("layout_editor.property_modal.injected_props.saved")}),i.jsx("div",{style:Ma,children:t("layout_editor.property_modal.injected_props.save_target")}),i.jsx("button",{type:"button","data-testid":"g7le-injected-props-save",style:{...bT,...c||!s?mT:null},disabled:c||!s,onClick:m,children:c?t("layout_editor.property_modal.injected_props.saving"):t("layout_editor.property_modal.injected_props.save_button",{source:g})})]})}function xT({injectedProps:e,t,onSaveInjectedProps:n}){return!Array.isArray(e)||e.length===0?null:i.jsxs("div",{style:hT,"data-testid":"g7le-injected-props-section",children:[i.jsxs("div",{style:eg,children:["🧩 ",t("layout_editor.property_modal.injected_props.title")]}),i.jsx("div",{style:Ma,children:t("layout_editor.property_modal.injected_props.help")}),e.map(o=>i.jsx(_T,{entry:o,t,onSave:r=>n(o.extensionId,r)},o.extensionId))]})}function wT(e,t){const n=e?.components??{};for(const o of Object.values(n)){const r=o?.find(s=>s.name===t);if(r)return r}return null}function kT({node:e,spec:t,manifest:n,t:o,onPatchNode:r,onClose:s,onDelete:a,permissionCandidates:l,pageCandidates:d,dataSourceCandidates:c,stateKeyCandidates:p,bindingCandidates:f,liveElement:y,scope:g=Wt,onScopeChange:m,templateIdentifier:h,initialTab:v,onSaveInjectedProps:b,branchLabel:x,isolatedScopeIdCandidates:k,usedScopeIds:w}){const _=e.__injectedProps,S=Array.isArray(_)&&_.length>0&&!!b,E=ve=>{m?.(ve)},C=()=>{r(mC(e,g))},N=typeof e.name=="string"?e.name:"",$=Oi(t,N),z=wT(n,N)?.settings,D=!!(z?.groups&&z.groups.length>0),O=Array.isArray($?.propControls)?$.propControls:[],M=nT($?.coreProps),B=new Set(M.map(ve=>za[ve].apply?.propKey)),T=O.filter(ve=>{const he=Ct(t,ve)?.apply?.propKey;return!(he!==void 0&&B.has(he))}),H=typeof $?.nodeEditor?.kind=="string"?$.nodeEditor.kind:void 0,L=$?.nodeEditor?.params,I=H?eT(H):null,P=!!I,F=Array.isArray($?.dataProps)?$.dataProps:[],G=F.length>0,V=!!(e.iteration&&typeof e.iteration=="object"),Y=E6(e,$),Z=M.length>0||T.length>0||P||G||Y||V,se=Array.isArray($?.styleControls)?$.styleControls:[],re=Array.isArray($?.advanced)?$.advanced:[],ee=(Array.isArray($?.events)?$.events:[]).length>0,fe=Hf($),K=se.length>0||fe!==null,me=!($?.visibilityCondition===!1)&&(Z||K||ee||D||re.length>0),Ce=u.useMemo(()=>{const ve=[];return D&&ve.push("settings"),Z&&ve.push("props"),K&&ve.push("style"),ee&&ve.push("action"),me&&ve.push("visibility"),ve.push("translation"),re.length>0&&ve.push("advanced"),ve},[D,Z,K,ee,me,re.length]),ze=T.length>0||P||G||V,[Se,qe]=u.useState(v&&Ce.includes(v)?v:D?"settings":ze?"props":K?"style":Z?"props":Ce[0]??"style"),De=yA(e),Pe=!Z&&!K&&!D&&!ee&&!me&&re.length===0,Qe=$?.label?$.label.startsWith("$t:")?o($.label.slice(3)):$.label:N||o("layout_editor.property_modal.element"),Me=(ve,te)=>{const he={...e.props??{}};te===void 0?delete he[ve]:he[ve]=te,r({...e,props:he})},Re={settings:o("layout_editor.property_modal.tab.settings"),props:o("layout_editor.property_modal.tab.props"),style:o("layout_editor.property_modal.tab.style"),action:o("layout_editor.property_modal.tab.action"),visibility:o("layout_editor.property_modal.tab.visibility"),translation:o("layout_editor.property_modal.tab.translation"),advanced:o("layout_editor.property_modal.tab.advanced")};return i.jsxs("div",{className:"g7le-property-modal","data-testid":"g7le-property-modal",style:ST,children:[i.jsxs("div",{"data-modal-drag-handle":!0,"data-testid":"g7le-property-modal-header",style:CT,children:[i.jsx("span",{"data-testid":"g7le-property-modal-title",style:{fontSize:14,fontWeight:700},children:D&&Se==="settings"?o("layout_editor.property_modal.settings_title",{name:Qe}):o("layout_editor.property_modal.title",{name:Qe})}),i.jsx("button",{type:"button","data-testid":"g7le-property-modal-close","aria-label":"close",onClick:s,style:$T,children:"✕"})]}),De&&i.jsx("div",{"data-testid":"g7le-property-modal-advanced-badge",style:ET,children:o("layout_editor.property_modal.advanced_badge")}),x&&i.jsx("div",{"data-testid":"g7le-property-modal-branch-badge",style:IT,children:o("layout_editor.property_modal.branch_badge",{device:x})}),i.jsx("div",{style:AT,role:"tablist",children:Ce.map(ve=>i.jsx("button",{type:"button",role:"tab","aria-selected":Se===ve,"data-testid":`g7le-property-tab-${ve}`,"data-active":Se===ve?"true":"false",onClick:()=>qe(ve),style:{...TT,color:Se===ve?"#2563eb":"#64748b",borderBottomColor:Se===ve?"#2563eb":"transparent"},children:Re[ve]},ve))}),i.jsxs("div",{style:DT,"data-testid":"g7le-property-modal-body",children:[Pe&&!S&&i.jsx("div",{"data-testid":"g7le-property-modal-no-editable",style:ng,children:o("layout_editor.property_modal.no_editable_props")}),S&&i.jsx(xT,{injectedProps:_,t:o,onSaveInjectedProps:b}),Se==="settings"&&z&&i.jsx(rA,{spec:z,node:e,t:o,onPatchProp:Me}),Se==="props"&&i.jsxs("div",{"data-testid":"g7le-property-props-tab",style:{display:"flex",flexDirection:"column"},children:[V&&i.jsx(i6,{node:e,candidates:f??[],t:o,onPatchNode:r}),G&&i.jsx(zA,{node:e,dataProps:F,candidates:f??[],t:o,onPatchNode:r}),Y&&i.jsx(e6,{node:e,candidates:f??[],t:o,onPatchNode:r,templateIdentifier:h}),P&&I&&i.jsx(I,{node:e,params:L,spec:t,manifest:n,t:o,onPatchNode:r,templateIdentifier:h,candidates:f}),M.map(ve=>i.jsx(pi,{controlKey:`core-${ve}`,control:za[ve],node:e,t:o,onPatch:r,scope:Wt,bindingCandidates:f},`core-${ve}`)),T.map(ve=>{const te=Ct(t,ve);return te?i.jsx(pi,{controlKey:ve,control:te,node:e,t:o,onPatch:r,scope:Wt,bindingCandidates:f},ve):null}),i.jsx(oT,{node:e,onPatchNode:r,t:o,scopeIdCandidates:k,usedScopeIds:w})]}),Se==="style"&&i.jsxs("div",{"data-testid":"g7le-property-style-tab",style:{display:"flex",flexDirection:"column"},children:[i.jsx("div",{style:tg,children:i.jsx(Uf,{scope:g,onChange:E,node:e,t:o,onClearScope:C})}),fe!==null&&i.jsx(z6,{node:e,spec:t,capability:$,t:o,onPatchNode:r,liveElement:y,scope:g}),se.map(ve=>{const te=Ct(t,ve);return te?i.jsx(pi,{controlKey:ve,control:te,node:e,t:o,onPatch:r,scope:g},ve):null})]}),Se==="action"&&i.jsx(AA,{node:e,spec:t,capability:$,t:o,onPatchNode:r,pageCandidates:d,dataSourceCandidates:c,stateKeyCandidates:p,bindingCandidates:f}),Se==="visibility"&&i.jsxs("div",{"data-testid":"g7le-property-visibility-tab",style:{display:"flex",flexDirection:"column"},children:[i.jsx("div",{style:tg,children:i.jsx(Uf,{scope:g,onChange:E,node:e,t:o,showColorScheme:!1})}),i.jsx($u,{node:e,spec:t,t:o,onPatchNode:r,dataSourceCandidates:c,stateKeyCandidates:p,scope:g})]}),Se==="translation"&&(h?i.jsx(Vd,{customKey:Kd(e),templateIdentifier:h,t:o,paramLabels:pv(e),onRemoveParam:ve=>{const te=typeof e.text=="string"?e.text:"";r({...e,text:bo(te,ve)});const he=Kd(e);h&&he&&kr(h,he,ve)}}):i.jsx("div",{"data-testid":"g7le-property-translation-deferred",style:ng,children:o("layout_editor.translation.not_a_key")})),Se==="advanced"&&i.jsx(mA,{node:e,advanced:re,t:o,onPatch:r,permissionCandidates:l})]}),i.jsxs("div",{style:NT,children:[i.jsx("span",{"data-testid":"g7le-property-modal-node-id",style:{fontSize:11,color:"#94a3b8"},children:typeof e.id=="string"||typeof e.id=="number"?`ID: ${e.id}`:""}),i.jsxs("div",{style:{display:"flex",gap:8},children:[i.jsx("button",{type:"button","data-testid":"g7le-property-modal-delete",onClick:a,style:zT,children:o("layout_editor.property_modal.delete_element")}),i.jsx("button",{type:"button","data-testid":"g7le-property-modal-done",onClick:s,style:MT,children:o("layout_editor.property_modal.close")})]})]})]})}const ST={display:"flex",flexDirection:"column",width:420,maxWidth:"92vw"},CT={display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderBottom:"1px solid #e2e8f0",cursor:"move",userSelect:"none"},$T={border:"none",background:"transparent",fontSize:14,cursor:"pointer",color:"#64748b"},ET={margin:"8px 16px 0",padding:"6px 10px",fontSize:11,background:"#fef3c7",color:"#92400e",borderRadius:6},IT={margin:"8px 16px 0",padding:"6px 10px",fontSize:11,background:"#dbeafe",color:"#1e40af",borderRadius:6},AT={display:"flex",gap:2,padding:"0 12px",borderBottom:"1px solid #e2e8f0",overflowX:"auto"},TT={padding:"8px 10px",fontSize:12,border:"none",borderBottom:"2px solid transparent",background:"transparent",cursor:"pointer",whiteSpace:"nowrap"},DT={padding:16,overflowY:"auto",maxHeight:"60vh"},tg={position:"sticky",top:-16,zIndex:2,background:"#fff",margin:"-16px -16px 0",padding:"6px 16px 0"},ng={fontSize:12,color:"#94a3b8",padding:"16px 0",textAlign:"center"},NT={display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderTop:"1px solid #e2e8f0"},zT={padding:"6px 12px",fontSize:12,border:"1px solid #fecaca",borderRadius:6,background:"#fff",color:"#dc2626",cursor:"pointer"},MT={padding:"6px 12px",fontSize:12,border:"none",borderRadius:6,background:"#2563eb",color:"#fff",cursor:"pointer"},La="g7le:component-target-picked",Pa="g7le:component-target-pick-request";let LT=1;function PT({value:e,onChange:t,t:n,control:o}){const r=yo(),s=e==null?"":String(e),a=o?.allowManualInput!==!1,l=u.useCallback(()=>{if(typeof window>"u")return;const d=`pick-${LT++}`,p=r.stack[r.stack.length-1]?.id;p&&r.minimize(p,n("layout_editor.target_picker.minimized_hint"));const f=y=>{const g=y.detail;g?.requestId===d&&(window.removeEventListener(La,f),p&&r.restore(p),!g.cancelled&&typeof g.id=="string"&&t(g.id))};window.addEventListener(La,f),window.dispatchEvent(new CustomEvent(Pa,{detail:{requestId:d}}))},[r,t,n]);return i.jsx("div",{className:"g7le-component-target-picker","data-testid":"g7le-component-target-picker",children:i.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center"},children:[a?i.jsx("input",{type:"text",className:"g7le-widget g7le-widget--text","data-testid":"g7le-component-target-input",value:s,placeholder:n("layout_editor.target_picker.id_placeholder"),onChange:d=>t(d.target.value===""?void 0:d.target.value),style:{flex:1,minWidth:0,padding:"6px 8px",border:"1px solid #cbd5e1",borderRadius:6,fontSize:13}}):i.jsx("span",{"data-testid":"g7le-component-target-value",style:{flex:1,minWidth:0},children:s||n("layout_editor.target_picker.none")}),i.jsxs("button",{type:"button","data-testid":"g7le-component-target-pick",onClick:l,style:{display:"flex",alignItems:"center",gap:4,padding:"6px 10px",background:"#1e293b",color:"#fff",border:"none",borderRadius:6,cursor:"pointer",fontSize:13,whiteSpace:"nowrap"},children:[i.jsx("span",{"aria-hidden":"true",children:"🎯"}),n("layout_editor.target_picker.select_area")]})]})})}async function OT(e,t,n,o,r=fetch){const s=`/api/admin/templates/${encodeURIComponent(e)}/layout-extensions/${t}`;let a;try{a=await r(s,{headers:je(),credentials:"same-origin"})}catch(b){return{kind:"error",message:b instanceof Error?b.message:String(b)}}if(a.status===404)return{kind:"not_found"};if(!a.ok)return{kind:"error",message:`HTTP ${a.status}`};const l=await a.json().catch(()=>null),d=(l&&(l.data||l))??{};let c={};const p=d.content;if(typeof p=="string")try{c=JSON.parse(p)}catch{return{kind:"error",message:"invalid extension content"}}else p&&typeof p=="object"&&(c=p);const f=typeof d.lock_version=="number"?d.lock_version:0,y=Array.isArray(c.injections)?[...c.injections]:[],g=y.findIndex(b=>b&&b.position==="inject_props"&&b.target_id===n);if(g<0)return{kind:"injection_not_found"};y[g]={...y[g],props:o};const m={...c,injections:y};let h;try{h=await r(s,{method:"PUT",headers:je({"Content-Type":"application/json"}),credentials:"same-origin",body:JSON.stringify({content:m,expected_lock_version:f})})}catch(b){return{kind:"error",message:b instanceof Error?b.message:String(b)}}const v=await h.json().catch(()=>null);return h.ok?{kind:"success",newLockVersion:typeof v?.data?.lock_version=="number"?v.data.lock_version:f+1}:h.status===409?{kind:"conflict",currentVersion:v?.current_version??-1,yourVersion:v?.your_version??f}:{kind:"error",message:v?.message??`HTTP ${h.status}`}}const og=new Map;function Oa(e,t){og.set(e,t)}function BT(e){return e?og.get(e)??null:null}const rg="g7le.clipboard";function ig(){try{return typeof window>"u"||!window.sessionStorage?null:window.sessionStorage}catch{return null}}function WT(e){const t=JSON.parse(JSON.stringify(e)),n=o=>{for(const r of Object.keys(o))r.startsWith("__")&&delete o[r];Array.isArray(o.children)&&o.children.forEach(n)};return n(t),t}function sg(e,t=0){const n=ig();if(!n)return!1;try{const o={node:WT(e),copiedAt:t};return n.setItem(rg,JSON.stringify(o)),!0}catch{return!1}}function jT(){const e=ig();if(!e)return null;try{const t=e.getItem(rg);if(!t)return null;const n=JSON.parse(t);return!n||typeof n.node!="object"||n.node===null?null:JSON.parse(JSON.stringify(n.node))}catch{return null}}const Yo={nw:{width:-1,height:-1},n:{width:0,height:-1},ne:{width:1,height:-1},e:{width:1,height:0},se:{width:1,height:1},s:{width:0,height:1},sw:{width:-1,height:1},w:{width:-1,height:0}};function Ba(e){if(typeof e=="number")return e;if(typeof e=="string"){const t=e.match(/^(-?\d+(?:\.\d+)?)px$/);if(t)return Number(t[1])}return null}function HT(e,t){const n=Array.isArray(e.options)?e.options:[],o=Array.isArray(e.scale)?e.scale:[],r=n.length>0?n.map(l=>l.value):o;if(r.length===0)return;let s=r[0],a=1/0;return r.forEach((l,d)=>{const c=Ba(l)??d*40,p=Math.abs(c-t);p{if(!t)return;const m=Yo[y];if(m.width!==0&&!n||m.height!==0&&!o)return;const h=t.props?.style??{},v=s?.()??null,b=Ba(h.width)??(v?Math.round(v.width):0),x=Ba(h.height)??(v?Math.round(v.height):0);p.current={handle:y,startX:g.clientX,startY:g.clientY,startW:b,startH:x,node:t};const k=m.width!==0&&m.height!==0?"both":m.width!==0?"width":"height";d?.(k);let w=null;const _=E=>{const C=p.current;if(!C)return;const N=r||1,$=(E.clientX-C.startX)/N*Yo[C.handle].width,A=(E.clientY-C.startY)/N*Yo[C.handle].height;let z=C.node;if(Yo[C.handle].width!==0&&n){const D=ag(n,C.startW+$);z=fn(z,n,D)}if(Yo[C.handle].height!==0&&o){const D=ag(o,C.startH+A);z=fn(z,o,D)}w=z,a(z,k)},S=()=>{p.current=null,d?.(null),window.removeEventListener("pointermove",_),window.removeEventListener("pointerup",S),w&&l?.(w,k)};window.addEventListener("pointermove",_),window.addEventListener("pointerup",S)},[t,n,o,r,a,l,d]);return{enabledAxes:c,onHandlePointerDown:f}}const lg=320,dg=1920,VT=1024;function Wa(e){return Number.isFinite(e)?Math.round(Math.max(lg,Math.min(dg,e))):VT}function ja(e={}){const{state:t,dispatch:n}=Je(),{previewDevice:o,previewZoom:r,previewCustomWidth:s,previewColorScheme:a}=t,l=o==="custom"?Wa(s):V6(o),d=u.useMemo(()=>{const g=e.availableWidth??l,m=l*r;return r>=1||m<=g?r:Math.min(r,g/l)},[l,r,e.availableWidth]),c=u.useCallback(g=>{n({type:"SET_PREVIEW_DEVICE",device:g})},[n]),p=u.useCallback(g=>{const m=Math.max(.5,Math.min(1,g));n({type:"SET_PREVIEW_ZOOM",zoom:m})},[n]),f=u.useCallback(g=>{n({type:"SET_PREVIEW_CUSTOM_WIDTH",width:Wa(g)})},[n]),y=u.useCallback(g=>{n({type:"SET_PREVIEW_COLOR_SCHEME",scheme:g})},[n]);return{device:o,deviceWidth:l,zoom:r,scale:d,customWidth:Wa(s),setDevice:c,setZoom:p,setCustomWidth:f,colorScheme:a,setColorScheme:y}}const yi="g7le-dnd-handle-";function UT(e){if(typeof e!="string"||!e.startsWith(yi))return null;const t=e.slice(yi.length);return t.length>0?t:null}function qT(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/["\\\]]/g,"\\$&")}function GT(e,t,n,o){const r=o?.handleFallback??!1;if(e instanceof HTMLElement){const s=e.closest("[data-editor-path]");if(s)return s;const a=e.closest('[data-testid^="g7le-"]');if(a&&!(a.getAttribute("data-testid")??"").startsWith(yi))return null;if(r){const l=e.closest(`[data-testid^="${yi}"]`);if(l&&t){const d=UT(l.getAttribute("data-testid"));if(d){const c=t.querySelector(`[data-editor-path="${qT(d)}"]`);if(c)return c}}}}if(r&&n&&typeof document<"u"&&typeof document.elementsFromPoint=="function")for(const s of document.elementsFromPoint(n.x,n.y)){const a=s.closest?.("[data-editor-path]");if(a)return a}return null}function YT(e,t,n){if(typeof e=="string"&&e.trim().length>0)return{color:e};const o=typeof n?.color=="string"&&n.color.length>0,r=typeof t=="string"&&t.trim().length>0;return o||r?{}:{color:"#0f172a"}}const XT="#ffffff",JT="#0f172a";function ZT(e){const t=e.trim(),n=t.match(/^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)/i);if(n)return[Number(n[1]),Number(n[2]),Number(n[3])];const o=t.replace(/^#/,"");return/^[0-9a-f]{3}$/i.test(o)?[parseInt(o[0]+o[0],16),parseInt(o[1]+o[1],16),parseInt(o[2]+o[2],16)]:/^[0-9a-f]{6}$/i.test(o)?[parseInt(o.slice(0,2),16),parseInt(o.slice(2,4),16),parseInt(o.slice(4,6),16)]:null}function QT(e){if(!e||/transparent/i.test(e))return!1;const t=e.trim().match(/^oklch\(\s*([\d.]+)(%?)/i);if(t)return(t[2]==="%"?Number(t[1])/100:Number(t[1]))>=.62;const n=ZT(e);if(!n)return!1;const[o,r,s]=n;return .299*o+.587*r+.114*s>=180}function RT(e,t,n){const o=typeof n?.color=="string"?n.color:null;return QT(e??o??t)?JT:XT}function e4({box:e,initialValue:t,isCustomKey:n,t:o,onCommit:r,onCancel:s,mirrorClassName:a,mirrorStyle:l,nodeEffectiveColor:d,onOpenTranslations:c}){const p=u.useRef(null),f=u.useRef(!1),[y,g]=u.useState(t.trim().length>0),[m,h]=u.useState(null);u.useEffect(()=>{const w=p.current;if(w){w.textContent=t,w.focus();try{const _=window.document.createRange();_.selectNodeContents(w);const S=window.getSelection();S?.removeAllRanges(),S?.addRange(_)}catch{}f.current=!1}},[t]),u.useEffect(()=>{const w=p.current;if(!w||typeof window.getComputedStyle!="function"){h(null);return}try{h(window.getComputedStyle(w).color||null)}catch{h(null)}},[a,l]);const v=()=>(p.current?.textContent??"").trim(),b=()=>{f.current||(f.current=!0,r(v()))},x=()=>{f.current||(f.current=!0,s())},k=w=>{w.key==="Enter"&&!w.shiftKey?(w.preventDefault(),b()):w.key==="Escape"&&(w.preventDefault(),x())};return i.jsxs("div",{className:"g7le-inline-text-editor","data-testid":"g7le-inline-text-editor","data-custom-key":n?"true":"false",style:{position:"absolute",left:e.left,top:e.top,minWidth:Math.max(e.width,60),minHeight:e.height,pointerEvents:"auto",zIndex:1e4},children:[i.jsx("div",{ref:p,role:"textbox","aria-label":o("layout_editor.inline_edit.aria_label"),"aria-multiline":"false","data-testid":"g7le-inline-text-editable",className:a,contentEditable:!0,suppressContentEditableWarning:!0,spellCheck:!1,onInput:()=>g(v().length>0),onKeyDown:k,onBlur:b,style:{outline:"2px solid #2563eb",outlineOffset:1,borderRadius:3,background:RT(d,m,l),padding:"2px 4px",minHeight:e.height,whiteSpace:"pre-wrap",wordBreak:"break-word",boxShadow:"0 2px 8px rgba(37, 99, 235, 0.25)",...l??{},...YT(d,a,l)}}),i.jsxs("div",{className:"g7le-inline-text-editor__hint","data-testid":"g7le-inline-text-editor-hint",style:{marginTop:2,display:"inline-flex",alignItems:"center",gap:4,whiteSpace:"nowrap"},children:[c?i.jsxs("button",{type:"button","data-testid":"g7le-inline-text-editor-open-translations",onMouseDown:w=>w.preventDefault(),onClick:w=>{w.preventDefault(),w.stopPropagation(),c()},title:o("layout_editor.inline_edit.open_translations"),style:{padding:"2px 8px",fontSize:11,background:n?"#eff6ff":"#f0fdf4",color:n?"#1d4ed8":"#15803d",border:`1px solid ${n?"#bfdbfe":"#bbf7d0"}`,borderRadius:4,display:"inline-flex",alignItems:"center",gap:4,cursor:"pointer",whiteSpace:"nowrap"},children:[i.jsx("span",{"aria-hidden":"true",children:"🌐"}),i.jsx("span",{children:o(n?"layout_editor.inline_edit.existing_key_hint":"layout_editor.inline_edit.new_key_hint")}),i.jsxs("span",{"aria-hidden":"true",style:{opacity:.7},children:["· ",o("layout_editor.inline_edit.open_translations")," ›"]})]}):i.jsx("span",{style:{padding:"2px 6px",fontSize:11,background:n?"#eff6ff":"#f0fdf4",color:n?"#1d4ed8":"#15803d",border:`1px solid ${n?"#bfdbfe":"#bbf7d0"}`,borderRadius:4,display:"inline-flex",alignItems:"center",gap:4,whiteSpace:"nowrap"},children:n?i.jsxs(i.Fragment,{children:["⌐ ",o("layout_editor.inline_edit.existing_key_hint")]}):i.jsxs(i.Fragment,{children:["✎ ",o("layout_editor.inline_edit.new_key_hint")]})}),!y&&i.jsx("span",{"data-testid":"g7le-inline-text-editor-empty-warn",style:{color:"#b91c1c",marginLeft:4},children:o("layout_editor.inline_edit.empty_warning")})]})]})}function t4({box:e,node:t,customKey:n,initialChipValue:o,chipParamLabels:r,onKeyify:s,templateIdentifier:a,locale:l,t:d,candidates:c,onInsertBinding:p,onRemoveBinding:f,onCommit:y,onCancel:g}){const[m,h]=u.useState(null),v=u.useRef(""),[b,x]=u.useState(!1),k=u.useRef(!1),w=u.useRef(null),_=Ft(),S=u.useRef(()=>{}),[E,C]=u.useState(null),[N,$]=u.useState(!1),A=u.useRef(n??null);u.useEffect(()=>{n&&A.current!==n&&(A.current=n)},[n]);const z=u.useMemo(()=>{if(!n&&r)return r;const L={},I=mt(typeof t.text=="string"?t.text:"");for(const P of I?.params??[])L[P.name]=Vt(P.expression);return L},[t.text,n,r]);u.useEffect(()=>{let L=!1;if(!n){const I=o??"";return v.current=I,h(I),()=>{L=!0}}return(async()=>{const I=It(n,l);if(I!==void 0){v.current=I,h(I);return}const P=await cn(a,n);if(L)return;const F=P?.values?.[l]??"";v.current=F,h(F)})(),()=>{L=!0}},[a,n,l,o]);const D=async()=>{if(k.current)return;k.current=!0;const L=m??"";if(L===v.current){y();return}x(!0);let I=A.current;if(!I){if(!s){x(!1),k.current=!1;return}if(I=await s(L),x(!1),!I){k.current=!1;return}A.current=I,y();return}const P=await wo(a,I,l,L);if(x(!1),P.kind==="error"){k.current=!1;return}_?.markDirty?.(),y()},O=()=>{k.current||(k.current=!0,g())},M=L=>{C(L)},B=async L=>{if(!(E===null||!p||N)){$(!0);try{const I=A.current;I&&m!==null&&m!==v.current&&(await wo(a,I,l,m),v.current=m);const P=await p(E,L);P!==null&&(h(P),v.current=P,_?.markDirty?.())}finally{$(!1),C(null)}}},T=async L=>{if(!(!f||N)){$(!0);try{const I=A.current;I&&m!==null&&m!==v.current&&(await wo(a,I,l,m),v.current=m);const P=await f(L);P!==null&&(h(P),v.current=P,_?.markDirty?.())}finally{$(!1)}}},H=L=>{L.key==="Enter"&&!L.shiftKey?(L.preventDefault(),D()):L.key==="Escape"&&(L.preventDefault(),O())};return S.current=()=>{D()},u.useEffect(()=>{const L=P=>{const F=w.current;if(!F)return;const G=P.target;if(G&&F.contains(G))return;const V=G;V&&V.closest&&V.closest('[data-testid="g7le-inline-toolbar"], .g7le-inline-toolbar')||S.current()},I=w.current?.ownerDocument??document;return I.addEventListener("pointerdown",L,!0),()=>I.removeEventListener("pointerdown",L,!0)},[]),i.jsxs("div",{ref:w,className:"g7le-inline-param-chip-editor","data-testid":"g7le-inline-param-chip-editor",onKeyDown:H,style:{position:"absolute",left:e.left,top:e.top,minWidth:Math.max(e.width,120),pointerEvents:"auto",zIndex:1e4,background:"#fff",border:"2px solid #2563eb",borderRadius:4,boxShadow:"0 2px 8px rgba(37,99,235,0.25)",padding:4},children:[m===null?i.jsx("div",{"data-testid":"g7le-inline-param-chip-loading",style:{fontSize:12,color:"#94a3b8",padding:4},children:d("layout_editor.translation.loading")}):i.jsx(mr,{value:m,onChange:h,t:d,paramLabels:z,testIdSuffix:"inline",onRequestInsert:p?M:void 0,onRemoveChip:f?L=>{T(L)}:void 0}),E!==null&&p&&i.jsx("div",{"data-testid":"g7le-inline-param-chip-insert-picker",style:{marginTop:4},children:i.jsx($t,{candidates:c??[],t:d,onSelect:L=>{B(L)},testIdSuffix:"inline-insert",defaultOpen:!0,floating:!1})}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginTop:4},children:[i.jsx("button",{type:"button","data-testid":"g7le-inline-param-chip-save",disabled:b,onMouseDown:L=>L.preventDefault(),onClick:()=>{D()},style:{fontSize:11,border:"none",borderRadius:6,background:"#2563eb",color:"#fff",padding:"4px 12px",cursor:"pointer"},children:d(b?"layout_editor.translation.saving":"layout_editor.translation.save")}),i.jsx("span",{style:{fontSize:10,color:"#94a3b8"},children:d("layout_editor.translation.placeholder_locked")})]})]})}const n4=["fontWeight","fontBold","fontStyle","fontItalic","textDecoration","textUnderline","textAlign","fontSize","textColor"],o4={fontWeight:"B",fontBold:"B",fontStyle:"I",fontItalic:"I",textDecoration:"U",textUnderline:"U",textAlign:"≡",fontSize:"T",textColor:"A"},r4=[["fontWeight","fontBold"],["fontItalic","fontStyle"],["textUnderline","textDecoration"]];function cg({node:e,spec:t,t:n,onApplyControl:o,box:r,scope:s=Wt}){const a=typeof e.name=="string"?e.name:"",l=Oi(t,a),d=Array.isArray(l?.styleControls)?l.styleControls:[];let c=n4.filter(p=>d.includes(p)&&Ct(t,p)!==null);for(const p of r4){const f=p.filter(y=>c.includes(y));if(f.length>1){const y=f[0];c=c.filter(g=>!p.includes(g)||g===y)}}return c.length===0?null:i.jsx("div",{className:"g7le-inline-toolbar","data-testid":"g7le-inline-toolbar",role:"toolbar","aria-label":n("layout_editor.inline_edit.toolbar_label"),style:{position:"absolute",left:r.left,top:r.top-40,display:"inline-flex",gap:2,padding:4,background:"#0f172a",borderRadius:8,boxShadow:"0 4px 12px rgba(15, 23, 42, 0.35)",pointerEvents:"auto",zIndex:10001},children:c.map(p=>i.jsx(s4,{controlKey:p,node:e,spec:t,t:n,scope:s,onApplyControl:o},p))})}const i4={fontWeight:"bold",fontBold:"bold",fontStyle:"italic",fontItalic:"italic",textDecoration:"underline",textUnderline:"underline"};function ug(e,t){const n=r=>(r.split(/[-\s]/).pop()??r)===t||r===t;return e.find(r=>{const s=typeof r.value=="string"?r.value:"",a=Array.isArray(r.apply?.tokens)?r.apply.tokens:[];return n(s)||a.some(n)})?.value}function s4({controlKey:e,node:t,spec:n,t:o,scope:r,onApplyControl:s}){const[a,l]=u.useState(!1),d=Ct(n,e);if(!d)return null;const c=d.options,p=Array.isArray(c),f=To(t,d,r),y=i4[e],g=y&&Array.isArray(c)?ug(c,y):void 0,m=!y,h=g!==void 0?f.value===g:p&&f.matched&&f.value!==void 0&&f.value!=="",v=o(`layout_editor.inline_edit.format.${e}`),b=_=>typeof _.label=="string"?_.label.startsWith("$t:")?o(_.label.slice(3)):_.label:String(_.value??""),x=()=>{s(e,_=>{const S=To(_,d,r),E=Array.isArray(c)?ug(c,y):void 0,C=E!==void 0&&S.value===E?void 0:E;return fn(_,d,C,r)})},k=_=>{s(e,S=>{const C=To(S,d,r).value===_?void 0:_;return fn(S,d,C,r)}),l(!1)},w=_=>{if(_.preventDefault(),_.stopPropagation(),!m&&Array.isArray(c)){x();return}l(S=>!S)};return i.jsxs("div",{style:{position:"relative",display:"inline-flex"},children:[i.jsxs("button",{type:"button","data-testid":`g7le-inline-format-${e}`,"data-active":h?"true":"false","aria-label":v,"aria-pressed":p?h:void 0,title:v,onMouseDown:_=>_.preventDefault(),onClick:w,style:{display:"inline-flex",alignItems:"center",gap:5,height:28,padding:"0 9px",fontSize:12,border:"none",borderRadius:5,cursor:"pointer",background:h?"#2563eb":"transparent",color:"#ffffff",whiteSpace:"nowrap"},children:[i.jsx("span",{"aria-hidden":"true",style:{fontWeight:e==="fontWeight"||e==="fontBold"?700:600,fontStyle:e==="fontStyle"||e==="fontItalic"?"italic":"normal",textDecoration:e==="textDecoration"||e==="textUnderline"?"underline":"none"},children:o4[e]}),i.jsx("span",{children:v}),m&&i.jsx("span",{"aria-hidden":"true",style:{fontSize:9,opacity:.8},children:"▾"})]}),m&&a&&i.jsx("div",{"data-testid":`g7le-inline-popover-${e}`,role:"listbox",onMouseDown:_=>_.preventDefault(),style:{position:"absolute",top:32,left:0,minWidth:140,maxHeight:240,overflowY:"auto",background:"#0f172a",border:"1px solid #334155",borderRadius:8,boxShadow:"0 8px 24px rgba(15,23,42,0.45)",padding:4,zIndex:10002},children:Array.isArray(c)&&c.length>0?c.map((_,S)=>{const E=f.value===_.value;return i.jsxs("button",{type:"button",role:"option","aria-selected":E,"data-testid":`g7le-inline-option-${e}-${String(_.value??S)}`,onMouseDown:C=>C.preventDefault(),onClick:C=>{C.preventDefault(),C.stopPropagation(),k(_.value)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",fontSize:12,textAlign:"left",border:"none",borderRadius:5,cursor:"pointer",background:E?"#2563eb":"transparent",color:"#ffffff"},children:[typeof _.swatch=="string"&&i.jsx("span",{"aria-hidden":"true",style:{width:14,height:14,borderRadius:3,background:_.swatch,border:"1px solid rgba(255,255,255,0.3)"}}),i.jsx("span",{children:b(_)}),E&&i.jsx("span",{"aria-hidden":"true",style:{marginLeft:"auto"},children:"✓"})]},String(_.value??S))}):i.jsx(a4,{testid:`g7le-inline-freeinput-${e}`,placeholder:o(`layout_editor.inline_edit.prompt.${e}`),initial:typeof f.value=="string"?f.value:"",onSubmit:_=>{s(e,S=>fn(S,d,_,r)),l(!1)}})})]})}function a4({testid:e,placeholder:t,initial:n,onSubmit:o}){const[r,s]=u.useState(n);return i.jsx("input",{type:"text","data-testid":e,value:r,placeholder:t,autoFocus:!0,onMouseDown:a=>a.stopPropagation(),onChange:a=>s(a.currentTarget.value),onKeyDown:a=>{a.key==="Enter"&&(a.preventDefault(),o(r.trim()))},style:{width:130,padding:"6px 8px",fontSize:12,border:"1px solid #334155",borderRadius:5,background:"#1e293b",color:"#ffffff"}})}function l4(e){const{frameEl:t,manifest:n,nesting:o,componentPalette:r,spec:s=null,permissionCandidates:a,resolveRouteMatch:l,onNavigateToDestination:d,onSessionAddedPathsChange:c,onEditProps:p}=e,{state:f,dispatch:y}=Je(),{t:g}=tt(),m=ja(),h=u.useCallback((W,X)=>{const R=window.G7Core;if(R&&typeof R.t=="function"){const de=R.t(W,X);if(de&&de!==W&&!de.startsWith("$t:"))return de}return g(W,X)},[g]),v=Ft(),b=i7(50),x=yo(),k=u.useRef([]),w=u.useMemo(()=>v?.document?.raw?.components??[],[v?.document?.raw?.components]),_=u.useMemo(()=>w.length===0?null:{children:w},[w]),S=u.useMemo(()=>{if(f.editMode!=="extension")return;const W=/^__extension__\/(\d+)/.exec(f.selectedRoute?.path??"");return W?Number(W[1]):void 0},[f.editMode,f.selectedRoute?.path]),E=u.useMemo(()=>{if(f.editMode==="iteration_item"){const W=v?.document?.iterationContext?.sourceIndexPath;return Array.isArray(W)&&W.length>0?W:null}if(f.editMode==="modal"){const W=v?.document?.modalContext?.editIndexPath;return Array.isArray(W)&&W.length>0?W:null}return null},[f.editMode,v?.document?.iterationContext?.sourceIndexPath,v?.document?.modalContext?.editIndexPath]),C=JE({rootNode:_,editMode:f.editMode,currentExtensionId:S,editableRootPath:E,pathParser:Ze,resolveRouteMatch:l}),[N,$]=u.useState(null),[A,z]=u.useState(null),[D,O]=u.useState(null),M=u.useRef(null);M.current=D;const[B,T]=u.useState(null),H=u.useRef(null),L=u.useRef(null);L.current=C.selectedPath;const I=Pb(),[P,F]=u.useState(null),G=u.useCallback(W=>{if(!t)return;const X=Ze(W);if(!X)return;const R={children:Me.current.components},de=We(R,X),ye=I.classify(de);if(!ye.editable){Et({op:"inline_edit_blocked_binding",sourceState:ye.sourceState,componentPath:at(X),timestamp:Date.now()});return}const we=po(t,W);if(!we)return;const Te=de?.props??{},ke=fg(t,W);F({path:X,domPath:W,box:we,initialValue:ye.displayValue,isCustomKey:ye.sourceState==="custom_key",isParamKey:ye.isParamKey===!0,customKey:ye.customKey,chipValue:ye.chipValue,chipParamLabels:ye.chipParamLabels,mirrorClassName:typeof Te.className=="string"?Te.className:void 0,mirrorStyle:Te.style??void 0,nodeEffectiveColor:ke}),Et({op:"inline_edit_enter",sourceState:ye.sourceState,componentPath:at(X),timestamp:Date.now()})},[t,I]),V=u.useCallback(()=>{if(!t){$(null),z(null);return}z(po(t,C.selectedPath)),$(po(t,C.hoverPath))},[t,C.selectedPath,C.hoverPath,w]);u.useEffect(()=>{if(V(),typeof window<"u"&&typeof window.requestAnimationFrame=="function"){const W=window.requestAnimationFrame(()=>V());return()=>window.cancelAnimationFrame(W)}},[V]),u.useEffect(()=>{if(t)return kp(V,t)},[t,V]);const Y=u.useCallback((W,X)=>{if(typeof window>"u")return;window.dispatchEvent(new CustomEvent(La,{detail:X===null?{requestId:W,cancelled:!0}:{requestId:W,id:X}})),O(null),T(null);const R=H.current;R?C.handleSelect("",{dataset:{editorPath:R}}):C.clearSelection(),H.current=null},[C]);u.useEffect(()=>{if(typeof window>"u")return;const W=X=>{const R=X.detail;if(typeof R?.requestId!="string")return;const de=M.current;de&&de!==R.requestId&&Y(de,null),H.current=L.current,O(R.requestId)};return window.addEventListener(Pa,W),()=>window.removeEventListener(Pa,W)},[Y]),u.useEffect(()=>{if(!D)return;const W=X=>{X.key==="Escape"&&(X.preventDefault(),Y(D,null))};return window.addEventListener("keydown",W,!0),()=>window.removeEventListener("keydown",W,!0)},[D,Y]),u.useEffect(()=>{if(!t)return;const W=f.editMode==="iteration_item"||f.editMode==="modal",X=(xe,Ee)=>GT(xe,t,Ee?{x:Ee.clientX,y:Ee.clientY}:void 0,{handleFallback:W}),R=xe=>{const Ee=xe.dataset.editorPath??"",Fe=Ee?Ze(Ee):null,zt={children:Me.current.components},gt=Fe?We(zt,Fe):null,Mt=gt&&typeof gt.props?.id=="string"?gt.props.id:typeof gt?.id=="string"?gt.id:"";return Mt.startsWith("auto_")?"":Mt},de=xe=>{const Ee=X(xe.target,xe);if(!Ee)return;const Fe=M.current;if(Fe){xe.preventDefault(),xe.stopPropagation();const zt=R(Ee);zt&&Y(Fe,zt);return}xe.preventDefault(),xe.stopPropagation(),C.handleSelect(Ee.dataset.editorId??"",{currentTarget:Ee,dataset:Ee.dataset})},ye=xe=>{const Ee=X(xe.target,xe);if(M.current){if(!Ee){T(null);return}const Fe=po(t,Ee.dataset.editorPath??null);if(!Fe){T(null);return}T({box:Fe,hasId:R(Ee)!==""});return}if(!Ee){C.handleHover(null,{});return}C.handleHover(Ee.dataset.editorId??"",{currentTarget:Ee,dataset:Ee.dataset})},we=()=>{if(M.current){T(null);return}C.handleHover(null,{})},Te=xe=>{const Ee=X(xe.target,xe);if(!Ee)return;const Fe=Ee.dataset.editorPath??"";Fe&&(xe.preventDefault(),xe.stopPropagation(),G(Fe))},ke=t.parentElement??t;return ke.addEventListener("click",de,!0),ke.addEventListener("mousemove",ye,!0),ke.addEventListener("mouseleave",we,!0),ke.addEventListener("dblclick",Te,!0),()=>{ke.removeEventListener("click",de,!0),ke.removeEventListener("mousemove",ye,!0),ke.removeEventListener("mouseleave",we,!0),ke.removeEventListener("dblclick",Te,!0)}},[t,C,G,f.editMode,Y]);const Z=u.useMemo(()=>{const W=C.selectedPath;if(!W)return null;const X=W.match(/^(.*)\.children\.\d+$/);return X?X[1]:null},[C.selectedPath]),se=u.useCallback(()=>{Z&&C.handleSelect("",{dataset:{editorPath:Z}})},[Z,C]),re=u.useMemo(()=>!t||!C.selectedPath?null:t.querySelector(`[data-editor-path="${an(C.selectedPath)}"]`),[t,C.selectedPath]),U=u.useMemo(()=>C.selectedPath?Ze(C.selectedPath):null,[C.selectedPath]),ee=u.useMemo(()=>{if(!U)return null;const W=U.find(et);if(!W)return null;const{i18nKey:X,raw:R}=gC(W.responsive);return X?g(X):g("layout_editor.overlay.branch_custom",{range:R})},[U,g]),fe=u.useMemo(()=>C.selectedPath?C.selectedIsIteration&&C.selectedIterationSourcePath?C.selectedIterationSourcePath:C.selectedPath:null,[C.selectedPath,C.selectedIsIteration,C.selectedIterationSourcePath]),K=u.useMemo(()=>fe?Ze(fe):null,[fe]),ne=u.useMemo(()=>!t||!fe?null:t.querySelector(`[data-editor-path="${an(fe)}"]`),[t,fe]),me=u.useMemo(()=>{if(ne?.parentElement)return ne.parentElement;if(!t||!fe)return null;const W=fe.match(/^(.*)\.children\.\d+$/);return W?t.querySelector(`[data-editor-path="${an(W[1])}"]`):null},[ne,t,fe]),Ce=u.useMemo(()=>{const W=C.selectedNode;return W&&(typeof W.name=="string"?W.name:typeof W.type=="string"?W.type:"")||null},[C.selectedNode]),ze=u.useMemo(()=>{if(C.selectedLockKind!=="extension")return null;const W=C.selectedNode?.__source;if(!W||W.kind!=="extension")return null;const X=W.extensionName?.trim(),R=W.extensionIdentifier?.trim();return X&&R?`${X} (${R})`:X||R||W.extensionSourceType||null},[C.selectedLockKind,C.selectedNode]),Se=n7({parentEl:me,selectedPath:K,selectedEl:ne}),qe=u.useMemo(()=>!t||!fe||fe===C.selectedPath?A:po(t,fe),[t,fe,A,C.selectedPath,w]),De=u.useRef(null),Pe=u.useCallback(()=>{const W=De.current;W&&(x.close(W),De.current=null)},[x]),Qe=u.useRef(()=>{}),Me=u.useRef({manifest:n,nesting:o,componentPalette:r,components:w});Me.current={manifest:n,nesting:o,componentPalette:r,components:w};const Re=u.useCallback(W=>{const X=W.insertion?.parentPath??[],R=W.insertion?.index??0,de=Me.current,ye=pg(de.components,X);Pe();const we=x.open({ariaLabel:h("layout_editor.palette.title"),width:880,maxHeightRatio:.82,content:u.createElement(Sf,{manifest:de.manifest,nesting:de.nesting,componentPalette:de.componentPalette??null,targetParentPath:X,targetContainerName:ye,onInsert:(Te,ke,xe)=>{Qe.current(Te,ke,xe)},insertionIndex:R,onClose:()=>Pe(),editorTemplateId:f.templateIdentifier,editorLocale:f.locale}),onClose:()=>{De.current=null}});De.current=we},[x,Pe]),ve=u.useMemo(()=>{if(!f.isPaletteOpen)return null;if(!U)return{parentPath:[],index:w.length};if(C.selectedLockKind!=="none"){const de=K;return!de||de.length===0?{parentPath:[],index:w.length}:{parentPath:de.slice(0,-1),index:(de[de.length-1]??0)+1}}const X=C.selectedNode,R=Array.isArray(X?.children)?X.children.length:0;return rI(X?.name,R,U,o,w.length)},[f.isPaletteOpen,U,K,C.selectedLockKind,C.selectedNode,w.length,o]),te=u.useCallback(()=>{y({type:"SET_PALETTE_OPEN",open:!1})},[y]),he=u.useRef(null);u.useEffect(()=>{if(!f.isPaletteOpen){const ye=he.current;ye&&(x.close(ye),he.current=null);return}if(!ve||he.current)return;const W=ve,X=Me.current,R=pg(X.components,W.parentPath),de=x.open({ariaLabel:h("layout_editor.palette.title"),width:880,maxHeightRatio:.82,content:u.createElement(Sf,{manifest:X.manifest,nesting:X.nesting,componentPalette:X.componentPalette??null,targetParentPath:W.parentPath,targetContainerName:R,onInsert:(ye,we,Te)=>{Qe.current(ye,we,Te),te()},insertionIndex:W.index,onClose:()=>te(),editorTemplateId:f.templateIdentifier,editorLocale:f.locale}),onClose:()=>{he.current=null,y({type:"SET_PALETTE_OPEN",open:!1})}});he.current=de},[f.isPaletteOpen,ve,x,te,y]);const Q=u.useRef({layoutName:null,pushed:!1});u.useEffect(()=>{const W=v?.document?.layoutName??null;if(!W){Q.current={layoutName:null,pushed:!1};return}Q.current.layoutName!==W&&(b.clear(),b.push({actionKind:"inline_text_edit",label:"baseline",snapshot:w}),Q.current={layoutName:W,pushed:!0})},[v?.document?.layoutName,w,b]);const ie=u.useRef(0);u.useEffect(()=>{const W=v?.saveSuccessCounter??0;W!==ie.current&&(ie.current=W,W!==0&&(b.clear(),b.push({actionKind:"inline_text_edit",label:"save_baseline",snapshot:w}),k.current=[],c?.([])))},[v?.saveSuccessCounter,w,b,c]);const _e=u.useRef(0);u.useEffect(()=>{const W=v?.reloadCounter??0;W!==_e.current&&(_e.current=W,W!==0&&(Q.current={layoutName:null,pushed:!1},k.current=[],c?.([])))},[v?.reloadCounter,c]);const ge=u.useCallback((W,X,R)=>{if(!v)return;let de=[];v.patchLayout(ke=>{const xe={children:ke},Ee=Ha(xe,X),Fe=R<0?Array.isArray(Ee?.children)?Ee.children.length:0:R,gt=Qi(xe,X,Fe,W).children??[];return de=gt,gt}),b.push({actionKind:"insert",label:`insert ${W.name??W.type??""}`,snapshot:de});const ye=Ha({children:de},X),we=R<0?Array.isArray(ye?.children)?ye.children.length-1:0:R,Te=at([...X,we]);if(k.current=[...k.current,Te],c?.(k.current),t){const ke=`[data-editor-path="${an(Te)}"]`,xe=()=>{const Ee=t.querySelector(ke);Ee&&typeof Ee.scrollIntoView=="function"&&Ee.scrollIntoView({behavior:"smooth",block:"center",inline:"nearest"})};typeof window<"u"&&typeof window.requestAnimationFrame=="function"?window.requestAnimationFrame(()=>window.requestAnimationFrame(xe)):setTimeout(xe,32)}},[v,b,c,t]);Qe.current=ge;const Ae=u.useCallback(()=>{if(!v||!C.selectedNode||!U)return;const W=es(C.selectedNode);let X=[];v.patchLayout(R=>{const de={children:R},ye=U.slice(0,-1),we=U[U.length-1]??0,ke=Qi(de,ye,we+1,W).children??[];return X=ke,ke}),b.push({actionKind:"insert",label:"duplicate",snapshot:X})},[v,C.selectedNode,U,b]),Ne=u.useCallback(()=>{if(!v||!U)return;let W=[];v.patchLayout(X=>{const ye=Ri({children:X},U).children??[];return W=ye,ye}),b.push({actionKind:"remove",label:"remove",snapshot:W}),C.clearSelection()},[v,U,b,C]),Le=u.useMemo(()=>{if(!C.selectedNode||!U||U.some(et))return null;const W=C.selectedNode;if(!Array.isArray(W.children))return null;const X=fC(f.previewDevice,W,f.previewCustomWidth);return{mode:X.mode,key:X.key,sourceKey:X.sourceKey}},[C.selectedNode,U,f.previewDevice,f.previewCustomWidth]),q=u.useCallback(()=>{if(!v||!U||Le?.mode!=="separate")return;const W=Le.key,X=Le.sourceKey;let R=[];v.patchLayout(de=>(R=$b({children:de},U,W,X).children??[],R)),b.push({actionKind:"insert",label:"separate_branch",snapshot:R})},[v,U,Le,b]),ae=u.useCallback(()=>{if(!v||!U||Le?.mode!=="merge")return;const W=Le.key;let X=[];v.patchLayout(R=>(X=Eb({children:R},U,W).children??[],X)),b.push({actionKind:"remove",label:"merge_branch",snapshot:X})},[v,U,Le,b]),pe=u.useCallback(W=>{switch(W){case"mobile":return g("layout_editor.context_menu.device_mobile");case"portable":return g("layout_editor.context_menu.device_portable");case"tablet":return g("layout_editor.context_menu.device_tablet");case"desktop":return g("layout_editor.context_menu.device_desktop");default:return g("layout_editor.context_menu.device_custom",{range:W})}},[g]),$e=u.useMemo(()=>{if(!Le)return null;const W=pe(Le.key);return{separate:g("layout_editor.context_menu.separate_branch_device",{device:W}),merge:g("layout_editor.context_menu.merge_branch_device",{device:W})}},[Le,g,pe]),be=u.useMemo(()=>{if(!C.selectedNode||!U)return[];if(U.some(et))return[];const W=Ur(f.previewDevice,C.selectedNode,f.previewCustomWidth);return K6(C.selectedNode,W).map(X=>({key:X,label:pe(X)}))},[C.selectedNode,U,f.previewDevice,f.previewCustomWidth,pe]),j=u.useCallback(W=>{if(W==="desktop"||W==="tablet"||W==="mobile"||W==="portable"){m.setDevice(W);return}m.setDevice(W)},[m]),oe=u.useCallback(()=>{C.selectedNode&&sg(C.selectedNode)},[C.selectedNode]),ue=u.useCallback(()=>{C.selectedNode&&(sg(C.selectedNode),Ne())},[C.selectedNode,Ne]),J=u.useCallback(()=>{if(!v)return;const W=jT();if(!W)return;const X=es(W);if(U&&U.length>0){const R=U.slice(0,-1),de=(U[U.length-1]??0)+1;ge(X,R,de)}else ge(X,[],w.length)},[v,U,ge,w.length]),le=u.useCallback((W,X)=>{b.push({actionKind:"move",label:X,snapshot:W})},[b]),Ie=u.useCallback(()=>{if(C.selectedNavAffordance==="route_in_tree"&&C.selectedNavTargetPath){if(d){d(C.selectedNavTargetPath);return}y({type:"SELECT_ROUTE",route:{path:C.selectedNavTargetPath,layoutName:null}})}},[C.selectedNavAffordance,C.selectedNavTargetPath,d,y]),dt=u.useCallback(()=>{const W=Sb(C.selectedBaseLayout,f.selectedRoute?.layoutName);W&&y({type:"ENTER_BASE_EDIT",layoutName:W})},[C.selectedBaseLayout,f.selectedRoute?.layoutName,y]),pt=u.useCallback(()=>{const W=C.selectedNode?.__source?.extensionId;W!=null&&y({type:"ENTER_EXTENSION_EDIT",extensionId:String(W)})},[C.selectedNode,y]),ot=u.useCallback(()=>{const W=C.selectedIterationSourcePath;W&&y({type:"ENTER_ITERATION_ITEM_EDIT",sourcePath:W})},[C.selectedIterationSourcePath,y]),Oe=u.useRef(null),He=u.useRef(null),Ye=u.useRef(null),Tt=u.useRef({colorScheme:"base",breakpoint:"base"}),Dt=Oe.current!==null?x.stack.some(W=>W.id===Oe.current):!1,Nt=u.useMemo(()=>Nd(f.routeTree,h),[f.routeTree,h]),xn=u.useMemo(()=>zd(v?.document?.raw),[v?.document?.raw]),wn=u.useMemo(()=>Md(s),[s?.states]),Zt=u.useMemo(()=>{const W=v?.document?.raw,X=$f(W?.components),R=W?.initIsolated,de=R&&typeof R=="object"&&!Array.isArray(R)?Object.keys(R):[];return JI(X,de)},[v?.document?.raw]),Hn=u.useMemo(()=>{const W=v?.document?.raw;return $f(W?.components).map(X=>X.scopeId).filter(X=>typeof X=="string"&&X.length>0)},[v?.document?.raw]),ln=Dd({raw:v?.document?.raw,spec:s}),Ii=u.useCallback((W,X)=>{if(!v)return;const R={children:Me.current.components},de=We(R,W);if(!de)return;Tt.current={colorScheme:f.previewColorScheme==="dark"?"dark":"base",breakpoint:Ur(f.previewDevice,de,f.previewCustomWidth)};const ye=t?.getBoundingClientRect(),we=A&&ye?{left:ye.left+A.left,top:ye.top+A.top,width:A.width,height:A.height}:void 0,Te=re,ke=W.find(et),xe=ke?pe(ke.responsive):null,Ee=W.filter(kn=>typeof kn=="number"),Fe=ab({children:Me.current.components},Ee,lb(ln)),zt=Fe.length>0?[...ji({iterationVars:Fe}),...ln]:ln,gt=(kn,rM)=>u.createElement(kT,{key:`pem-${at(He.current??[])}`,node:kn,spec:s,manifest:Me.current.manifest,t:h,permissionCandidates:a,pageCandidates:Nt,dataSourceCandidates:xn,stateKeyCandidates:wn,bindingCandidates:zt,liveElement:Te,templateIdentifier:f.templateIdentifier,initialTab:rM,branchLabel:xe,isolatedScopeIdCandidates:Zt,usedScopeIds:Hn,onSaveInjectedProps:async(bt,Sn)=>{const Ai=typeof kn.id=="string"?kn.id:"",Fn=await OT(f.templateIdentifier,bt,Ai,Sn);if(st({op:"save",layoutName:`extension:${bt}`,editMode:f.editMode,saveTarget:"layout_extension",endpoint:`/api/admin/templates/${f.templateIdentifier}/layout-extensions/${bt}`,isDirty:!0,timestamp:Date.now()}),Fn.kind!=="success")throw new Error(Fn.kind==="conflict"?h("layout_editor.save.conflict"):Fn.kind==="injection_not_found"?"injection not found":Fn.kind==="not_found"?"extension not found":Fn.message??"save failed")},scope:Tt.current,onScopeChange:bt=>{Tt.current=bt;const Sn=Oe.current;Sn&&x.open({id:Sn,ariaLabel:h("layout_editor.property_modal.title"),width:420,draggable:!0,avoidRect:we,content:gt(kn),onClose:()=>{Oe.current=null,He.current=null}})},onPatchNode:bt=>{let Sn=[];v.patchLayout(Fn=>(Sn=Ot({children:Fn},W,()=>bt).children??[],Sn)),b.push({actionKind:"inline_text_edit",label:"edit_props",snapshot:Sn}),ir({source:"style_control",componentPath:at(W),componentName:typeof bt.name=="string"?bt.name:null,patchKey:null,timestamp:Date.now()});const Ai=Oe.current;Ai&&x.open({id:Ai,ariaLabel:h("layout_editor.property_modal.title"),width:420,draggable:!0,avoidRect:we,content:gt(bt),onClose:()=>{Oe.current=null,He.current=null}})},onDelete:()=>{const bt=Oe.current;bt&&x.close(bt),Ne()},onClose:()=>{const bt=Oe.current;bt&&x.close(bt)}});He.current=W;const Mt=x.open({ariaLabel:h("layout_editor.property_modal.title"),width:420,draggable:!0,avoidRect:we,content:gt(de,X),onClose:()=>{Oe.current=null,He.current=null,Ye.current=null}});Oe.current=Mt,Ye.current=kn=>{x.open({id:Mt,ariaLabel:h("layout_editor.property_modal.title"),width:420,draggable:!0,avoidRect:we,content:gt(kn),onClose:()=>{Oe.current=null,He.current=null,Ye.current=null}})}},[v,s,h,a,Nt,xn,wn,ln,re,b,x,Ne,t,A,f.previewColorScheme,f.previewDevice,f.previewCustomWidth,pe]);u.useEffect(()=>{const W=Ye.current,X=He.current;if(!W||!X)return;const R={children:Me.current.components},de=We(R,X);de?W(de):Oe.current&&x.close(Oe.current)},[w]);const Hz=()=>{if(!Dt)return null;const X={position:"absolute",background:"rgba(15, 23, 42, 0.45)",pointerEvents:"auto",zIndex:d7},R=ke=>{ke.preventDefault(),ke.stopPropagation()};if(!A)return i.jsx("div",{"data-testid":"g7le-edit-lock-full",onClick:R,onMouseMove:R,style:{...X,inset:0}});const{left:de,top:ye,width:we,height:Te}=A;return i.jsxs("div",{"data-testid":"g7le-edit-lock",style:{position:"absolute",inset:0,pointerEvents:"none"},children:[i.jsx("div",{"data-testid":"g7le-edit-lock-top",onClick:R,onMouseMove:R,style:{...X,left:0,top:0,right:0,height:Math.max(0,ye)}}),i.jsx("div",{"data-testid":"g7le-edit-lock-bottom",onClick:R,onMouseMove:R,style:{...X,left:0,top:ye+Te,right:0,bottom:0}}),i.jsx("div",{"data-testid":"g7le-edit-lock-left",onClick:R,onMouseMove:R,style:{...X,left:0,top:ye,width:Math.max(0,de),height:Te}}),i.jsx("div",{"data-testid":"g7le-edit-lock-right",onClick:R,onMouseMove:R,style:{...X,left:de+we,top:ye,right:0,height:Te}})]})},ml=u.useCallback(()=>{if(U&&bp(C.selectedLockKind)){if(p&&C.selectedPath){p(C.selectedPath);return}Ii(U)}},[U,C.selectedPath,C.selectedLockKind,p,Ii]),{scale:vl}=m,_l=typeof C.selectedNode?.name=="string"?C.selectedNode.name:"",Lh=s?.componentCapabilities?.[_l]??null,Ph=Array.isArray(Lh?.styleControls)?Lh.styleControls:[],Fz=Ph.includes("width")?Ct(s,"width"):null,Kz=Ph.includes("height")?Ct(s,"height"):null,Vz=u.useCallback((W,X)=>{if(!v||!U)return;let R=[];v.patchLayout(de=>(R=Ot({children:de},U,()=>W).children??[],R)),ir({source:"resize",componentPath:at(U),componentName:_l||null,patchKey:X==="height"?"height":"width",resizeAxis:X,timestamp:Date.now()})},[v,U,_l]),Uz=u.useCallback((W,X)=>{if(!v||!U)return;let R=[];v.patchLayout(de=>(R=Ot({children:de},U,()=>W).children??[],R)),b.push({actionKind:"inline_text_edit",label:`resize ${X}`,snapshot:R})},[v,U,b]),qz=u.useCallback(()=>{if(!re)return null;const W=re.getBoundingClientRect(),X=vl||1;return{width:W.width/X,height:W.height/X}},[re,vl]),rr=KT({node:C.selectedNode,widthControl:Fz,heightControl:Kz,scale:vl,measureStartSize:qz,onResize:Vz,onResizeEnd:Uz}),Gz=u.useCallback((W,X)=>{rr.onHandlePointerDown(W,X)},[rr]),xl=u.useCallback(()=>{const W=b.undo();!W||!v||v.setLayoutComponents(W.snapshot)},[b,v]),wl=u.useCallback(()=>{const W=b.redo();!W||!v||v.setLayoutComponents(W.snapshot)},[b,v]);a7({onUndo:xl,onRedo:wl});const Yz=u.useMemo(()=>({copy:oe,cut:ue,paste:J,delete:Ne,openProps:ml,selectParent:Z?se:void 0,deselect:C.clearSelection}),[oe,ue,J,Ne,ml,Z,se,C.clearSelection]);Ru({handlers:Yz,hasSelection:!!C.selectedPath}),u.useEffect(()=>(window.__g7LayoutEditorHasSelection=!!C.selectedPath,()=>{try{delete window.__g7LayoutEditorHasSelection}catch{}}),[C.selectedPath]),u.useEffect(()=>(window.__g7LayoutEditorHistory={undo:xl,redo:wl,canUndo:b.canUndo,canRedo:b.canRedo},()=>{try{delete window.__g7LayoutEditorHistory}catch{}}),[xl,wl,b.canUndo,b.canRedo]);const Xz=u.useCallback(W=>{const X=P;F(null),X&&(async()=>{if((await I.commit(X.path,W)).kind==="created"&&v){const de=v.document?.raw?.components??[];b.push({actionKind:"inline_text_edit",label:"inline_create_key",snapshot:de})}})()},[P,I,v,b]),Oh=u.useCallback(()=>{const W=P;F(null),I.trackCancel(W?.path??null)},[P,I]),Jz=u.useCallback(()=>{F(null)},[]),Zz=u.useCallback(async W=>{const X=P;if(!X)return null;const R=await I.keyifyChipValue(X.path,W);if(R.kind!=="created"||!R.translationKey)return null;const de=v?.document?.raw?.components??[];return b.push({actionKind:"inline_text_edit",label:"inline_keyify_chip",snapshot:de}),R.translationKey},[P,I,v,b]),Qz=u.useCallback(()=>{const W=P;W&&(F(null),C.handleSelect("",{dataset:{editorPath:W.domPath}}),Ii(W.path,"translation"))},[P,C,Ii]),xt=u.useMemo(()=>{if(!P)return null;const W=v?.document?.raw?.components??w;return We({children:W},P.path)},[P,v?.document,w]),Rz=u.useCallback(async(W,X)=>{const R=P;if(!v||!R)return null;const de=typeof xt?.text=="string"?xt.text:"";let ye;if(R.isParamKey)ye=await wr(f.templateIdentifier,f.locale,de,W,X.sourceId,X.path,"scalar");else{const Fe=zt=>zt.replace(/\$t:[a-zA-Z0-9._-]+/g,gt=>{const Mt=h(gt.slice(3));return Mt&&Mt!==gt.slice(3)&&!Mt.startsWith("$t:")?Mt:""}).replace(/\s+/g," ").trim();ye=await ls(f.templateIdentifier,f.selectedRoute?.layoutName??null,f.locale,de,W,X.sourceId,X.path,"scalar",Fe,h)}if(ye.kind==="error")return null;const we=R.path;let Te=[];v.patchLayout(Fe=>(Te=Ot({children:Fe},we,Mt=>({...Mt,text:ye.text})).children??[],Te)),b.push({actionKind:"inline_text_edit",label:"inline_insert_binding",snapshot:Te});const ke=ye.kind==="ok"&&"key"in ye?ye.key:void 0;!R.isParamKey&&ke&&F(Fe=>Fe&&Fe.path===we?{...Fe,isParamKey:!0,customKey:ke,chipValue:void 0,chipParamLabels:void 0}:Fe);try{window.dispatchEvent(new CustomEvent(kt,{detail:{templateIdentifier:f.templateIdentifier,locale:f.locale}}))}catch{}const xe=mt(ye.text),Ee=R.customKey??xe?.key??"";return Ee?It(Ee,f.locale)??null:null},[v,P,xt,f.templateIdentifier,f.locale,f.selectedRoute,b,h]),eM=u.useCallback(async W=>{const X=P;if(!v||!X)return null;const R=typeof xt?.text=="string"?xt.text:"",de=mt(R),ye=X.customKey??de?.key??null,we=bo(R,W),Te=X.path;let ke=[];return v.patchLayout(xe=>(ke=Ot({children:xe},Te,zt=>({...zt,text:we})).children??[],ke)),b.push({actionKind:"inline_text_edit",label:"inline_remove_binding",snapshot:ke}),ye&&await kr(f.templateIdentifier,ye,W,f.locale),ye?It(ye,f.locale)??null:null},[v,P,xt,f.templateIdentifier,f.locale,b]),[kl,Bh]=u.useState({}),tM=["fontSize","color","fontStyle","textDecoration","textAlign","letterSpacing","lineHeight","fontFamily"];u.useEffect(()=>{if(!P||!t||typeof MutationObserver>"u"){Bh({});return}const W=`[data-editor-path="${an(P.domPath)}"]`,X=()=>{const ye=t.querySelector(W);if(!ye)return;const we={};for(const ke of tM){const xe=ye.style.getPropertyValue(ke.replace(/([A-Z])/g,"-$1").toLowerCase());xe&&(we[ke]=xe)}const Te=fg(t,P.domPath)??void 0;Bh({className:ye.className,style:we,effectiveColor:Te})};X();const R=t.querySelector(W);if(!R)return;const de=new MutationObserver(X);return de.observe(R,{attributes:!0,attributeFilter:["class","style"]}),de.observe(t,{childList:!0,subtree:!0}),()=>de.disconnect()},[P?.path?at(P.path):null,t]);const Wh=u.useCallback((W,X)=>{if(!v||!P)return;const R=P.path;let de=[],ye=null;v.patchLayout(we=>(de=Ot({children:we},R,xe=>{const Ee=X(xe);return ye=typeof Ee.name=="string"?Ee.name:null,Ee}).children??[],de)),b.push({actionKind:"inline_text_edit",label:`inline_format ${W}`,snapshot:de}),ir({source:"style_control",componentPath:at(R),componentName:ye,patchKey:W,timestamp:Date.now()})},[v,P,b]),ft=u.useMemo(()=>{const W=C.selectedPath;if(!W||!_)return null;const X=[];let R=W;for(;R;){X.push(R);const de=R.match(/^(.*)\.children\.\d+$/);R=de?de[1]:null}for(const de of X){const ye=Ze(de);if(!ye)continue;const we=We(_,ye),Te=typeof we?.name=="string"?we.name:null;if(!Te)continue;const ke=Oi(s,Te),xe=ke?.canvasOverlay?.kind;if(typeof xe!="string"||!xe||!we)continue;const Ee=ke.canvasOverlay.params&&typeof ke.canvasOverlay.params=="object"?ke.canvasOverlay.params:void 0,Fe=de===W?null:W.slice(de.length+1);return{kind:xe,params:Ee,tablePath:de,tableNode:we,selectedCellRel:Fe}}return null},[C.selectedPath,_,s]),ho=ft?BT(ft.kind):null,jh=u.useMemo(()=>!ho||!t||!ft?null:po(t,ft.tablePath),[ho,t,ft,A,w]),nM=u.useMemo(()=>{if(!ho||!t||!ft)return[];const W=ft.tablePath,X=an(W),R=[];return t.querySelectorAll(`[data-editor-path^="${X}.children."]`).forEach(we=>{const Te=we.dataset.editorPath??"";if(!Te.startsWith(W+"."))return;const ke=Te.slice(W.length+1),xe=so(we,t);xe&&R.push({path:ke,top:xe.top,left:xe.left,width:xe.width,height:xe.height})}),t.querySelectorAll(`[data-editor-item-path^="${X}."]`).forEach(we=>{const Te=we.dataset.editorItemPath??"";if(!Te.startsWith(W+"."))return;const ke=Te.slice(W.length+1),xe=so(we,t);xe&&R.push({path:ke,top:xe.top,left:xe.left,width:xe.width,height:xe.height})}),R},[ho,t,ft,A,w]),oM=u.useCallback(W=>{const X=ft?Ze(ft.tablePath):null;if(!v||!X)return;let R=[];v.patchLayout(de=>(R=Ot({children:de},X,()=>W).children??[],R)),b.push({actionKind:"inline_text_edit",label:"inplace_edit",snapshot:R}),ir({source:"style_control",componentPath:ft?.tablePath??"",componentName:typeof W.name=="string"?W.name:null,patchKey:"canvas_inplace",timestamp:Date.now()})},[v,U,b]);return t?i.jsxs("div",{className:"g7le-editor-canvas-overlay","data-testid":"g7le-editor-canvas-overlay",style:{position:"absolute",inset:0,pointerEvents:"none"},children:[!D&&Hz(),D&&i.jsxs("div",{"data-testid":"g7le-canvas-pick-banner",style:{position:"absolute",top:8,left:"50%",transform:"translateX(-50%)",zIndex:9999,display:"flex",alignItems:"center",gap:12,padding:"8px 14px",background:"#1e293b",color:"#fff",borderRadius:8,fontSize:13,boxShadow:"0 4px 12px rgba(0,0,0,0.25)",pointerEvents:"auto"},children:[i.jsxs("span",{children:["🎯 ",h("layout_editor.target_picker.canvas_pick_hint")]}),i.jsx("button",{type:"button","data-testid":"g7le-canvas-pick-cancel",onClick:()=>Y(D,null),style:{border:"1px solid #475569",borderRadius:6,background:"transparent",color:"#cbd5e1",cursor:"pointer",fontSize:12,padding:"3px 10px"},children:h("layout_editor.target_picker.cancel")})]}),f.editMode!=="route"&&i.jsx(kI,{frameEl:t,components:w,editMode:f.editMode,currentExtensionId:S,editableRootPath:E}),P&&((P.isParamKey&&P.customKey||P.chipValue)&&xt?i.jsxs(i.Fragment,{children:[xt&&i.jsx(cg,{node:xt,spec:s,t:h,onApplyControl:Wh,box:P.box,scope:{colorScheme:f.previewColorScheme==="dark"?"dark":"base",breakpoint:Ur(f.previewDevice,xt,f.previewCustomWidth)}}),i.jsx(t4,{box:P.box,node:xt,customKey:P.customKey??null,initialChipValue:P.chipValue,chipParamLabels:P.chipParamLabels,onKeyify:Zz,templateIdentifier:f.templateIdentifier,locale:f.locale,t:h,candidates:ln,onInsertBinding:Rz,onRemoveBinding:eM,onCommit:Jz,onCancel:Oh})]}):i.jsxs(i.Fragment,{children:[xt&&i.jsx(cg,{node:xt,spec:s,t:h,onApplyControl:Wh,box:P.box,scope:{colorScheme:f.previewColorScheme==="dark"?"dark":"base",breakpoint:xt?Ur(f.previewDevice,xt,f.previewCustomWidth):"base"}}),i.jsx(e4,{box:P.box,initialValue:P.initialValue,isCustomKey:P.isCustomKey,t:h,onCommit:Xz,onCancel:Oh,mirrorClassName:kl.className,mirrorStyle:kl.style,nodeEffectiveColor:kl.effectiveColor??P.nodeEffectiveColor,onOpenTranslations:Qz})]})),!D&&i.jsx(h7,{hoverBox:N,selectedBox:A,lockKind:C.selectedLockKind,navAffordance:C.selectedNavAffordance,onEditProps:ml,onDuplicate:Ae,onDelete:Ne,onSeparateBranch:Le?.mode==="separate"?q:void 0,separateBranchLabel:$e?.separate,onMergeBranch:Le?.mode==="merge"?ae:void 0,mergeBranchLabel:$e?.merge,definedDeviceBranches:be,onJumpToDevice:be.length>0?j:void 0,onLinkEditDestination:Ie,onEditBase:dt,onEditExtension:pt,extensionLabel:ze,baseLayoutLabel:C.selectedBaseLayout,dataSourceLabel:C.selectedDataSourceId,branchLabel:ee,onEditIteration:C.selectedIsIteration&&f.editMode!=="iteration_item"?ot:void 0,resizeEnabledAxes:rr.enabledAxes,onResizeHandlePointerDown:rr.enabledAxes.width||rr.enabledAxes.height?Gz:void 0,selectedName:Ce,onSelectParent:Z?se:void 0}),D&&B&&i.jsx("div",{"data-testid":"g7le-canvas-pick-hover","data-pick-has-id":B.hasId?"true":"false",style:{position:"absolute",left:B.box.left,top:B.box.top,width:B.box.width,height:B.box.height,pointerEvents:"none",zIndex:9998,boxSizing:"border-box",border:B.hasId?"2px solid #2563eb":"2px dashed #94a3b8",background:B.hasId?"rgba(37,99,235,0.10)":"repeating-linear-gradient(45deg, rgba(148,163,184,0.18) 0, rgba(148,163,184,0.18) 6px, transparent 6px, transparent 12px)",cursor:B.hasId?"pointer":"not-allowed"},children:!B.hasId&&i.jsx("span",{"data-testid":"g7le-canvas-pick-hover-hint",style:{position:"absolute",top:0,left:0,transform:"translateY(-100%)",background:"#475569",color:"#fff",fontSize:11,lineHeight:1.4,padding:"2px 6px",borderRadius:4,whiteSpace:"nowrap"},children:h("layout_editor.target_picker.needs_id")})}),!D&&i.jsx(x7,{selectedBox:qe,points:Se.points,onAddRequest:Re}),ho&&ft&&jh&&C.selectedLockKind==="none"&&i.jsx(ho,{node:ft.tableNode,params:ft.params,nodeBox:jh,cellBoxes:nM,selectedCellPath:ft.selectedCellRel??void 0,colorScheme:f.previewColorScheme==="dark"?"dark":"light",t:h,onPatchNode:oM,onInsertChild:ge,onRemoveChild:W=>{const X=Ze(W);if(!v||!X)return;let R=[];v.patchLayout(de=>(R=Ri({children:de},X).children??[],R)),b.push({actionKind:"remove",label:"inplace_remove",snapshot:R})},onRequestInlineEdit:W=>{ft&&G(`${ft.tablePath}.${W}`)}}),v&&i.jsx(bI,{frameEl:t,nesting:o,editMode:f.editMode,currentExtensionId:S,editableRootPath:E,components:w,patchLayout:v.patchLayout,pushHistory:le,selectedPath:C.selectedPath,onSelectPath:W=>C.handleSelect("",{dataset:{editorPath:W}}),onMovePath:W=>C.handleSelect("",{dataset:{editorPath:W}}),onRequestInlineEdit:G})]}):null}function pg(e,t){if(t.length===0)return null;const o=Ha({children:e},t);return o&&typeof o.name=="string"?o.name:null}function Ha(e,t){return We(e,t)}function an(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/[^a-zA-Z0-9_\-.]/g,t=>`\\${t}`)}function fg(e,t){if(!t)return null;const n=e.querySelector(`[data-editor-path="${an(t)}"]`);if(!n||typeof window.getComputedStyle!="function")return null;let o=n;const r=n.ownerDocument.createTreeWalker(n,NodeFilter.SHOW_TEXT);let s=r.nextNode();for(;s;){if((s.textContent??"").trim().length>0){const a=s.parentElement;if(a&&n.contains(a)){o=a;break}}s=r.nextNode()}try{return window.getComputedStyle(o).color||null}catch{return null}}function po(e,t){if(!t)return null;const n=e.querySelector(`[data-editor-path="${an(t)}"]`);if(n){const c=so(n,e);return c&&ao(c,e)?c:null}const o=e.querySelectorAll(`[data-editor-path^="${an(t)}.iteration."]`);let r=1/0,s=1/0,a=-1/0,l=-1/0,d=!1;return o.forEach(c=>{const p=c.dataset.editorPath??"";if(!new RegExp("\\.iteration\\.\\d+$").test(p))return;const f=so(c,e);f&&ao(f,e)&&(d=!0,r=Math.min(r,f.left),s=Math.min(s,f.top),a=Math.max(a,f.left+f.width),l=Math.max(l,f.top+f.height))}),d?{left:r,top:s,width:a-r,height:l-s,scale:1}:null}function d4({isEditMode:e,editorSpec:t,sampleOverride:n}){const o=t?.sampleData;return u.useMemo(()=>zm({spec:o,overrideSpec:n,onMatch:r=>{Fh(r)}}),[e,o,n])}const c4=Lt().ComponentRegistry;function u4(e){return e.split(/[-_]/).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")}async function p4(e){const t=typeof window<"u"?window.localStorage?.getItem("auth_token"):null,n={Accept:"application/json"};t&&(n.Authorization=`Bearer ${t}`);const o=await fetch(`/api/admin/templates/${encodeURIComponent(e)}/editor-assets`,{headers:n,credentials:"same-origin"});if(!o.ok){const s=await o.json().catch(()=>null);throw Gr(o.status,s,"assets")}const r=await o.json();return r.data||r}async function f4(e){try{if(typeof fetch!="function")return 0;const t=await fetch(en(`/api/templates/${encodeURIComponent(e)}/config`,"json"),{credentials:"same-origin",headers:{Accept:"application/json"}});if(!t.ok)return 0;const n=await t.json().catch(()=>null),o=n?.data?.cache_version??n?.cache_version;return typeof o=="number"&&o>0?o:0}catch{return 0}}function g4(e){return new Promise((t,n)=>{if(typeof document>"u"){n(new Error("document undefined"));return}if(document.querySelector(`script[data-g7le-asset="${e}"]`)){t();return}const r=document.createElement("script");r.src=e,r.async=!1,r.setAttribute("data-g7le-asset",e),r.addEventListener("load",()=>t()),r.addEventListener("error",()=>n(new Error(`script load failed: ${e}`))),document.head.appendChild(r)})}async function h4(e){if(typeof document>"u")return;const t=`[data-g7le-asset="${e}"]`;if(document.querySelector(`link${t}, style${t}`))return;if(e.includes("/api/admin/"))try{const r=typeof window<"u"?window.localStorage?.getItem("auth_token"):null,s={Accept:"text/css"};r&&(s.Authorization=`Bearer ${r}`);const a=await fetch(e,{headers:s,credentials:"same-origin"});if(a.ok){const l=await a.text(),d=document.createElement("style");d.textContent=l,d.setAttribute("data-g7le-asset",e),document.head.appendChild(d);return}}catch{}const o=document.createElement("link");o.rel="stylesheet",o.href=e,o.setAttribute("data-g7le-asset",e),document.head.appendChild(o)}function y4(e,t,n="user"){const[o,r]=u.useState({componentRegistry:null,translationEngine:null,isReady:!1,error:null});return u.useEffect(()=>{let s=!1;return(async()=>{r(a=>({...a,isReady:!1,error:null}));try{const a=await p4(e);if(s)return;for(const y of a.css??[])if(await h4(y),s)return;const l=u4(e);if(!(typeof window<"u"&&typeof window[l]=="object")){for(const y of a.js??[])if(await g4(y),s)return}const c=c4.createIsolatedInstance();if(await c.loadComponents(e,n),s)return;const p=await f4(e);if(s)return;const f=new Pt({defaultLocale:t});if(p>0&&f.setCacheVersion(p),await f.loadTranslations(e,t),s)return;cd(f,e);try{const y=Pt.getInstance();p>y.getCacheVersion()&&y.setCacheVersion(p),await y.loadTranslations(e,t),cd(y,e)}catch{}if(s)return;r({componentRegistry:c,translationEngine:f,isReady:!0,error:null})}catch(a){if(s)return;const l=pp(a)?a:io(a,"assets");r({componentRegistry:null,translationEngine:null,isReady:!1,error:l})}})(),()=>{s=!0}},[e,t,n]),o}const gg=Lt().AuthManager;function b4(e){switch(e){case"unauthorized":return{icon:"🔒",tone:"blue",titleKey:"layout_editor.access_error.unauthorized.title",messageKey:"layout_editor.access_error.unauthorized.message",showRequiredPermissions:!0};case"forbidden":return{icon:"⛔",tone:"rose",titleKey:"layout_editor.access_error.forbidden.title",messageKey:"layout_editor.access_error.forbidden.message",showRequiredPermissions:!0};case"not_found":return{icon:"🗂️",tone:"slate",titleKey:"layout_editor.access_error.not_found.title",messageKey:"layout_editor.access_error.not_found.message",showRequiredPermissions:!1};case"server_error":return{icon:"🛠️",tone:"amber",titleKey:"layout_editor.access_error.server_error.title",messageKey:"layout_editor.access_error.server_error.message",showRequiredPermissions:!1};case"network":return{icon:"📡",tone:"amber",titleKey:"layout_editor.access_error.network.title",messageKey:"layout_editor.access_error.network.message",showRequiredPermissions:!1};default:return{icon:"⚠️",tone:"slate",titleKey:"layout_editor.access_error.unknown.title",messageKey:"layout_editor.access_error.unknown.message",showRequiredPermissions:!1}}}const m4={blue:{bg:"#eff6ff",border:"#bfdbfe",iconBg:"#dbeafe"},rose:{bg:"#fff1f2",border:"#fecdd3",iconBg:"#ffe4e6"},amber:{bg:"#fffbeb",border:"#fde68a",iconBg:"#fef3c7"},slate:{bg:"#f8fafc",border:"#e2e8f0",iconBg:"#f1f5f9"}};function v4({error:e}){return u.useEffect(()=>{if(e.kind!=="unauthorized"||typeof window>"u")return;const t=gg.getInstance(),n=`${window.location.pathname}${window.location.search}`,o=t.getLoginRedirectUrl("admin",n,"session_expired"),r=window.setTimeout(()=>{window.location.href=o},600);return()=>window.clearTimeout(r)},[e.kind]),null}function Fa({error:e}){const{t}=tt(),n=b4(e.kind),o=m4[n.tone],r=()=>{typeof window<"u"&&(window.location.href="/admin")},s=()=>{typeof window<"u"&&window.location.reload()},a=()=>{if(typeof window>"u")return;const l=gg.getInstance(),d=`${window.location.pathname}${window.location.search}`;window.location.href=l.getLoginRedirectUrl("admin",d)};return i.jsxs("div",{className:"g7le-access-error","data-testid":"g7le-access-error","data-error-kind":e.kind,style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"#f1f5f9"},children:[i.jsx(v4,{error:e}),i.jsxs("div",{style:{maxWidth:480,width:"100%",background:o.bg,border:`1px solid ${o.border}`,borderRadius:12,padding:"28px 32px",boxShadow:"0 2px 8px rgba(15, 23, 42, 0.05)",textAlign:"center"},children:[i.jsx("div",{style:{width:64,height:64,margin:"0 auto 16px",borderRadius:"50%",background:o.iconBg,display:"flex",alignItems:"center",justifyContent:"center",fontSize:32,lineHeight:1},"aria-hidden":"true",children:n.icon}),i.jsx("h2",{"data-testid":"g7le-access-error-title",style:{margin:"0 0 8px",fontSize:18,fontWeight:700,color:"#0f172a"},children:t(n.titleKey)}),i.jsx("p",{"data-testid":"g7le-access-error-message",style:{margin:"0 0 16px",fontSize:13,lineHeight:1.6,color:"#475569"},children:t(n.messageKey)}),n.showRequiredPermissions&&e.requiredPermissions&&i.jsxs("div",{"data-testid":"g7le-access-error-permissions",style:{display:"inline-flex",flexWrap:"wrap",gap:6,justifyContent:"center",padding:"8px 12px",marginBottom:16,background:"rgba(15, 23, 42, 0.04)",borderRadius:8,fontSize:12,color:"#475569"},children:[i.jsx("span",{style:{fontWeight:600},children:t("layout_editor.access_error.required_permission_label")}),e.requiredPermissions.split(/[,\s]+/).filter(Boolean).map(l=>i.jsx("code",{style:{padding:"2px 6px",background:"#fff",border:"1px solid #e2e8f0",borderRadius:4,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace",fontSize:11,color:"#1e293b"},children:l},l))]}),e.message&&i.jsxs("details",{"data-testid":"g7le-access-error-detail",style:{marginBottom:16,fontSize:11,color:"#94a3b8"},children:[i.jsx("summary",{style:{cursor:"pointer"},children:t("layout_editor.access_error.detail_summary")}),i.jsxs("pre",{style:{marginTop:8,padding:8,background:"#fff",border:"1px solid #e2e8f0",borderRadius:6,overflowX:"auto",whiteSpace:"pre-wrap",wordBreak:"break-word",textAlign:"left",fontSize:11,color:"#475569"},children:[e.status>0?`HTTP ${e.status} `:"",e.message]})]}),i.jsxs("div",{style:{display:"flex",justifyContent:"center",gap:8,flexWrap:"wrap"},children:[e.kind==="unauthorized"&&i.jsx("button",{type:"button","data-testid":"g7le-access-error-action-signin",onClick:a,style:Ka,children:t("layout_editor.access_error.action.sign_in")}),e.kind==="forbidden"&&i.jsx("button",{type:"button","data-testid":"g7le-access-error-action-home",onClick:r,style:Ka,children:t("layout_editor.access_error.action.go_home")}),(e.kind==="not_found"||e.kind==="server_error"||e.kind==="network"||e.kind==="unknown")&&i.jsx("button",{type:"button","data-testid":"g7le-access-error-action-retry",onClick:s,style:Ka,children:t("layout_editor.access_error.action.retry")}),e.kind!=="unauthorized"&&i.jsx("button",{type:"button","data-testid":"g7le-access-error-action-home-secondary",onClick:r,style:_4,children:t("layout_editor.access_error.action.go_admin_home")})]})]})]})}const Ka={padding:"8px 16px",background:"#2563eb",color:"#fff",border:"1px solid #1d4ed8",borderRadius:6,fontSize:13,fontWeight:600,cursor:"pointer"},_4={padding:"8px 16px",background:"#fff",color:"#475569",border:"1px solid #cbd5e1",borderRadius:6,fontSize:13,fontWeight:500,cursor:"pointer"};function x4(e){const t=window;if(typeof t>"u")return{getSnapshot:()=>({globalState:{},localState:{}}),restore:()=>{}};const n=t.G7Core||{},o={templateApp:t.__templateApp,g7CoreState:n.state,g7CoreDispatch:n.dispatch,g7CoreData:n.data,g7CoreModal:n.modal,g7CoreToast:n.toast};let r={...e.initialGlobalState??{}};r._local||(r._local={});const s=[],a=()=>{const c={globalState:{...r},localState:{...r._local??{}}};for(const p of s)try{p(r)}catch{}e.onChange?.(c)},l={},d={getGlobalState:()=>r,setGlobalState:(c,p)=>{typeof c=="function"?r=c(r):r={...r,...c},a()},onGlobalStateChange:c=>(s.push(c),()=>{const p=s.indexOf(c);p>=0&&s.splice(p,1)}),get globalState(){return r},getActionDispatcher:()=>e.actionDispatcher,getDataSource:c=>l[c]??null,setDataSource:(c,p)=>{l[c]=p},refetchDataSource:async c=>null,updateDataSourceItem:(c,p,f)=>l[c]??null,getLocale:()=>e.locale,changeLocale:c=>{},getRouter:()=>({navigate:()=>{},replace:()=>{},push:()=>{}}),updateQueryParams:()=>{}};return t.__templateApp=d,n&&typeof n.dispatch=="function"&&(n.dispatch=(c,p)=>{try{return e.actionDispatcher.executeAction(c,p??{})}catch{return}}),n&&typeof n.modal=="object"&&n.modal!==null&&(n.modal={...n.modal,open:()=>{},close:()=>{},closeAll:()=>{}}),n&&typeof n.toast=="object"&&n.toast!==null&&(n.toast={...n.toast,push:()=>{},dismiss:()=>{}}),{getSnapshot:()=>({globalState:{...r},localState:{...r._local??{}}}),restore:()=>{t.__templateApp===d&&(t.__templateApp=o.templateApp),t.G7Core&&(o.g7CoreState!==void 0&&(t.G7Core.state=o.g7CoreState),o.g7CoreDispatch!==void 0&&(t.G7Core.dispatch=o.g7CoreDispatch),o.g7CoreData!==void 0&&(t.G7Core.data=o.g7CoreData),o.g7CoreModal!==void 0&&(t.G7Core.modal=o.g7CoreModal),o.g7CoreToast!==void 0&&(t.G7Core.toast=o.g7CoreToast)),s.length=0}}}const w4=new Set(["id","userId","postId","orderId","productId","categoryId","commentId","noticeId","inquiryId","addressId","wishlistId","notificationId","roleId","menuId"]);function k4(e){if(!e)return{};const t={},n=/:([a-zA-Z_][a-zA-Z0-9_]*)/g;let o;for(;(o=n.exec(e))!==null;){const r=o[1];t[r]=S4(r)}return t}function S4(e){return w4.has(e)||/Id$|_id$/.test(e)?"1":"sample"}const C4=dr("LayoutEditor");function Xo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function bi(e){if(Array.isArray(e))return e.map(t=>bi(t));if(Xo(e)){const t={};for(const[n,o]of Object.entries(e))t[n]=bi(o);return t}return e}function hg(e,t="",n=new Set){for(const[o,r]of Object.entries(e)){const s=t?`${t}.${o}`:o;Xo(r)?hg(r,s,n):n.add(s)}return n}function yg(e,t,n,o,r,s=""){for(const[a,l]of Object.entries(t)){const d=s?`${s}.${a}`:a;if(n.has(d)){r(`[LayoutEditor] sampleGlobal key conflict: extension '${o}' override of core key '${d}' ignored`);continue}const c=e[a];Xo(l)&&Xo(c)?yg(c,l,n,o,r,d):e[a]=bi(l)}}function Va(e){const t=e.warn??(r=>C4.warn(r)),n=bi(e.coreSeed??{});e.isGuestOnly&&"currentUser"in n&&delete n.currentUser;const o=hg(n);for(const r of e.sources)Xo(r.sampleGlobal)&&yg(n,r.sampleGlobal,o,r.id,t);return e.isGuestOnly&&"currentUser"in n&&delete n.currentUser,n}function $4(e){const t={};if(!e||typeof e!="object"||Array.isArray(e))return t;for(const[n,o]of Object.entries(e))n.startsWith("$")&&(t[n]=o);return t}function E4(e){const t={};if(!e||typeof e!="object"||Array.isArray(e))return t;for(const[n,o]of Object.entries(e))n.startsWith("$")||(t[n]=o);return t}function I4(e){if(typeof e!="string")return null;const t=/^\s*\{\{\s*([\s\S]*?)\s*\}\}\s*$/.exec(e);if(!t)return null;let n=t[1];const o=n.indexOf("??");return o>=0&&(n=n.slice(0,o)),n=n.replace(/\?\./g,".").replace(/\s+/g,""),n===""||!/^[A-Za-z_$][A-Za-z0-9_$]*(\.[A-Za-z_$][A-Za-z0-9_$]*)*$/.test(n)?null:n.split(".")}function A4(e,t){const n=I4(t);if(!n||n.length===0)return e;let o=e;for(let a=0;ao.map(r=>{if(!r||typeof r!="object")return r;const s=r;let a=s;if(typeof s.slot=="string"&&!t.has(s.slot)){const{slot:l,...d}=s;a={...d,__editorSlotName:l}}if(Array.isArray(a.children)){const l=n(a.children);l!==a.children&&(a={...a,children:l})}return a});return n(e)}function St(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Xt(e){if(Array.isArray(e))return e.map(t=>Xt(t));if(St(e)){const t={};for(const[n,o]of Object.entries(e))t[n]=Xt(o);return t}return e}function mi(e,t){for(const[n,o]of Object.entries(t)){const r=e[n];St(o)&&St(r)?mi(r,o):e[n]=Xt(o)}}function N4(e){const t=[];let n="";for(let o=0;o0&&(t.push(n),n="");const s=e[o+1];if(s==="'"||s==='"'){const l=e.indexOf(`${s}]`,o+2);if(l!==-1){t.push(e.slice(o+2,l)),o=l+1;continue}}const a=e.indexOf("]",o+1);if(a!==-1){t.push(e.slice(o+1,a)),o=a;continue}n+=r}else r==="."?n.length>0&&(t.push(n),n=""):n+=r}return n.length>0&&t.push(n),t.filter(o=>o.length>0)}function Ua(e,t,n){const o=N4(t);if(o.length===0)return;let r=e;for(let s=0;s0?t:void 0}const Ga="g7le:editor-t-ready",vg="data-g7le-vh-expanded";function M4(e,t){if(!e||!t)return;const n=t;e.querySelectorAll("*").forEach(r=>{const s=window.getComputedStyle(r),a=parseFloat(s.height),l=Number.isFinite(a)&&Math.abs(a-n)<=2,d=parseFloat(s.minHeight),c=Number.isFinite(d)&&Math.abs(d-n)<=2,p=s.overflowY==="auto"||s.overflowY==="scroll"||s.overflowY==="hidden"||s.overflow==="auto"||s.overflow==="scroll"||s.overflow==="hidden";l&&p?(r.style.setProperty("height","auto","important"),c&&r.style.setProperty("min-height","0","important"),r.style.setProperty("overflow","visible","important"),r.setAttribute(vg,"1")):(s.overflowY==="auto"||s.overflowY==="scroll")&&r.scrollHeight>r.clientHeight+4&&r.clientHeight>120&&(r.style.setProperty("overflow","visible","important"),r.style.setProperty("height","auto","important"),r.setAttribute(vg,"1"))})}const L4=[];function P4(e={}){const{manifest:t=null,nesting:n=null,componentPalette:o=null,spec:r=null,permissionCandidates:s,sampleGlobalSources:a=L4,resolveRouteMatch:l,onNavigateToDestination:d,onSessionAddedPathsChange:c}=e,{state:p}=Je(),f=Ft(),y=wp(),{document:g,isLoading:m,error:h}=f??y,v=u.useRef(null),[b,x]=u.useState(null),{deviceWidth:k,scale:w,colorScheme:_}=ja(),S=u.useMemo(()=>p.activeStateId?p.availableStates.find(Q=>Q.id===p.activeStateId)??null:null,[p.activeStateId,p.availableStates]),E=u.useMemo(()=>mg(S),[S]),C=d4({isEditMode:!0,editorSpec:r??void 0,sampleOverride:E}),{t:N}=tt(),{componentRegistry:$,translationEngine:A,isReady:z,error:D}=y4(p.templateIdentifier,p.locale),O=u.useRef(null);O.current===null&&(O.current=new vd);const M=u.useRef(null);if(M.current===null){M.current=new jE({navigate:()=>{}}),M.current.setPreviewMode(!0);try{const ie=window.__templateApp?.getActionDispatcher?.();if(ie&&typeof ie.getRegisteredHandlers=="function"){const _e=ie.getRegisteredHandlers();for(const ge of _e){if(!ge.includes("."))continue;const Ae=typeof ie.getHandler=="function"?ie.getHandler(ge):void 0;typeof Ae=="function"&&M.current.registerHandler(ge,Ae,{category:"plugin",source:"preview-canvas-cloned-from-host"})}}}catch{}}u.useEffect(()=>{if(!z)return;const Q=M.current;if(Q)try{const ie=window.G7Core?.getActionDispatcher?.();if(!ie||typeof ie.getRegisteredHandlers!="function")return;const _e=ie.getRegisteredHandlers();for(const ge of _e){if(!ge.includes(".")||typeof Q.getHandler=="function"&&Q.getHandler(ge))continue;const Ae=typeof ie.getHandler=="function"?ie.getHandler(ge):void 0;typeof Ae=="function"&&Q.registerHandler(ge,Ae,{category:"plugin",source:"preview-canvas-iife-reclone"})}}catch{}},[z]);const B=u.useMemo(()=>new HE({sampleProvider:C,actionDispatcher:M.current}),[C]),T=u.useMemo(()=>g?.raw?.meta?.guest_only===!0,[g]),H=u.useMemo(()=>Va({sources:a,isGuestOnly:T}),[a,T]),L=u.useMemo(()=>{const Q=O4(qa(S),A,{templateId:p.templateIdentifier,locale:p.locale}),ie=H._local,{global:_e,local:ge}=z4({globalBaseline:H,localBaseline:ie??{},patch:S?.initialState??null,formErrors:Q});return{..._e,_local:ge}},[H,S,A,p.templateIdentifier,p.locale]),I=u.useMemo(()=>!S||!(!!S.initialState?.local||!!qa(S))?null:{...L._local??{},_forceLocalInit:S.id,_merge:"deep"},[S,L]),P=Q=>typeof Q=="object"&&Q!==null&&!Array.isArray(Q),F=u.useMemo(()=>P(S?.initialState?.query)?S.initialState.query:null,[S]),G=u.useMemo(()=>P(S?.initialState?.route)?S.initialState.route:null,[S]),[V,Y]=u.useState(()=>Va({sources:[],isGuestOnly:!1})),Z=u.useRef(null);u.useEffect(()=>{const Q={...L},ie=x4({actionDispatcher:M.current,locale:p.locale,initialGlobalState:Q,onChange:ge=>{Y(ge.globalState)}});Z.current=ie;const _e=window.__templateApp;return _e?.setGlobalState&&M.current.setGlobalStateUpdater((ge,Ae)=>{_e.setGlobalState(ge,Ae)}),Y(Q),$l({kind:"applyPatch",activeStateId:p.activeStateId,routePath:p.selectedRoute?.path??null,hasInitialPatch:!!S?.initialState,hasFormErrors:!!qa(S),hasSampleOverride:!!mg(S)}),()=>{ie.restore(),Z.current=null}},[p.locale,L]),u.useEffect(()=>{if(!A)return;const Q=window.G7Core;if(!Q||typeof Q.t!="function")return;const ie=Q.t,_e=p.templateIdentifier,ge=p.locale;return Q.t=(Ae,Ne)=>{try{const Le=Ne?"|"+Object.entries(Ne).map(([ae,pe])=>`${ae}=${pe}`).join("|"):void 0,q=A.translate(Ae,{templateId:_e,locale:ge},Le);if(q!==Ae&&!q.startsWith("$t:"))return q}catch{}return ie(Ae,Ne)},typeof window<"u"&&window.dispatchEvent(new CustomEvent(Ga)),()=>{window.G7Core?.t&&window.G7Core.t!==ie&&(window.G7Core.t=ie)}},[A,p.templateIdentifier,p.locale]);const se=u.useMemo(()=>{const Q=g?.raw?.components??[];return p.editMode!=="base"?Q:D4(Q)},[g,p.editMode]),re=g?.raw?.__editability,U=g?.raw?.__extensionId,ee=u.useMemo(()=>p.editMode!=="extension"||re!=="ok"?[]:typeof U!="number"?[]:B4(se,U),[p.editMode,re,U,se]),[fe,K]=u.useState(null),[ne,me]=u.useState(!1),Ce=g?.layoutName??null,ze=u.useMemo(()=>{const Q=g?.raw?.scripts??[];return Array.isArray(Q)?Q.map(ie=>ie&&typeof ie.src=="string"?ie.src:"").join("|"):""},[g]);u.useEffect(()=>{me(!1)},[Ce,ze]),u.useEffect(()=>{let Q=!1;const ie=g?.raw?.scripts??[];if(!Array.isArray(ie)||ie.length===0){me(!0);return}const _e=[];for(const ge of ie){if(!ge?.src||typeof ge.src!="string")continue;const Ae=ge.id?`script#${CSS.escape(ge.id)}, script[data-g7le-canvas-script="${ge.src}"]`:`script[data-g7le-canvas-script="${ge.src}"], script[src="${ge.src}"]`,Ne=window.document.querySelector(Ae);if(Ne){const Le=Ne.hasAttribute("data-g7le-canvas-script");if(Ne.hasAttribute("data-g7le-script-loaded")||!Le)continue;_e.push(new Promise(ae=>{if(Ne.hasAttribute("data-g7le-script-loaded")){ae();return}Ne.addEventListener("load",()=>ae()),Ne.addEventListener("error",()=>ae())}));continue}_e.push(new Promise(Le=>{const q=window.document.createElement("script");q.src=ge.src,q.async=!1,ge.id&&(q.id=ge.id),q.setAttribute("data-g7le-canvas-script",ge.src);const ae=()=>{q.setAttribute("data-g7le-script-loaded","1"),Le()};q.addEventListener("load",ae),q.addEventListener("error",ae),window.document.head.appendChild(q)}))}if(_e.length===0){me(!0);return}return Promise.all(_e).then(()=>{Q||requestAnimationFrame(()=>{requestAnimationFrame(()=>{Q||me(!0)})})}),()=>{Q=!0}},[g]);const Se=u.useMemo(()=>g?.raw?.data_sources??[],[g]),qe=u.useMemo(()=>g?.raw?.computed??{},[g]),[De,Pe]=u.useState({}),Qe=u.useMemo(()=>{if(p.editMode!=="iteration_item")return De;const Q=g?.iterationContext;if(!Q)return De;const ie=g?.raw?.components??[],_e=We({children:ie},Q.sourceIndexPath),ge=_e&&_e.iteration&&typeof _e.iteration.source=="string"?_e.iteration.source:null;return ge?A4(De,ge):De},[p.editMode,De,g]),[Me,Re]=u.useState(0);u.useEffect(()=>{if(typeof window>"u")return;const Q=()=>Re(ie=>ie+1);return window.addEventListener(kt,Q),()=>window.removeEventListener(kt,Q)},[]);const ve=u.useMemo(()=>k4(p.selectedRoute?.path??null),[p.selectedRoute?.path]);if(u.useEffect(()=>{let Q=!1;return(async()=>{if(Se.length===0){Q||Pe({});return}try{const ie=await B.fetchDataSources(Se,ve,new URLSearchParams,void 0,void 0);Q||Pe(ie)}catch{Q||Pe({})}})(),()=>{Q=!0}},[Se,B,ve]),u.useEffect(()=>{const Q=b;if(!Q||typeof window>"u")return;let ie=0,_e=0,ge=0;const Ae=()=>M4(Q,window.innerHeight);ie=window.requestAnimationFrame(()=>{_e=window.requestAnimationFrame(Ae)});let Ne=null;return typeof MutationObserver<"u"&&(Ne=new MutationObserver(()=>{ge||(ge=window.requestAnimationFrame(()=>{ge=0,Ae()}))}),Ne.observe(Q,{childList:!0,subtree:!0})),()=>{window.cancelAnimationFrame(ie),window.cancelAnimationFrame(_e),ge&&window.cancelAnimationFrame(ge),Ne&&Ne.disconnect()}},[b,se,ne,k,De]),u.useEffect(()=>{const Q=b;if(!Q||typeof window>"u"||p.editMode!=="extension"||re!=="ok"||ee.length===0){K(null);return}let ie=0,_e=0;const ge=ae=>{if(!ae)return!1;const pe=ae.getBoundingClientRect();return pe.width>0&&pe.height>0},Ae=ae=>{const pe=Q.querySelector(`[data-editor-path="${ae}"]`);if(ge(pe))return!0;const $e=Q.querySelectorAll(`[data-editor-path^="${ae}.children."]`);for(const be of Array.from($e))if(ge(be))return!0;return!1},Ne=()=>{K(ee.some(Ae))};ie=window.requestAnimationFrame(()=>{_e=window.requestAnimationFrame(Ne)});let Le=null,q=0;return typeof MutationObserver<"u"&&(Le=new MutationObserver(()=>{q||(q=window.requestAnimationFrame(()=>{q=0,Ne()}))}),Le.observe(Q,{childList:!0,subtree:!0})),()=>{window.cancelAnimationFrame(ie),window.cancelAnimationFrame(_e),q&&window.cancelAnimationFrame(q),Le&&Le.disconnect()}},[b,p.editMode,re,ee,ne,De]),u.useEffect(()=>{if(typeof window>"u"||p.editMode!=="base")return;const Q=window.document,ie="g7le-base-slot-style";if(Q.getElementById(ie))return;const _e=Q.createElement("style");_e.id=ie;const ge=N("layout_editor.preview.slot_area_label");return _e.textContent=`.g7le-preview-frame [data-editor-slot]{position:relative;min-height:96px;outline:2px dashed #94a3b8;outline-offset:-2px;}.g7le-preview-frame [data-editor-slot]::after{content:'${ge.replace(/'/g,"\\'")} · ' attr(data-editor-slot);position:absolute;top:8px;left:50%;transform:translateX(-50%);font-size:12px;line-height:1;color:#64748b;background:rgba(241,245,249,0.92);border:1px solid #cbd5e1;border-radius:9999px;padding:4px 12px;pointer-events:none;white-space:nowrap;}`,Q.head.appendChild(_e),()=>{Q.getElementById(ie)?.remove()}},[p.editMode,N]),!(p.editMode==="extension"||p.editMode==="iteration_item")&&(p.selectedRoute?.layoutName===null||p.selectedRoute===null))return i.jsx("div",{className:"g7le-preview-canvas g7le-preview-canvas--empty","data-testid":"g7le-preview-empty",style:Jo,children:N("layout_editor.preview.empty")});if(m)return i.jsx("div",{className:"g7le-preview-canvas g7le-preview-canvas--loading","data-testid":"g7le-preview-loading",style:Jo,children:N("layout_editor.preview.loading")});if(h)return i.jsx(Fa,{error:h});if(D)return i.jsx(Fa,{error:D});if(!z||$===null||A===null)return i.jsx("div",{className:"g7le-preview-canvas g7le-preview-canvas--assets-loading","data-testid":"g7le-preview-assets-loading",style:Jo,children:N("layout_editor.preview.assets_loading")});if(se.length===0)return i.jsx("div",{className:"g7le-preview-canvas g7le-preview-canvas--empty-layout","data-testid":"g7le-preview-empty-layout",style:Jo,children:N("layout_editor.preview.empty_layout")});const he=p.editMode==="extension"?re==="no-injection"?"no-injection":re==="ok"&&ee.length>0&&fe!==!0?"gated-no-state":null:null;return ne?i.jsx("div",{className:"g7le-preview-canvas","data-testid":"g7le-preview-canvas",style:{overflow:"visible",background:"#f1f5f9",padding:24,display:"flex",justifyContent:"center",alignItems:"flex-start",minHeight:"calc(100vh - var(--g7le-header-h, 0px))",boxSizing:"border-box"},children:i.jsxs("div",{className:"g7le-preview-frame-wrapper","data-testid":"g7le-preview-frame-wrapper",style:{position:"relative",width:k,transform:`scale(${w})`,transformOrigin:"top center"},children:[i.jsx("div",{className:_==="dark"?"g7le-preview-frame g7le-preview-dark":"g7le-preview-frame","data-testid":"g7le-preview-frame","data-color-scheme":_,ref:Q=>{v.current=Q,x(Q)},style:{width:k,background:"#fff",border:"1px solid #cbd5e1",boxShadow:"0 1px 3px rgba(0,0,0,0.05)",minHeight:400,position:"relative",transform:"translateZ(0)",overflow:"hidden"},children:i.jsx(WE,{overrideWidth:k,children:se.map((Q,ie)=>i.jsx(BE,{componentDef:Q,dataContext:{...Qe,...$4(V),_global:E4(V),_computedDefinitions:qe,...I?{_localInit:I,_local:{...De._local??{},...V._local??{}}}:{},route:W4({...De.route??{},...ve,path:p.selectedRoute?.path??""},G),query:{...De.query??{},...F??{}}},translationContext:{templateId:p.templateIdentifier,locale:p.locale},registry:$,bindingEngine:O.current,translationEngine:Pt.getInstance(),actionDispatcher:M.current,isEditMode:!0,isRootRenderer:ie===0,componentPath:`${ie}`,onComponentSelect:(_e,ge)=>{},onComponentHover:(_e,ge)=>{}},`${Q.id??`preview-${ie}`}:t${Me}${p.editMode==="extension"?`:s${ne?1:0}`:""}`))})}),i.jsx("div",{className:"g7le-overlay-layer","data-testid":"g7le-overlay-layer",style:{position:"absolute",left:0,top:0,width:k,height:b?b.getBoundingClientRect().height/(w||1):"100%",overflow:"visible",pointerEvents:"none"},children:i.jsx(l4,{frameEl:b,manifest:t,nesting:n,componentPalette:o,spec:r,permissionCandidates:s,resolveRouteMatch:l,onNavigateToDestination:d,onSessionAddedPathsChange:c})}),he!==null&&i.jsx("div",{className:"g7le-preview-canvas--extension-fallback","data-testid":"g7le-preview-extension-fallback","data-fallback-reason":he,style:{position:"absolute",left:0,top:0,right:0,bottom:0,minHeight:b?b.getBoundingClientRect().height/(w||1):400,background:"#f1f5f9",display:"flex",alignItems:"flex-start",justifyContent:"center",padding:24,boxSizing:"border-box",pointerEvents:"auto",zIndex:50},children:i.jsxs("div",{className:"g7le-extension-fallback-card",style:{maxWidth:440,textAlign:"center",position:"sticky",top:"calc(40vh - var(--g7le-header-h, 0px))"},children:[i.jsx("p",{className:"g7le-extension-fallback-title",style:{fontWeight:600,marginBottom:8,color:"#0f172a"},children:N(he==="no-injection"?"layout_editor.preview.extension_no_injection_title":"layout_editor.preview.extension_gated_title")}),i.jsx("p",{className:"g7le-extension-fallback-desc",style:{color:"#475569",lineHeight:1.6},children:he==="no-injection"?N("layout_editor.preview.extension_no_injection_desc"):p.availableStates.length>1?N("layout_editor.preview.extension_gated_desc_with_states"):N("layout_editor.preview.extension_gated_desc")})]})})]})}):i.jsx("div",{className:"g7le-preview-canvas g7le-preview-canvas--scripts-loading","data-testid":"g7le-preview-scripts-loading",style:Jo,children:N("layout_editor.preview.loading")})}function O4(e,t,n){if(!e)return;if(!t)return e;const o=s=>{if(typeof s=="string"&&s.startsWith("$t:"))try{const a=s.slice(3),l=a.indexOf("|");if(l===-1)return t.translate(a,n);const d=a.slice(0,l),c=a.slice(l);return t.translate(d,n,c)}catch{return s}return Array.isArray(s)?s.map(o):s},r={};for(const[s,a]of Object.entries(e))r[s]=o(a);return r}function B4(e,t){const n=[],o=(r,s)=>{Array.isArray(r)&&r.forEach((a,l)=>{if(!a||typeof a!="object")return;const d=s?`${s}.children.${l}`:`${l}`,c=a.__source;if(c?.kind==="extension"&&c.extensionId===t){n.push(d);return}Array.isArray(a.children)&&o(a.children,d)})};return o(e,""),n}function W4(e,t){if(!t)return e;const n={...e};for(const[o,r]of Object.entries(t))r===null?delete n[o]:n[o]=r;return n}const Jo={flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"#f1f5f9",color:"#64748b",fontSize:13},j4={desktop:"layout_editor.device.desktop",tablet:"layout_editor.device.tablet",mobile:"layout_editor.device.mobile",portable:"layout_editor.device.portable"};function H4(){const{device:e,zoom:t,customWidth:n,setDevice:o,setZoom:r,setCustomWidth:s,colorScheme:a,setColorScheme:l}=ja(),{t:d}=tt(),c=Vf();return i.jsxs("div",{className:"g7le-device-toolbar","data-testid":"g7le-device-toolbar",style:{display:"inline-flex",alignItems:"center",gap:8,padding:"4px 8px",background:"#fff",border:"1px solid #cbd5e1",borderRadius:6},children:[i.jsxs("div",{role:"group","aria-label":d("layout_editor.device.group_label"),children:[c.map(p=>{const f=e===p,y=j4[p],g=y?d(y):p;return i.jsx("button",{type:"button","data-testid":`g7le-device-${p}`,"aria-pressed":f,onClick:()=>o(p),style:{padding:"2px 8px",marginRight:2,fontSize:12,cursor:"pointer",background:f?"#0f172a":"#f8fafc",color:f?"#fff":"#0f172a",border:"1px solid #cbd5e1",borderRadius:4},children:g},p)}),(()=>{const p=e==="custom";return i.jsx("button",{type:"button","data-testid":"g7le-device-custom","aria-pressed":p,onClick:()=>o("custom"),style:{padding:"2px 8px",marginRight:2,fontSize:12,cursor:"pointer",background:p?"#0f172a":"#f8fafc",color:p?"#fff":"#0f172a",border:"1px solid #cbd5e1",borderRadius:4},children:d("layout_editor.device.custom")})})()]}),e==="custom"&&i.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[i.jsx("label",{htmlFor:"g7le-custom-width-input",style:{fontSize:11,color:"#475569"},children:d("layout_editor.device.custom_width_label")}),i.jsx("input",{id:"g7le-custom-width-input",type:"number",min:lg,max:dg,step:10,value:n,"data-testid":"g7le-custom-width-input","aria-label":d("layout_editor.device.custom_width_label"),onChange:p=>{const f=parseInt(p.currentTarget.value,10);Number.isFinite(f)&&s(f)},style:{width:72,padding:"2px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:4}}),i.jsx("span",{style:{fontSize:11,color:"#475569"},children:"px"})]}),i.jsx("div",{role:"group","aria-label":d("layout_editor.toolbar.color_scheme_group"),style:{display:"inline-flex",gap:2},children:["light","dark"].map(p=>{const f=a===p;return i.jsx("button",{type:"button","data-testid":`g7le-toolbar-scheme-${p}`,"aria-pressed":f,onClick:()=>l(p),style:{padding:"2px 8px",fontSize:12,cursor:"pointer",background:f?"#0f172a":"#f8fafc",color:f?"#fff":"#0f172a",border:"1px solid #cbd5e1",borderRadius:4},children:d(p==="light"?"layout_editor.toolbar.color_scheme_light":"layout_editor.toolbar.color_scheme_dark")},p)})}),i.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[i.jsx("span",{style:{fontSize:11,color:"#475569"},children:d("layout_editor.zoom.label")}),i.jsx("input",{type:"range",min:.5,max:1,step:.05,value:t,"data-testid":"g7le-zoom-slider","aria-label":d("layout_editor.zoom.aria_label"),onChange:p=>r(parseFloat(p.currentTarget.value)),style:{width:100}}),i.jsxs("span",{style:{fontSize:11,color:"#475569",minWidth:36,textAlign:"right"},children:[Math.round(t*100),"%"]})]}),i.jsx(jb,{})]})}function F4(){const{t:e}=tt(),{state:t,dispatch:n}=Je(),{availableStates:o,activeStateId:r}=t,[,s]=u.useState(0);u.useEffect(()=>{if(typeof window>"u")return;const p=()=>s(y=>y+1),f=window.requestAnimationFrame(p);return window.addEventListener(Ga,p),()=>{window.cancelAnimationFrame(f),window.removeEventListener(Ga,p)}},[]);const a=u.useCallback((p,f)=>{if(!p)return f;if(!p.startsWith("$t:"))return p;const y=p.slice(3),g=window.G7Core;if(g&&typeof g.t=="function"){const h=g.t(y);if(h&&h!==y&&!h.startsWith("$t:"))return h}const m=e(y);return m&&m!==y?m:f},[e]);if(!Array.isArray(o)||o.length<=1)return null;const l=p=>{const f=p.target.value;n({type:"SET_ACTIVE_STATE",activeStateId:f}),$l({kind:"change",activeStateId:f,routePath:t.selectedRoute?.path??null,availableCount:o.length})},d=o.find(p=>p.id===r)??o[0],c=d?.description?a(d.description,""):"";return i.jsxs("div",{className:"g7le-state-switcher","data-testid":"g7le-state-switcher","data-active-state":r??"",style:{display:"inline-flex",alignItems:"center",gap:6,padding:"4px 8px",background:"#fff",border:"1px solid #cbd5e1",borderRadius:6},children:[i.jsx("span",{style:{fontSize:12,fontWeight:600,color:"#475569",whiteSpace:"nowrap"},children:e("layout_editor.toolbar.state")}),i.jsx("select",{"data-testid":"g7le-state-switcher-select","aria-label":e("layout_editor.toolbar.state"),value:r??o[0].id,onChange:l,style:{fontSize:12,padding:"2px 6px",border:"1px solid #cbd5e1",borderRadius:4,background:"#fff",color:"#0f172a",cursor:"pointer",outline:"none"},children:o.map(p=>i.jsx("option",{value:p.id,children:a(p.label,p.id)},p.id))}),c&&i.jsx("span",{"data-testid":"g7le-state-switcher-description",style:{fontSize:11,color:"#94a3b8",whiteSpace:"nowrap"},children:c})]})}function K4(e,t,n){if(e==="extension"){if(typeof n=="string"&&n.length>0){const o=Ya(n,"__base__/");return o?{kind:"base",match:o}:{kind:"route",match:n}}return null}if(!t)return null;switch(e){case"route":return{kind:"route",match:t};case"base":{const o=Ya(t,"__base__/");return o?{kind:"base",match:o}:null}case"modal":{const o=Ya(t,"__modal__/");return o?{kind:"modal",match:o}:null}default:return null}}function V4(e,t){if(!t||!Array.isArray(e)||e.length===0)return[];const n=[];for(const o of e)if(q4(o.scope,t))for(const r of o.items??[])r&&typeof r.id=="string"&&r.id.length>0&&n.push(r);return n}function U4(e){if(e.length===0)return null;const t=e.find(n=>n.default===!0);return t?t.id:e[0].id}function q4(e,t){if(!e||e.kind!==t.kind)return!1;const n=e.match;return typeof n!="string"||n.length===0?!1:t.kind==="route"?G4(t.match,n):n===t.match}function G4(e,t){if(t===e)return!0;if(!t.includes("*"))return!1;const n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]+");return new RegExp(`^${n}$`).test(e)}function Ya(e,t){return e.startsWith(t)?e.slice(t.length):""}const Y4="__conngroup__/modals/",X4="__conngroup__/extensions/";function J4(e){return e.meta?.editor_label?{label:e.meta.editor_label,labelSource:"editor_label"}:e.meta?.title?{label:e.meta.title,labelSource:"title"}:{label:e.path,labelSource:"path"}}function Z4(e){switch(e.source.kind){case"template":return"template";case"module":return`module:${e.source.identifier??""}`;case"plugin":return`plugin:${e.source.identifier??""}`;case"core":return null;default:return null}}function Q4(e,t){if(e.meta?.parent&&t.has(e.meta.parent))return e.meta.parent;const n=e.path.split("/").filter(Boolean);for(let o=n.length-1;o>=1;o--){const r="/"+n.slice(0,o).join("/");if(r!==e.path&&t.has(r))return r}return null}function R4(e){const t=new Map;for(const n of e)n.layout&&t.set(n.layout,(t.get(n.layout)??0)+1);return t}function eD(e){const t=new Map;for(const n of e){if(!n.hostLayout)continue;const o=t.get(n.hostLayout)??[];o.push(n),t.set(n.hostLayout,o)}return t}function tD(e){const t=new Map;for(const n of e)for(const o of n.extensions)for(const r of o.hostLayouts??[]){if(!r)continue;const s=t.get(r)??[];s.push({extension:o,group:n}),t.set(r,s)}return t}function nD(e,t){return{path:`__modal__/${e.hostLayout}/${e.modalId}`,layoutName:e.hostLayout,label:e.label??e.modalId,labelSource:e.label?"editor_label":"path",source:{kind:"core",identifier:null},kind:"modal",modalId:e.modalId,modalHostLayout:e.hostLayout,connectedHostRoutePath:t,children:[]}}function oD(e,t){const{extension:n,group:o}=e,r=o.sourceType==="plugin"?"🔌":"🧩";return{path:`__extension__/${n.id}`,layoutName:null,label:`${r} ${o.sourceLabel} · ${n.targetName}`,labelSource:"path",source:{kind:o.sourceType,identifier:o.sourceIdentifier},kind:"extension",extensionId:String(n.id),extensionType:n.extensionType,extensionPriority:n.priority,extensionTargetName:n.targetName,isModified:n.isModified,isInactive:!n.isActive,connectedHostRoutePath:t,children:[]}}function _g(e,t,n){if(e.kind!=="route"&&e.kind!=="base"||!e.layoutName)return;const o=[],r=t.get(e.layoutName)??[];r.length>0&&o.push({path:`${Y4}${e.path}`,layoutName:null,label:`$t:layout_editor.chrome.route_tree.connected.modals|count=${r.length}`,labelSource:"editor_label",source:{kind:"core",identifier:null},kind:"route",children:r.map(a=>nD(a,e.path))});const s=n.get(e.layoutName)??[];s.length>0&&o.push({path:`${X4}${e.path}`,layoutName:null,label:`$t:layout_editor.chrome.route_tree.connected.extensions|count=${s.length}`,labelSource:"editor_label",source:{kind:"core",identifier:null},kind:"route",children:s.map(a=>oD(a,e.path))}),o.length>0&&(e.children=[...o,...e.children??[]])}function rD(e){const t=[],n=new Set(e.routes.map(o=>o.path));for(const o of e.routes){const r=Z4(o);if(!r)continue;const{label:s,labelSource:a}=J4(o),l=Q4(o,n),d={path:o.path,layoutName:o.layout??null,label:s,labelSource:a,icon:o.meta?.icon??null,source:o.source,isRedirect:!!o.redirect,isHidden:!!o.meta?.hidden,kind:"route",children:[]};t.push({node:d,parentKey:l,groupKey:r})}return t}function iD(e,t){if(e==="template")return"$t:layout_editor.chrome.route_tree.group.template";if(e.startsWith("module:")){const n=e.slice(7);return`$t:layout_editor.chrome.route_tree.group.module|name=${t.moduleDisplayNames[n]??n}`}if(e.startsWith("plugin:")){const n=e.slice(7);return`$t:layout_editor.chrome.route_tree.group.plugin|name=${t.pluginDisplayNames[n]??n}`}return e}function sD(e,t){R4(e.routes);const n=eD(e.modals),o=tD(e.extensionGroups??[]),r=new Map;for(const d of t)r.has(d.groupKey)||r.set(d.groupKey,[]),r.get(d.groupKey).push(d);const s=Array.from(r.keys()).sort((d,c)=>{const p=g=>g==="template"?1:g.startsWith("module:")?2:g.startsWith("plugin:")?3:4,f=p(d),y=p(c);return f!==y?f-y:d.localeCompare(c)}),a=[];if(e.baseLayouts.length>0){const d=e.baseLayouts.map(c=>({path:`__base__/${c.layoutName}`,layoutName:c.layoutName,label:c.label??c.layoutName,labelSource:c.label?"editor_label":"path",source:{kind:"core",identifier:null},kind:"base",children:[]}));for(const c of d)_g(c,n,o);a.push({path:"__group__/base",layoutName:null,label:"$t:layout_editor.chrome.route_tree.group.base",labelSource:"editor_label",source:{kind:"core",identifier:null},kind:"route",children:d})}for(const d of s){const c=r.get(d),p=new Map;for(const y of c)p.set(y.node.path,y);const f=[];for(const y of c)if(y.parentKey&&p.has(y.parentKey)){const g=p.get(y.parentKey);g.node.children=g.node.children??[],g.node.children.push(y.node)}else f.push(y.node);for(const y of c)_g(y.node,n,o);a.push({path:`__group__/${d}`,layoutName:null,label:iD(d,e),labelSource:"editor_label",source:{kind:"core",identifier:null},kind:"route",children:f})}if(e.modals.length>0){const d=e.modals.map(c=>({path:`__modal__/${c.hostLayout}/${c.modalId}`,layoutName:c.hostLayout,label:c.label??c.modalId,labelSource:c.label?"editor_label":"path",source:{kind:"core",identifier:null},kind:"modal",modalId:c.modalId,modalHostLayout:c.hostLayout,children:[]}));a.push({path:"__group__/modal",layoutName:null,label:"$t:layout_editor.chrome.route_tree.group.modal",labelSource:"editor_label",source:{kind:"core",identifier:null},kind:"route",children:d})}const l=e.extensionGroups??[];if(l.length>0){const d=l.map(c=>{const p=c.sourceType==="plugin"?"🔌":"🧩",f=c.extensions.map(y=>({path:`__extension__/${y.id}`,layoutName:null,label:`${c.sourceLabel} · ${y.targetName}`,labelSource:"path",source:{kind:c.sourceType,identifier:c.sourceIdentifier},kind:"extension",extensionId:String(y.id),extensionType:y.extensionType,extensionPriority:y.priority,extensionTargetName:y.targetName,isModified:y.isModified,isInactive:!y.isActive,children:[]}));return{path:`__extgroup__/${c.sourceType}/${c.sourceIdentifier}`,layoutName:null,label:`${p} ${c.sourceLabel}`,labelSource:"path",source:{kind:c.sourceType,identifier:c.sourceIdentifier},kind:"route",children:f}});a.push({path:"__group__/extension",layoutName:null,label:"$t:layout_editor.chrome.route_tree.group.extension",labelSource:"editor_label",source:{kind:"core",identifier:null},kind:"route",children:d})}return a}function aD(e){const t=rD(e);return sD(e,t)}const On=dr("useEditorRoutes");function lD(e,t){if(typeof e=="string")return e.length>0?e:null;if(e&&typeof e=="object"){const n=e[t];if(typeof n=="string"&&n.length>0)return n;if(typeof e.en=="string"&&e.en.length>0)return e.en;for(const o of Object.values(e))if(typeof o=="string"&&o.length>0)return o}return null}function xg(e,t){const n={};if(typeof window>"u")return n;const r=window.G7Config?.[e];if(!Array.isArray(r))return n;for(const s of r)s&&typeof s.identifier=="string"&&(n[s.identifier]=lD(s.display_name,t)??s.identifier);return n}function dD(e){const t=new vd,n=typeof window<"u"?window.G7Config:void 0,o={_global:{settings:n?.settings??{},plugins:n?.plugins??{},modules:n?.modules??{},appConfig:n?.appConfig??{}}};return e.map(r=>{const s={...r};if(typeof s.path=="string"&&s.path.includes("{{")){const a=s.path;let l=t.resolveBindings(s.path,o);l=l.replace(/\/\/+/g,"/")||"/",l.includes("{{")&&(On.warn("편집기 route path 표현식 평가 실패 — fallback 적용",{originalPath:a}),l=a.replace(/\{\{[^}]+\}\}/g,"").replace(/\/\/+/g,"/")||"/"),s.path=l}if(typeof s.redirect=="string"&&s.redirect.includes("{{")){const a=s.redirect;let l=t.resolveBindings(a,o);l=l.replace(/\/\/+/g,"/")||"/",l.includes("{{")&&(On.warn("편집기 route redirect 표현식 평가 실패 — fallback 적용",{originalRedirect:a}),l=a.replace(/\{\{[^}]+\}\}/g,"").replace(/\/\/+/g,"/")||"/"),s.redirect=l}return s})}function cD(e){const{dispatch:t}=Je(),{translationEngine:n,translationContext:o}=tt(),{templateIdentifier:r,cacheVersion:s}=e;u.useEffect(()=>{let a=!1;const l=s??(typeof window<"u"?window.G7Config?.cache_version:void 0)??"",d=l!==""?`?v=${encodeURIComponent(String(l))}`:"",c=en(`/api/admin/templates/${encodeURIComponent(r)}/editor/routes`,"json",null,d.replace(/^[?&]+/,"")),p=o?.locale??"ko",f=n&&r!==o?.templateId?n.loadTranslations(r,p).then(()=>{On.log("편집 대상 lang 로드 완료",{targetTemplate:r,locale:p})}).catch(h=>{On.warn("편집 대상 lang 로드 실패 — 라우트 라벨 fallback 사용",h)}):Promise.resolve(),y=(()=>{if(typeof fetch!="function")return Promise.reject(io(new Error("fetch unavailable"),"routes"));try{const h=fetch(c,{credentials:"same-origin",headers:je()});return!h||typeof h.then!="function"?Promise.reject(io(new Error("fetch returned non-Promise (test stub?)"),"routes")):h.then(async v=>{if(!v.ok){const b=await v.json().catch(()=>null);throw Gr(v.status,b,"routes")}return v.json()})}catch(h){return Promise.reject(h)}})(),g=`/api/admin/templates/${encodeURIComponent(r)}/layout-extensions${d}`,m=(()=>{if(typeof fetch!="function")return Promise.resolve(null);try{const h=fetch(g,{credentials:"same-origin",headers:je()});return!h||typeof h.then!="function"?Promise.resolve(null):h.then(async v=>v.ok?await v.json():null).catch(()=>null)}catch{return Promise.resolve(null)}})();return Promise.all([y,f,m]).then(([h,,v])=>{if(a)return;if(!h||!h.success||!Array.isArray(h.data?.routes)){On.warn("routes 응답 형식이 비정상 — empty tree 로 둠",h),t({type:"SET_ROUTES_ERROR",error:{kind:"unknown",status:200,message:"routes 응답 형식이 비정상입니다.",source:"routes"}});return}const b=dD(h.data.routes),x=xg("activeModules",p),k=xg("activePlugins",p),w=(h.data.base_layouts??[]).map(A=>({layoutName:A.layout_name,label:A.label??void 0})),_=(h.data.modals??[]).map(A=>({modalId:A.modal_id,hostLayout:A.host_layout,label:A.label??void 0})),S=(v?.success&&Array.isArray(v.data)?v.data:[]).map(A=>({sourceIdentifier:A.source_identifier,sourceType:A.source_type,sourceLabel:A.source_label,extensions:(A.extensions??[]).map(z=>({id:z.id,extensionType:z.extension_type,targetName:z.target_name,priority:z.priority,isActive:z.is_active,isModified:z.is_modified,hostLayouts:Array.isArray(z.host_layouts)?z.host_layouts:[],currentVersion:typeof z.current_version=="number"?z.current_version:void 0}))})),E=aD({routes:b,modals:_,baseLayouts:w,extensionGroups:S,moduleDisplayNames:x,pluginDisplayNames:k});t({type:"SET_ROUTE_TREE",tree:E});const C=h.data.layout_versions,N={};if(C&&typeof C=="object"&&!Array.isArray(C))for(const[A,z]of Object.entries(C))typeof z=="number"&&Number.isFinite(z)&&(N[A]=z);t({type:"SET_LAYOUT_VERSIONS",versions:N});const $={};for(const A of S)for(const z of A.extensions){const D=z.currentVersion;typeof D=="number"&&Number.isFinite(D)&&($[String(z.id)]=D)}t({type:"SET_EXTENSION_VERSIONS",versions:$}),On.log("routes 로드 완료",{count:b.length,groups:E.length})}).catch(h=>{if(a)return;On.error("routes 로드 실패",h);const v=pp(h)?h:io(h,"routes");t({type:"SET_ROUTES_ERROR",error:v})}),()=>{a=!0}},[r,s,t,n,o?.locale,o?.templateId])}function wg(e,t,n,o=[]){const r=t?kg(o,t):null,s=r!==null?{path:r.path,layoutName:r.layoutName}:void 0;if(e.startsWith("__base__/")){const a=e.slice(9);if(a)return n({type:"ENTER_BASE_EDIT",layoutName:a,returnRoute:s}),!0}else if(e.startsWith("__modal__/")){const a=e.slice(10);return a&&!a.includes("/")&&t?(n({type:"ENTER_MODAL_EDIT",modalId:a,hostLayout:t,returnRoute:s}),!0):!1}else if(e.startsWith("__extension__/")){const a=e.slice(14);if(a&&!a.includes("/"))return n({type:"ENTER_EXTENSION_EDIT",extensionId:a,returnRoute:s}),!0}else if(e.startsWith("__iteration__/")){const a=e.slice(14);return a&&t?(n({type:"ENTER_ITERATION_ITEM_EDIT",sourcePath:a,hostLayout:t,returnRoute:s}),!0):!1}return!1}function kg(e,t){for(const n of e){if(n.kind==="route"&&n.layoutName===t)return n;if(n.children&&n.children.length>0){const o=kg(n.children,t);if(o)return o}}return null}function Xa(e,t){for(const n of e){if(n.kind==="route"&&n.path===t)return n;if(n.children&&n.children.length>0){const o=Xa(n.children,t);if(o)return o}}return null}function uD(e){const{state:t,dispatch:n}=Je(),o=u.useRef(!1),r=u.useRef(t.editMode);r.current=t.editMode,u.useEffect(()=>{if(o.current||t.routeTree.length===0||typeof window>"u")return;const a=rp(window.location.search);if(a){const c=op(window.location.search),p=wg(a,c,n,t.routeTree);if(o.current=!0,p)return}const l=np(window.location.search);if(!l){o.current=!0;return}const d=Xa(t.routeTree,l);d&&n({type:"SELECT_ROUTE",route:{path:d.path,layoutName:d.layoutName}}),o.current=!0},[t.routeTree,n]),u.useEffect(()=>{if(typeof window>"u")return;const a=()=>{const l=rp(window.location.search);if(l){const p=op(window.location.search);if(wg(l,p,n,t.routeTree))return}if(r.current!=="route")switch(r.current){case"base":n({type:"EXIT_BASE_EDIT"});return;case"modal":n({type:"EXIT_MODAL_EDIT"});return;case"extension":n({type:"EXIT_EXTENSION_EDIT"});return;case"iteration_item":n({type:"EXIT_ITERATION_ITEM_EDIT"});return}const d=np(window.location.search);if(!d){n({type:"SELECT_ROUTE",route:null});return}const c=Xa(t.routeTree,d);c&&n({type:"SELECT_ROUTE",route:{path:c.path,layoutName:c.layoutName}})};return window.addEventListener("popstate",a),()=>{window.removeEventListener("popstate",a)}},[t.routeTree,n]);const s=u.useRef("route");u.useEffect(()=>{if(typeof window>"u"||!window.history?.replaceState||t.routeTree.length===0)return;const a=Zs(e,t.selectedRoute?.path??null,t.selectedRoute?.layoutName??null),l=`${window.location.pathname}${window.location.search}`,d=s.current;if(s.current=t.editMode,l===a)return;d==="route"&&t.editMode!=="route"&&window.history.pushState?window.history.pushState(window.history.state,"",a):window.history.replaceState(window.history.state,"",a)},[t.selectedRoute,t.editMode,t.routeTree,e])}function pD(){u.useEffect(()=>{if(typeof document>"u")return;const e=document.documentElement;let t=e.classList.contains("dark");const n=()=>{e.classList.contains("dark")&&(t=!0,e.classList.remove("dark"))};n();let o=null;return typeof MutationObserver<"u"&&(o=new MutationObserver(n),o.observe(e,{attributes:!0,attributeFilter:["class"]})),()=>{o?.disconnect(),t&&e.classList.add("dark")}},[])}function fD(){u.useEffect(()=>{if(typeof document>"u"||!document.body)return;const e=document.body,t=()=>{e.style.overflow==="hidden"&&(e.style.overflow=""),e.style.overflowY==="hidden"&&(e.style.overflowY="")};t();let n=null;return typeof MutationObserver<"u"&&(n=new MutationObserver(t),n.observe(e,{attributes:!0,attributeFilter:["style"]})),()=>{n?.disconnect()}},[])}function gD(e){if(typeof e!="string")return null;const t="__extension__/";if(!e.startsWith(t))return null;const n=e.slice(t.length);return n===""||n.includes("/")?null:n}function hD(e){if(Array.isArray(e.components))return e.components;if(Array.isArray(e.injections)){const t=[];return e.injections.forEach((n,o)=>{if(n&&Array.isArray(n.components))for(const r of n.components)t.push({...r,__injectionIndex:o})}),t}return[]}function yD(e,t){if(Array.isArray(e.components)){const n=t.map(o=>Ja(o));return{...e,components:n}}if(Array.isArray(e.injections)){const n=e.injections.map(o=>({...o}));n.forEach(o=>{Array.isArray(o.components)&&(o.components=[])});for(const o of t){const r=o.__injectionIndex,s=typeof r=="number"&&r>=0&&rJa(n))),t}function Sg(e,t){const n=[],o=r=>{if(Array.isArray(r))for(const s of r){if(!s||typeof s!="object")continue;const a=s.__source;if(a?.kind==="extension"&&a.extensionId===t){n.push(s);continue}Array.isArray(s.children)&&o(s.children)}};return o(e),n}function Cg(e,t){const o=Sg(e,t)[0]?.__source;return o&&o.kind==="extension"&&o.extensionId===t?o:{kind:"extension",extensionId:t}}function Za(e,t){for(const n of e){const o=n?.__source;if(o?.kind==="extension"&&o.extensionId===t||Array.isArray(n.children)&&Za(n.children,t))return!0}return!1}function bD(){const{state:e}=Je(),t=e.templateIdentifier,n=e.editMode==="extension"?gD(e.selectedRoute?.path):null,o=e.editMode==="extension"&&typeof e.selectedRoute?.layoutName=="string"?e.selectedRoute.layoutName:null,[r,s]=u.useState(null),[a,l]=u.useState(!1),[d,c]=u.useState(null),[p,f]=u.useState(!1),[y,g]=u.useState(0),[m,h]=u.useState(null),v=u.useRef({}),b=u.useRef({kind:"extension",extensionId:0}),x=u.useRef(null);u.useEffect(()=>{x.current=r},[r]),u.useEffect(()=>{h(null)},[n]);const k=u.useCallback(async A=>{const z=window.G7Config?.cache_version??0,D=en(`/api/layouts/${encodeURIComponent(t)}/${A}`,"json",`${z}.${xp()}`,"with_source_meta=1"),O=sr(),M={Accept:"application/json"};O&&(M.Authorization=`Bearer ${O}`);const B=await fetch(D,{headers:M,credentials:"same-origin"});if(!B.ok)return null;const T=await B.json().catch(()=>null);return(T&&(T.data||T))??{}},[t]),w=u.useCallback(async()=>{if(!n){s(null),c(null),f(!1);return}l(!0),c(null);try{const A=window.G7Config?.cache_version??0,z=`/api/admin/templates/${encodeURIComponent(t)}/layout-extensions/${encodeURIComponent(n)}?v=${A}`,D=await fetch(z,{headers:je(),credentials:"same-origin"}),O=await D.json().catch(()=>null);if(!D.ok){c(Gr(D.status,O,"layout")),s(null),f(!1);return}const M=(O&&(O.data||O))??{};let B={};const T=M.content;if(typeof T=="string")try{B=JSON.parse(T)}catch{B={}}else T&&typeof T=="object"&&(B=T);const H=M.extension_type==="overlay"?"overlay":"extension_point",L=typeof M.lock_version=="number"?M.lock_version:0,I=Array.isArray(M?.host_layouts)?M.host_layouts.filter(re=>typeof re=="string"):[],P=o??(I.length===1?I[0]:m&&I.includes(m)?m:null),F=Number(n);v.current=B;let V=hD(B),Y={},Z="pending";const se={kind:"extension",extensionId:F};if(b.current=se,P){const re=await k(P);if(re){Y=re;const U=Array.isArray(re.components)?re.components:[],ee=Cg(U,F);if(b.current=ee,Za(U,F))V=U,Z="ok";else{const K=(Array.isArray(re.modals)?re.modals:[]).filter(ne=>ne&&typeof ne=="object"&&Za([ne],F));if(K.length>0){const ne=K.map(me=>({...me,props:{...me.props??{},isOpen:!0}}));V=[...U,...ne],b.current=Cg(K,F),Z="ok"}else V=U,Z="no-injection"}}}s({extensionId:F,content:B,extensionType:H,components:V,lockVersion:L,hostLayouts:I,hostLayoutName:P,hostRaw:Y,editability:Z}),f(!1),st({op:"load",layoutName:`extension:${n}`,editMode:"extension",statusCode:D.status,timestamp:Date.now()})}catch(A){c(io(A,"layout")),s(null),f(!1)}finally{l(!1)}},[t,n,m,o,k]);u.useEffect(()=>{w()},[w]);const _=u.useCallback(A=>{h(A)},[]),S=u.useCallback(A=>{s(z=>z&&{...z,components:A}),f(!0),st({op:"patch",layoutName:`extension:${x.current?.extensionId??""}`,editMode:"extension",isDirty:!0,timestamp:Date.now()})},[]),E=u.useCallback(A=>{s(z=>z&&{...z,components:A(z.components)}),f(!0)},[]),C=u.useCallback(async()=>{const A=x.current;if(!A)return{kind:"guard_no_document"};const z=`/api/admin/templates/${encodeURIComponent(t)}/layout-extensions/${A.extensionId}`,D=Sg(A.components,A.extensionId),O=D.length>0?D:A.components,M=yD(v.current,O);st({op:"save",layoutName:`extension:${A.extensionId}`,editMode:"extension",saveTarget:"layout_extension",endpoint:z,isDirty:p,timestamp:Date.now()});let B;try{B=await fetch(z,{method:"PUT",headers:je({"Content-Type":"application/json"}),credentials:"same-origin",body:JSON.stringify({content:M,expected_lock_version:A.lockVersion})})}catch(H){return{kind:"network_error",message:H instanceof Error?H.message:"network error"}}const T=await B.json().catch(()=>null);if(st({op:"save_response",layoutName:`extension:${A.extensionId}`,editMode:"extension",endpoint:z,statusCode:B.status,conflict:B.status===409?{currentVersion:T?.errors?.current_version??T?.current_version,yourVersion:T?.errors?.your_version??T?.your_version}:void 0,timestamp:Date.now()}),B.ok){const H=T?.data??{},L=typeof H.lock_version=="number"?H.lock_version:A.lockVersion+1;s(P=>P&&{...P,lockVersion:L}),f(!1),g(P=>P+1);const I=typeof H.current_version=="number"?H.current_version:void 0;return{kind:"success",newLockVersion:L,newContentVersion:I,savedExtensionId:String(A.extensionId)}}return B.status===409?{kind:"concurrent_modification",currentVersion:T?.current_version??-1,yourVersion:T?.your_version??A.lockVersion}:B.status===422?{kind:"validation_failed",status:422,errors:T?.errors??null}:{kind:"network_error",message:T?.message??`HTTP ${B.status}`}},[t,p]),N=u.useCallback(async()=>{na(),await w()},[w]),$=!!r&&r.hostLayouts.length>1&&r.hostLayoutName===null;return{document:r,isLoading:a,error:d,isDirty:p,saveSuccessCounter:y,setLayoutComponents:S,patchLayout:E,save:C,reload:N,needsHostPicker:$,selectHost:_}}const $g=new Set;function mD(e,t,n){const r=e&&Object.keys(e).length>0?e:t,s=Array.isArray(r.data_sources)?r.data_sources:[],a=Array.isArray(t.data_sources)?t.data_sources:[],l=new Set,d=[];for(const c of[...s,...a]){const p=c&&typeof c=="object"?c.id:void 0,f=typeof p=="string"?p:`__anon_${d.length}`;l.has(f)||(l.add(f),d.push(c))}return{...r,components:n,...d.length>0?{data_sources:d}:{},lock_version:void 0}}function vD(e){return{document:e.document?{layoutName:`extension:${e.document.extensionId}`,raw:{...mD(e.document.hostRaw,e.document.content,e.document.components),__editability:e.document.editability,__extensionId:e.document.extensionId},lockVersion:e.document.lockVersion}:null,isLoading:e.isLoading,error:e.error,isDirty:e.isDirty,saveSuccessCounter:e.saveSuccessCounter,reload:e.reload,patchLayout:e.patchLayout,setLayoutComponents:e.setLayoutComponents,patchDocumentRaw:()=>{},dirtyKeys:$g,dirtyLayoutNames:$g,invalidateCurrentCache:()=>{},reloadCounter:0,save:()=>e.save(),markDirty:()=>{}}}function _D({hostLayouts:e,extensionLabel:t,onSelect:n}){const{t:o}=tt();return i.jsx("div",{className:"g7le-host-picker__backdrop","data-testid":"g7le-host-picker",role:"dialog","aria-modal":"true","aria-label":o("layout_editor.host_picker.title"),style:{position:"fixed",inset:0,zIndex:9500,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(15, 23, 42, 0.55)"},children:i.jsxs("div",{className:"g7le-host-picker__panel",style:{width:"min(520px, 92vw)",maxHeight:"80vh",overflow:"auto",background:"#ffffff",color:"#0f172a",borderRadius:12,boxShadow:"0 20px 48px rgba(15, 23, 42, 0.28)",padding:"20px 22px"},children:[i.jsx("h2",{className:"g7le-host-picker__title",style:{margin:"0 0 6px",fontSize:16,fontWeight:700},children:o("layout_editor.host_picker.title")}),i.jsx("p",{className:"g7le-host-picker__desc",style:{margin:"0 0 16px",fontSize:13,color:"#475569",lineHeight:1.6},children:t?o("layout_editor.host_picker.description_with_label",{label:t}):o("layout_editor.host_picker.description")}),i.jsx("ul",{className:"g7le-host-picker__list",style:{listStyle:"none",margin:0,padding:0,display:"grid",gap:8},children:e.map(r=>i.jsx("li",{children:i.jsxs("button",{type:"button",className:"g7le-host-picker__item","data-testid":"g7le-host-picker-item","data-host":r,onClick:()=>n(r),style:{width:"100%",textAlign:"left",padding:"12px 14px",border:"1px solid #e2e8f0",borderRadius:8,background:"#f8fafc",cursor:"pointer",fontSize:13,fontWeight:600,color:"#0f172a",display:"flex",alignItems:"center",gap:8},children:[i.jsx("span",{"aria-hidden":!0,style:{fontSize:14},children:"🖼"}),i.jsx("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis"},children:r}),i.jsx("span",{"aria-hidden":!0,style:{color:"#94a3b8"},children:"→"})]})},r))})]})})}function xD(e,t){const[n,o]=u.useState(!1),[r,s]=u.useState(null),a=u.useCallback(async l=>{if(!t||!l)return{kind:"no_document"};o(!0),s(null);try{const d=mo(l),c=`/api/admin/templates/${encodeURIComponent(e)}/layouts/${t}/preview`,p=await fetch(c,{method:"POST",credentials:"same-origin",headers:je({"Content-Type":"application/json"}),body:JSON.stringify({content:JSON.stringify(d)})}),f=await p.json().catch(()=>null);if(!p.ok){const h=f?.message??`HTTP ${p.status}`;return s(h),{kind:"network_error",message:h}}const y=f?.data,g=typeof y?.token=="string"?y.token:"",m=typeof y?.preview_url=="string"&&y.preview_url?y.preview_url:g?`/preview/${g}`:"";return m?(window.G7Core?.dispatch?.({handler:"openWindow",params:{path:m}}),{kind:"success",previewUrl:m,token:g}):(s("invalid preview response"),{kind:"network_error",message:"invalid preview response"})}catch(d){const c=d instanceof Error?d.message:"network error";return s(c),{kind:"network_error",message:c}}finally{o(!1)}},[e,t]);return{isCreating:n,error:r,createPreview:a}}const ce="layout_editor.action_recipe",bn={setState:{label:`$t:${ce}.set_state.label`,params:[{key:"target",label:`$t:${ce}.set_state.param_target`,widget:"select",options:[{value:"local"},{value:"global"}]},{key:"state",label:`$t:${ce}.set_state.param_state`,widget:"state-key-value"},{key:"merge",label:`$t:${ce}.set_state.param_merge`,widget:"toggle"}],build:{handler:"setState",params:{target:"{{target}}",merge:"{{merge}}","...":"{{state}}"}}},loadFromLocalStorage:{label:`$t:${ce}.load_local.label`,params:[{key:"key",label:`$t:${ce}.load_local.param_key`,widget:"text",required:!0},{key:"stateKey",label:`$t:${ce}.load_local.param_state_key`,widget:"state-key-picker"},{key:"defaultValue",label:`$t:${ce}.load_local.param_default`,widget:"text"}],build:{handler:"loadFromLocalStorage",params:{key:"{{key}}",stateKey:"{{stateKey}}",defaultValue:"{{defaultValue}}"}}},saveToLocalStorage:{label:`$t:${ce}.save_local.label`,params:[{key:"key",label:`$t:${ce}.save_local.param_key`,widget:"text",required:!0},{key:"value",label:`$t:${ce}.save_local.param_value`,widget:"data-chip"}],build:{handler:"saveToLocalStorage",params:{key:"{{key}}",value:"{{value}}"}}},navigate:{label:`$t:${ce}.navigate.label`,params:[{key:"path",label:`$t:${ce}.navigate.param_path`,widget:"page-picker",required:!0},{key:"query",label:`$t:${ce}.navigate.param_query`,widget:"key-value"},{key:"mergeQuery",label:`$t:${ce}.navigate.param_merge_query`,widget:"toggle"},{key:"scroll",label:`$t:${ce}.navigate.param_scroll`,widget:"select",options:[{value:"top"},{value:"preserve"},{value:"none"}]},{key:"replace",label:`$t:${ce}.navigate.param_replace`,widget:"toggle"},{key:"transition_overlay_target",label:`$t:${ce}.navigate.param_overlay_target`,widget:"component-target-picker",dependsOn:{param:"replace",equals:!0}}],build:{handler:"navigate",params:{path:"{{path}}",query:"{{query}}",mergeQuery:"{{mergeQuery}}",scroll:"{{scroll}}",replace:"{{replace}}",transition_overlay_target:"{{transition_overlay_target}}"}}},openWindow:{label:`$t:${ce}.open_window.label`,params:[{key:"target",label:`$t:${ce}.open_window.param_target`,widget:"page-picker",required:!0},{key:"windowTarget",label:`$t:${ce}.open_window.param_window_target`,widget:"select",options:[{value:"_blank"},{value:"_self"}]}],build:{handler:"openWindow",target:"{{target}}",params:{windowTarget:"{{windowTarget}}"}}},navigateBack:{label:`$t:${ce}.navigate_back.label`,params:[],build:{handler:"navigateBack"}},navigateForward:{label:`$t:${ce}.navigate_forward.label`,params:[],build:{handler:"navigateForward"}},replaceUrl:{label:`$t:${ce}.replace_url.label`,params:[{key:"path",label:`$t:${ce}.replace_url.param_path`,widget:"page-picker"},{key:"query",label:`$t:${ce}.replace_url.param_query`,widget:"key-value"}],build:{handler:"replaceUrl",params:{path:"{{path}}",query:"{{query}}"}}},toast:{label:`$t:${ce}.toast.label`,params:[{key:"message",label:`$t:${ce}.toast.param_message`,widget:"i18n-text",required:!0},{key:"type",label:`$t:${ce}.toast.param_type`,widget:"select",options:[{value:"info"},{value:"success"},{value:"warning"},{value:"error"}]},{key:"duration",label:`$t:${ce}.toast.param_duration`,widget:"number"},{key:"icon",label:`$t:${ce}.toast.param_icon`,widget:"text"}],build:{handler:"toast",params:{message:"{{message}}",type:"{{type}}",duration:"{{duration}}",icon:"{{icon}}"}}},openModal:{label:`$t:${ce}.open_modal.label`,params:[{key:"target",label:`$t:${ce}.open_modal.param_target`,widget:"modal-picker",required:!0}],build:{handler:"openModal",target:"{{target}}"}},closeModal:{label:`$t:${ce}.close_modal.label`,params:[],build:{handler:"closeModal"}},showAlert:{label:`$t:${ce}.show_alert.label`,params:[{key:"target",label:`$t:${ce}.show_alert.param_message`,widget:"i18n-text",required:!0}],build:{handler:"showAlert",target:"{{target}}"}},setError:{label:`$t:${ce}.set_error.label`,params:[{key:"target",label:`$t:${ce}.set_error.param_message`,widget:"i18n-text"},{key:"stateTarget",label:`$t:${ce}.set_error.param_state_target`,widget:"select",options:[{value:"local"},{value:"global"}]}],build:{handler:"setError",target:"{{target}}",params:{stateTarget:"{{stateTarget}}"}}},refetchDataSource:{label:`$t:${ce}.refetch.label`,params:[{key:"dataSourceId",label:`$t:${ce}.refetch.param_data_source`,widget:"datasource-picker",required:!0},{key:"sync",label:`$t:${ce}.refetch.param_sync`,widget:"toggle"}],build:{handler:"refetchDataSource",params:{dataSourceId:"{{dataSourceId}}",sync:"{{sync}}"}}},appendDataSource:{label:`$t:${ce}.append_data.label`,params:[{key:"dataSourceId",label:`$t:${ce}.append_data.param_data_source`,widget:"datasource-picker",required:!0},{key:"dataPath",label:`$t:${ce}.append_data.param_data_path`,widget:"text"},{key:"newData",label:`$t:${ce}.append_data.param_new_data`,widget:"data-chip"}],build:{handler:"appendDataSource",params:{dataSourceId:"{{dataSourceId}}",dataPath:"{{dataPath}}",newData:"{{newData}}"}}},updateDataSource:{label:`$t:${ce}.update_data.label`,params:[{key:"dataSourceId",label:`$t:${ce}.update_data.param_data_source`,widget:"datasource-picker",required:!0},{key:"data",label:`$t:${ce}.update_data.param_data`,widget:"data-chip"},{key:"merge",label:`$t:${ce}.update_data.param_merge`,widget:"toggle"}],build:{handler:"updateDataSource",params:{dataSourceId:"{{dataSourceId}}",data:"{{data}}",merge:"{{merge}}"}}},scrollIntoView:{label:`$t:${ce}.scroll.label`,params:[{key:"selector",label:`$t:${ce}.scroll.param_selector`,widget:"text",required:!0},{key:"behavior",label:`$t:${ce}.scroll.param_behavior`,widget:"select",options:[{value:"smooth"},{value:"auto"}]},{key:"block",label:`$t:${ce}.scroll.param_block`,widget:"select",options:[{value:"start"},{value:"center"},{value:"end"},{value:"nearest"}]}],build:{handler:"scrollIntoView",params:{selector:"{{selector}}",behavior:"{{behavior}}",block:"{{block}}"}}},login:{label:`$t:${ce}.login.label`,params:[{key:"body",label:`$t:${ce}.login.param_body`,widget:"key-value"}],build:{handler:"login",params:{body:"{{body}}"}}},logout:{label:`$t:${ce}.logout.label`,params:[{key:"target",label:`$t:${ce}.logout.param_target`,widget:"text"}],build:{handler:"logout",target:"{{target}}"}},setLocale:{label:`$t:${ce}.set_locale.label`,params:[{key:"target",label:`$t:${ce}.set_locale.param_target`,widget:"locale-picker",required:!0}],build:{handler:"setLocale",target:"{{target}}"}},emitEvent:{label:`$t:${ce}.emit_event.label`,params:[{key:"event",label:`$t:${ce}.emit_event.param_event`,widget:"text",required:!0},{key:"data",label:`$t:${ce}.emit_event.param_data`,widget:"data-chip"}],build:{handler:"emitEvent",params:{event:"{{event}}",data:"{{data}}"}}},apiCall:{label:`$t:${ce}.api_call.label`,params:[{key:"target",label:`$t:${ce}.api_call.param_target`,widget:"page-picker",required:!0},{key:"method",label:`$t:${ce}.api_call.param_method`,widget:"select",options:[{value:"GET"},{value:"POST"},{value:"PUT"},{value:"PATCH"},{value:"DELETE"}]},{key:"body",label:`$t:${ce}.api_call.param_body`,widget:"key-value"},{key:"query",label:`$t:${ce}.api_call.param_query`,widget:"key-value"},{key:"identity_target_email",label:`$t:${ce}.api_call.param_identity_target_email`,widget:"data-chip"},{key:"identity_target_phone",label:`$t:${ce}.api_call.param_identity_target_phone`,widget:"data-chip"},{key:"onSuccess",label:`$t:${ce}.api_call.param_on_success`,widget:"action-list"},{key:"onError",label:`$t:${ce}.api_call.param_on_error`,widget:"action-list"}],build:{handler:"apiCall",target:"{{target}}",identity_target:{email:"{{identity_target_email}}",phone:"{{identity_target_phone}}"},onSuccess:"{{onSuccess}}",onError:"{{onError}}",params:{method:"{{method}}",body:"{{body}}",query:"{{query}}"}}},conditions:{label:`$t:${ce}.conditions.label`,params:[{key:"branches",label:`$t:${ce}.conditions.param_branches`,widget:"branch-list"}],build:{handler:"conditions",conditions:"{{branches}}"}},sequence:{label:`$t:${ce}.sequence.label`,params:[{key:"actions",label:`$t:${ce}.sequence.param_actions`,widget:"action-list"}],build:{handler:"sequence",params:{actions:"{{actions}}"}}},parallel:{label:`$t:${ce}.parallel.label`,params:[{key:"actions",label:`$t:${ce}.parallel.param_actions`,widget:"action-list"}],build:{handler:"parallel",params:{actions:"{{actions}}"}}},switch:{label:`$t:${ce}.switch.label`,params:[{key:"value",label:`$t:${ce}.switch.param_value`,widget:"data-chip"},{key:"cases",label:`$t:${ce}.switch.param_cases`,widget:"action-list",advanced:!0}],build:{handler:"switch",params:{value:"{{value}}",cases:"{{cases}}"}}},suppress:{label:`$t:${ce}.suppress.label`,params:[],build:{handler:"suppress"}}};function wD(){return{actionRecipes:bn,initActionRecipes:bn,errorRecipes:{navigate:bn.navigate,openModal:bn.openModal,toast:bn.toast,setState:bn.setState,sequence:bn.sequence,parallel:bn.parallel,showErrorPage:{label:`$t:${ce}.show_error_page.label`,params:[{key:"target",label:`$t:${ce}.show_error_page.param_target`,widget:"select",options:[{value:"content"},{value:"full"}]}],build:{handler:"showErrorPage",params:{target:"{{target}}"}}}}}}function Qa(e,t){return typeof e.label=="string"?e.label.startsWith("$t:")?t(e.label.slice(3)):e.label:String(e.value)}function vi(e){return Array.isArray(e.options)?e.options:[]}function kD({control:e,value:t,onChange:n,t:o}){const r=vi(e);return i.jsx("div",{className:"g7le-widget g7le-widget--segmented","data-testid":"g7le-widget-segmented",style:LD,children:r.map(s=>{const a=s.value===t;return i.jsx("button",{type:"button","data-testid":`g7le-segment-${String(s.value)}`,"data-active":a?"true":"false",onClick:()=>n(a?void 0:s.value),style:{...KD,background:a?"#2563eb":"#fff",color:a?"#fff":"#0f172a",borderColor:a?"#2563eb":"#cbd5e1"},children:Qa(s,o)},String(s.value))})})}function SD({control:e,value:t,onChange:n,t:o}){const r=Array.isArray(e.scale)?e.scale:[],s=r.findIndex(l=>l===t),a=t!=null;return i.jsxs("div",{className:"g7le-widget g7le-widget--slider","data-testid":"g7le-widget-slider",style:Ig,children:[i.jsxs("label",{style:Ra,children:[i.jsx("input",{type:"checkbox","data-testid":"g7le-slider-enabled",checked:a,onChange:l=>{l.target.checked?n(r.length>0?r[Math.max(0,s===-1?0:s)]:void 0):n(void 0)}}),i.jsx("span",{style:{fontSize:12,color:"#64748b"},children:o("layout_editor.control.use")})]}),i.jsx("input",{type:"range","data-testid":"g7le-slider-range",min:0,max:Math.max(0,r.length-1),step:1,disabled:!a||r.length===0,value:s===-1?0:s,onChange:l=>{const d=Number(l.target.value);n(r[d])},style:{flex:1}}),i.jsx("span",{"data-testid":"g7le-slider-value",style:{fontSize:12,color:"#0f172a",minWidth:48,textAlign:"right"},children:a?String(t):o("layout_editor.control.default")})]})}function CD({control:e,value:t,onChange:n,t:o}){const r=vi(e);return i.jsxs("select",{className:"g7le-widget g7le-widget--select","data-testid":"g7le-widget-select",value:t==null?"":String(t),onChange:s=>{const a=s.target.value;if(a===""){n(void 0);return}const l=r.find(d=>String(d.value)===a);n(l?l.value:a)},style:VD,children:[i.jsx("option",{value:"",children:o("layout_editor.control.default")}),r.map(s=>i.jsx("option",{value:String(s.value),children:Qa(s,o)},String(s.value)))]})}function $D({control:e,value:t,onChange:n}){const o=vi(e),r=o[1]?.value??!0,s=o[0]?.value??void 0,a=t===r;return i.jsx("button",{type:"button",className:"g7le-widget g7le-widget--toggle","data-testid":"g7le-widget-toggle",role:"switch","aria-checked":a,onClick:()=>n(a?s:r),style:{...UD,background:a?"#2563eb":"#cbd5e1"},children:i.jsx("span",{style:{...qD,transform:a?"translateX(18px)":"translateX(0)"}})})}function ED({control:e,value:t,onChange:n,t:o,freeValueDisabled:r}){const s=vi(e),a=t==null?"":String(t),[l,d]=u.useState(a);u.useEffect(()=>{d(a)},[a]);const c=p=>{const f=p.trim();if(f===""){n(void 0);return}n(f)};return i.jsxs("div",{className:"g7le-widget g7le-widget--dimension","data-testid":"g7le-widget-dimension",style:PD,children:[r?i.jsx("div",{"data-testid":"g7le-dimension-free-disabled",style:HD,children:o("layout_editor.property_modal.dark_preset_only")}):i.jsxs("div",{style:OD,children:[i.jsx("input",{type:"text","data-testid":"g7le-dimension-input",value:l,placeholder:o("layout_editor.control.dimension.placeholder"),onChange:p=>d(p.target.value),onBlur:p=>c(p.target.value),onKeyDown:p=>{p.key==="Enter"&&(p.preventDefault(),c(p.target.value))},style:BD}),i.jsx("button",{type:"button","data-testid":"g7le-dimension-clear",title:o("layout_editor.control.default"),onClick:()=>{d(""),n(void 0)},style:WD,children:o("layout_editor.control.default")})]}),s.length>0&&i.jsx("div",{style:jD,"data-testid":"g7le-dimension-chips",children:s.map(p=>{const f=String(p.value),y=f===a;return i.jsx("button",{type:"button","data-testid":`g7le-dimension-chip-${f}`,"data-active":y?"true":"false",onClick:()=>{d(f),n(f)},style:{...FD,background:y?"#2563eb":"#fff",color:y?"#fff":"#0f172a",borderColor:y?"#2563eb":"#cbd5e1"},children:Qa(p,o)},f)})})]})}function ID(e){return[{key:"t",infix:`${e}t-`,labelKey:"layout_editor.control.spacing.top"},{key:"r",infix:`${e}r-`,labelKey:"layout_editor.control.spacing.right"},{key:"b",infix:`${e}b-`,labelKey:"layout_editor.control.spacing.bottom"},{key:"l",infix:`${e}l-`,labelKey:"layout_editor.control.spacing.left"}]}function AD(e,t,n,o){const r={all:-1,sides:{}};if(typeof e!="string"||e.trim()==="")return r;const s=e.split(/\s+/).filter(a=>a.length>0);for(const a of s){const l=n.find(d=>a.startsWith(d.infix));if(l){r.sides[l.key]=o.indexOf(a.slice(l.infix.length));continue}if(a.startsWith(`${t}x-`)){const d=o.indexOf(a.slice(`${t}x-`.length));r.sides.l=d,r.sides.r=d;continue}if(a.startsWith(`${t}y-`)){const d=o.indexOf(a.slice(`${t}y-`.length));r.sides.t=d,r.sides.b=d;continue}a.startsWith(`${t}-`)&&(r.all=o.indexOf(a.slice(`${t}-`.length)))}return r}function TD({control:e,value:t,onChange:n,t:o}){const r=typeof e.spacingPrefix=="string"?e.spacingPrefix:"p",s=(Array.isArray(e.scale)?e.scale:[]).map(b=>String(b)),a=ID(r),l=AD(t,r,a,s),d=Object.values(l.sides).some(b=>b>=0),c=l.all>=0||d,[p,f]=u.useState(d);u.useEffect(()=>{d&&f(!0)},[d]);const y=Math.min(4,Math.max(0,s.length-1)),g=b=>{const x=[];for(const k of a){const w=b[k.key];w!==void 0&&w>=0&&x.push(`${k.infix}${s[w]}`)}n(x.length>0?x.join(" "):void 0)},m=b=>{n(b>=0?`${r}-${s[Math.max(0,Math.min(b,s.length-1))]}`:void 0)},h=()=>({...l.sides}),v=(b,x,k,w,_)=>{const S=k>=0;return i.jsxs("div",{style:MD,"data-testid":b,children:[i.jsxs("label",{style:{...Ra,minWidth:64},children:[i.jsx("input",{type:"checkbox","data-testid":`${b}-enabled`,checked:S,onChange:E=>_(E.target.checked)}),i.jsx("span",{style:{fontSize:12,color:"#0f172a"},children:o(x)})]}),i.jsx("input",{type:"range","data-testid":`${b}-range`,min:0,max:Math.max(0,s.length-1),step:1,disabled:!S||s.length===0,value:k<0?0:k,onChange:E=>w(Number(E.target.value)),style:{flex:1}}),i.jsx("span",{"data-testid":`${b}-value`,style:{fontSize:12,color:S?"#0f172a":"#94a3b8",minWidth:28,textAlign:"right"},children:S?s[k]:"–"})]},b)};return i.jsxs("div",{className:"g7le-widget g7le-widget--spacing","data-testid":"g7le-widget-spacing",style:DD,children:[i.jsxs("div",{style:ND,children:[i.jsxs("div",{style:zD,"data-testid":"g7le-spacing-mode",children:[i.jsx("button",{type:"button","data-testid":"g7le-spacing-mode-all","data-active":p?"false":"true",onClick:()=>{f(!1),d&&n(void 0)},style:{...Eg,background:p?"#fff":"#2563eb",color:p?"#0f172a":"#fff",borderColor:p?"#cbd5e1":"#2563eb"},children:o("layout_editor.control.spacing.mode_all")}),i.jsx("button",{type:"button","data-testid":"g7le-spacing-mode-sides","data-active":p?"true":"false",onClick:()=>{if(f(!0),l.all>=0){const b={};for(const x of a)b[x.key]=l.all;g(b)}},style:{...Eg,background:p?"#2563eb":"#fff",color:p?"#fff":"#0f172a",borderColor:p?"#2563eb":"#cbd5e1"},children:o("layout_editor.control.spacing.mode_sides")})]}),i.jsx("span",{"data-testid":"g7le-spacing-value",style:{fontSize:11,color:"#64748b",minWidth:80,textAlign:"right"},children:c?String(t):o("layout_editor.control.default")})]}),p?i.jsx("div",{"data-testid":"g7le-spacing-sides",style:{display:"flex",flexDirection:"column",gap:4},children:a.map(b=>v(`g7le-spacing-side-${b.key}`,b.labelKey,l.sides[b.key]??-1,x=>{const k=h();k[b.key]=x,g(k)},x=>{const k=h();x?k[b.key]=l.sides[b.key]>=0?l.sides[b.key]:y:delete k[b.key],g(k)}))}):i.jsxs("div",{style:Ig,children:[i.jsxs("label",{style:{...Ra,minWidth:64},children:[i.jsx("input",{type:"checkbox","data-testid":"g7le-spacing-all-enabled",checked:l.all>=0,onChange:b=>m(b.target.checked?y:-1)}),i.jsx("span",{style:{fontSize:12,color:"#64748b"},children:o("layout_editor.control.spacing.all")})]}),i.jsx("input",{type:"range","data-testid":"g7le-spacing-all-range",min:0,max:Math.max(0,s.length-1),step:1,disabled:l.all<0||s.length===0,value:l.all<0?0:l.all,onChange:b=>m(Number(b.target.value)),style:{flex:1}}),i.jsx("span",{"data-testid":"g7le-spacing-all-value",style:{fontSize:12,color:l.all>=0?"#0f172a":"#94a3b8",minWidth:28,textAlign:"right"},children:l.all>=0?s[l.all]:"–"})]})]})}const DD={display:"flex",flexDirection:"column",gap:6,width:"100%"},ND={display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},zD={display:"inline-flex",gap:0,border:"1px solid #cbd5e1",borderRadius:6,overflow:"hidden"},Eg={padding:"3px 10px",fontSize:11,border:"none",borderRight:"1px solid #e2e8f0",cursor:"pointer"},MD={display:"flex",alignItems:"center",gap:8,width:"100%"},LD={display:"inline-flex",gap:0,border:"1px solid #cbd5e1",borderRadius:6,overflow:"hidden"},PD={display:"flex",flexDirection:"column",gap:6,width:"100%"},OD={display:"flex",gap:6,alignItems:"center"},BD={flex:1,padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,minWidth:80},WD={padding:"4px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#64748b",cursor:"pointer",whiteSpace:"nowrap"},jD={display:"flex",flexWrap:"wrap",gap:4},HD={fontSize:11,color:"#94a3b8",fontStyle:"italic",padding:"2px 0"},FD={padding:"3px 9px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:999,background:"#fff",cursor:"pointer"},KD={padding:"4px 10px",fontSize:12,border:"none",borderRight:"1px solid #e2e8f0",cursor:"pointer"},Ig={display:"flex",alignItems:"center",gap:8,width:"100%"},Ra={display:"inline-flex",alignItems:"center",gap:4},VD={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",minWidth:120},UD={position:"relative",width:38,height:20,borderRadius:10,border:"none",cursor:"pointer",padding:2,display:"inline-flex",alignItems:"center",transition:"background 120ms ease"},qD={display:"block",width:16,height:16,borderRadius:8,background:"#fff",transition:"transform 120ms ease"},GD=["#0f172a","#334155","#64748b","#94a3b8","#e2e8f0","#ffffff","#dc2626","#ea580c","#d97706","#16a34a","#0891b2","#2563eb","#7c3aed","#db2777"],Ag=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;function YD(e){return Array.isArray(e.options)?e.options.filter(t=>typeof t.value=="string").map(t=>({value:t.value,swatch:typeof t.swatch=="string"?t.swatch:void 0,label:typeof t.label=="string"?t.label:void 0})):[]}function XD({control:e,value:t,onChange:n,t:o,freeValueDisabled:r}){const s=YD(e),a=s.length>0,l=typeof t=="string"&&s.some(g=>g.value===t)?t:"",d=typeof t=="string"&&Ag.test(t)?t:"",[c,p]=u.useState(d);u.useEffect(()=>{p(d)},[d]);const f=g=>{const m=g.trim();if(m===""){n(void 0);return}const h=m.startsWith("#")?m:`#${m}`;Ag.test(h)&&n(h)},y=GD;return i.jsxs("div",{className:"g7le-widget g7le-widget--color","data-testid":"g7le-widget-color",style:JD,children:[r?i.jsx("div",{"data-testid":"g7le-color-free-disabled",style:nN,children:o("layout_editor.property_modal.dark_preset_only")}):i.jsxs("div",{style:ZD,children:[i.jsxs("label",{style:QD,children:[i.jsx("span",{"data-testid":"g7le-color-swatch",style:{...RD,background:d||"transparent",backgroundImage:d?void 0:"linear-gradient(45deg,#e2e8f0 25%,transparent 25%,transparent 75%,#e2e8f0 75%),linear-gradient(45deg,#e2e8f0 25%,#fff 25%,#fff 75%,#e2e8f0 75%)",backgroundSize:"8px 8px",backgroundPosition:"0 0, 4px 4px"}}),i.jsx("input",{type:"color","data-testid":"g7le-color-native",value:d||"#000000",onChange:g=>n(g.target.value),style:{width:0,height:0,opacity:0,position:"absolute"}})]}),i.jsx("input",{type:"text","data-testid":"g7le-color-hex",value:c,placeholder:o("layout_editor.control.color_hex_placeholder"),onChange:g=>p(g.target.value),onBlur:g=>f(g.target.value),onKeyDown:g=>{g.key==="Enter"&&f(g.target.value)},style:eN}),i.jsx("button",{type:"button","data-testid":"g7le-color-clear",onClick:()=>n(void 0),style:tN,children:o("layout_editor.control.default")})]}),a?i.jsx("div",{style:Tg,"data-testid":"g7le-color-token-presets",children:s.map(g=>{const m=l===g.value,h=g.label?g.label.startsWith("$t:")?o(g.label.slice(3)):g.label:g.value;return i.jsx("button",{type:"button","aria-label":h,title:h,"data-testid":`g7le-color-token-${g.value}`,"data-active":m?"true":"false",onClick:()=>n(m?void 0:g.value),style:{...Dg,background:g.swatch||"#e2e8f0",outline:m?"2px solid #2563eb":"none"}},g.value)})}):!r&&i.jsx("div",{style:Tg,"data-testid":"g7le-color-presets",children:y.map(g=>i.jsx("button",{type:"button","aria-label":g,"data-testid":`g7le-color-preset-${g}`,onClick:()=>n(g),style:{...Dg,background:g,outline:d.toLowerCase()===g.toLowerCase()?"2px solid #2563eb":"none"}},g))})]})}const JD={display:"flex",flexDirection:"column",gap:8},ZD={display:"flex",alignItems:"center",gap:6},QD={position:"relative",display:"inline-flex",cursor:"pointer"},RD={width:24,height:24,borderRadius:4,border:"1px solid #cbd5e1",display:"inline-block"},eN={flex:1,padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,fontFamily:"monospace"},tN={padding:"4px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",cursor:"pointer",color:"#64748b"},Tg={display:"grid",gridTemplateColumns:"repeat(7, 1fr)",gap:4},Dg={width:"100%",height:18,borderRadius:4,border:"1px solid #cbd5e1",cursor:"pointer",padding:0},nN={fontSize:11,color:"#94a3b8",fontStyle:"italic",padding:"2px 0"},Zo=[{value:"fill",labelKey:"layout_editor.control.background_image.mode_fill",size:"cover",repeat:"no-repeat"},{value:"fit",labelKey:"layout_editor.control.background_image.mode_fit",size:"contain",repeat:"no-repeat"},{value:"tile",labelKey:"layout_editor.control.background_image.mode_tile",size:"auto",repeat:"repeat"}];function oN(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Ng(e){return Zo.find(n=>n.size===e.size&&n.repeat===e.repeat)?.value??"fill"}function rN({value:e,onChange:t,t:n}){const o=oN(e),{state:r}=Je(),s=yo(),[a,l]=u.useState(!1),[d,c]=u.useState(null),[p,f]=u.useState(o.url??""),[y,g]=u.useState([]),m=u.useRef(null),h=r.templateIdentifier,v=r.selectedRoute?.layoutName??"";u.useEffect(()=>{f(o.url??"")},[o.url]);const b=u.useCallback(async()=>{if(!h||!v){g([]);return}const E=await Dl(h,v);E.ok&&g(E.data)},[h,v]);u.useEffect(()=>{b()},[b]);const x=E=>{if(!E){t(void 0);return}const C=Zo.find(N=>N.value===Ng(o))??Zo[0];t({url:E,size:o.size??C.size,repeat:o.repeat??C.repeat,position:o.position??"center"})},k=E=>{const C=Zo.find(N=>N.value===E);!C||!o.url||t({url:o.url,size:C.size,repeat:C.repeat,position:o.position??"center"})},w=async E=>{const C=E.target.files?.[0];if(!C)return;l(!0),c(null);const N=await Nl(h,v,C);N.ok?(x(N.data.url),b()):c(n("layout_editor.control.background_image.upload_failed")),l(!1),m.current&&(m.current.value="")},_=async E=>{(await zl(E.id)).ok&&g(N=>N.filter($=>$.id!==E.id))},S=()=>{const E=s.open({ariaLabel:n("layout_editor.attachment_manager.title"),width:720,maxHeightRatio:.82,content:u.createElement(Ml,{templateIdentifier:h,layoutName:v,t:n,onSelect:C=>{x(C),s.close(E)},onChanged:()=>{b()},onClose:()=>s.close(E)})})};return i.jsxs("div",{className:"g7le-widget g7le-widget--image","data-testid":"g7le-widget-image",style:iN,children:[o.url&&i.jsx("div",{"data-testid":"g7le-image-preview",style:{...sN,backgroundImage:`url(${o.url})`,backgroundSize:o.size??"cover",backgroundRepeat:o.repeat??"no-repeat",backgroundPosition:o.position??"center"}}),i.jsxs("div",{style:aN,children:[i.jsxs("label",{style:lN,children:[a?"…":n("layout_editor.control.background_image.upload"),i.jsx("input",{ref:m,type:"file",accept:"image/*","data-testid":"g7le-image-file",onChange:w,disabled:a,style:{display:"none"}})]}),i.jsx("button",{type:"button","data-testid":"g7le-image-clear",onClick:()=>t(void 0),style:dN,children:n("layout_editor.control.background_image.clear")})]}),i.jsx("input",{type:"text","data-testid":"g7le-image-url",placeholder:"https://… / URL",value:p,onChange:E=>f(E.target.value),onBlur:E=>x(E.target.value.trim()||void 0),style:cN}),i.jsx("div",{style:uN,"data-testid":"g7le-image-modes",children:Zo.map(E=>{const C=Ng(o)===E.value;return i.jsx("button",{type:"button","data-testid":`g7le-image-mode-${E.value}`,"data-active":C?"true":"false",disabled:!o.url,onClick:()=>k(E.value),style:{...pN,background:C&&o.url?"#2563eb":"#fff",color:C&&o.url?"#fff":"#0f172a"},children:n(E.labelKey)},E.value)})}),i.jsxs("div",{style:fN,"data-testid":"g7le-image-gallery",children:[i.jsxs("div",{style:gN,children:[i.jsx("span",{style:{fontSize:11,color:"#64748b"},children:n("layout_editor.attachment_manager.recent")}),i.jsxs("button",{type:"button","data-testid":"g7le-image-manage",onClick:S,style:hN,children:["🖼 ",n("layout_editor.attachment_manager.manage_link")]})]}),y.length>0?i.jsx("div",{style:yN,"data-testid":"g7le-image-thumbs",children:y.slice(0,8).map(E=>i.jsxs("div",{style:bN,"data-testid":`g7le-image-thumb-${E.id}`,children:[i.jsx("button",{type:"button",title:E.original_name,onClick:()=>x(E.url),style:{...mN,backgroundImage:`url(${E.url})`},"data-testid":`g7le-image-thumb-use-${E.id}`}),i.jsx("button",{type:"button",title:n("layout_editor.attachment_manager.delete"),onClick:()=>_(E),style:vN,"data-testid":`g7le-image-thumb-del-${E.id}`,children:"✕"})]},E.id))}):i.jsx("span",{style:{fontSize:11,color:"#94a3b8"},children:n("layout_editor.attachment_manager.empty")})]}),d&&i.jsx("span",{"data-testid":"g7le-image-error",style:{fontSize:11,color:"#dc2626"},children:d})]})}const iN={display:"flex",flexDirection:"column",gap:6},sN={width:"100%",height:80,borderRadius:6,border:"1px solid #cbd5e1"},aN={display:"flex",gap:6},lN={padding:"5px 10px",fontSize:12,border:"1px solid #2563eb",borderRadius:6,background:"#fff",color:"#2563eb",cursor:"pointer",display:"inline-flex",alignItems:"center"},dN={padding:"5px 10px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#64748b",cursor:"pointer"},cN={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6},uN={display:"inline-flex",border:"1px solid #cbd5e1",borderRadius:6,overflow:"hidden"},pN={padding:"4px 10px",fontSize:12,border:"none",borderRight:"1px solid #e2e8f0",cursor:"pointer"},fN={display:"flex",flexDirection:"column",gap:4,border:"1px solid #e2e8f0",borderRadius:6,padding:6,marginTop:2},gN={display:"flex",alignItems:"center",justifyContent:"space-between"},hN={fontSize:11,color:"#2563eb",background:"transparent",border:"none",cursor:"pointer",padding:0},yN={display:"flex",gap:6,flexWrap:"wrap"},bN={position:"relative",width:44,height:44},mN={width:44,height:44,borderRadius:6,border:"1px solid #cbd5e1",backgroundSize:"cover",backgroundPosition:"center",cursor:"pointer",padding:0},vN={position:"absolute",top:-6,right:-6,width:16,height:16,borderRadius:"50%",border:"none",background:"#dc2626",color:"#fff",fontSize:9,lineHeight:"16px",cursor:"pointer",padding:0};function _N(e){return Array.isArray(e)&&e.every(t=>t!==null&&typeof t=="object"&&!Array.isArray(t))}function xN(e){return typeof e=="string"&&/\{\{.*\}\}/.test(e)}function wN({value:e,onChange:t,t:n,bindingCandidates:o}){if(xN(e))return i.jsx("div",{className:"g7le-widget g7le-widget--options-list","data-testid":"g7le-widget-options-list-bound",style:TN,children:n("layout_editor.list_editor.bound_degraded")});const r=_N(e)?e:[],s=y=>{t(y.length===0?void 0:y)},a=(y,g)=>{const m=r.map((h,v)=>v===y?{...h,...g}:h);s(m)},l=y=>{s(r.filter((g,m)=>m!==y))},d=(y,g)=>{const m=y+g;if(m<0||m>=r.length)return;const h=[...r];[h[y],h[m]]=[h[m],h[y]],s(h)},c=()=>{s([...r,{value:"",label:""}])},p=y=>typeof y.label=="string"?y.label:y.label==null?"":String(y.label),f=y=>y.value===void 0||y.value===null?"":String(y.value);return i.jsxs("div",{className:"g7le-widget g7le-widget--options-list","data-testid":"g7le-widget-options-list",style:kN,children:[r.length===0&&i.jsx("div",{"data-testid":"g7le-options-empty",style:AN,children:n("layout_editor.list_editor.empty")}),r.map((y,g)=>i.jsxs("div",{"data-testid":`g7le-options-row-${g}`,style:SN,children:[i.jsxs("div",{style:zg,children:[i.jsx("span",{style:Mg,children:n("layout_editor.list_editor.option_value")}),i.jsx("input",{type:"text","data-testid":`g7le-options-value-${g}`,value:f(y),placeholder:n("layout_editor.list_editor.option_value"),onChange:m=>a(g,{value:m.target.value}),style:$N})]}),i.jsxs("div",{style:zg,children:[i.jsx("span",{style:Mg,children:n("layout_editor.list_editor.option_label")}),i.jsx("div",{"data-testid":`g7le-options-label-${g}`,style:{flex:1,minWidth:0},children:i.jsx(vt,{value:p(y),onChange:m=>a(g,{label:m??""}),t:n,placeholder:n("layout_editor.list_editor.option_label"),testidPrefix:`g7le-options-label-i18n-${g}`,candidates:o,enableExpressionTree:!0,expressionTreeCollapsible:!0})})]}),i.jsxs("div",{style:CN,children:[i.jsx("button",{type:"button","data-testid":`g7le-options-up-${g}`,title:n("layout_editor.list_editor.move_up"),disabled:g===0,onClick:()=>d(g,-1),style:Lg,children:"↑"}),i.jsx("button",{type:"button","data-testid":`g7le-options-down-${g}`,title:n("layout_editor.list_editor.move_down"),disabled:g===r.length-1,onClick:()=>d(g,1),style:Lg,children:"↓"}),i.jsx("button",{type:"button","data-testid":`g7le-options-remove-${g}`,title:n("layout_editor.list_editor.remove"),onClick:()=>l(g),style:EN,children:"✕"})]})]},g)),i.jsx("button",{type:"button","data-testid":"g7le-options-add",onClick:c,style:IN,children:n("layout_editor.list_editor.add")})]})}const kN={display:"flex",flexDirection:"column",gap:8,width:"100%"},SN={display:"flex",flexDirection:"column",gap:4,width:"100%",minWidth:0,paddingBottom:6,borderBottom:"1px solid #f1f5f9"},zg={display:"flex",gap:6,alignItems:"center",width:"100%",minWidth:0},Mg={flexShrink:0,width:36,fontSize:11,color:"#94a3b8",textAlign:"right"},CN={display:"flex",gap:4,alignItems:"center",justifyContent:"flex-end"},$N={flex:1,minWidth:0,padding:"4px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6},Lg={padding:"2px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},EN={padding:"2px 6px",fontSize:12,border:"1px solid #fecaca",borderRadius:6,background:"#fff",color:"#dc2626",cursor:"pointer"},IN={padding:"4px 8px",fontSize:12,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",alignSelf:"flex-start"},AN={fontSize:11,color:"#94a3b8",fontStyle:"italic"},TN={fontSize:11,color:"#b45309",fontStyle:"italic",padding:"4px 2px"},Pg=/[^A-Za-z0-9\-_:.]/g;function DN(e){return typeof e=="string"&&Ui(e)}function Og(e){return Ui(e)?In(e).map(t=>t.kind==="binding"?t.raw:t.raw.replace(Pg,"")).join(""):e.replace(Pg,"")}const NN={width:"100%",padding:"6px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:4,fontFamily:"monospace"},zN={marginTop:4,fontSize:11,color:"#94a3b8"},MN={display:"flex",gap:6,alignItems:"center"},LN={flexShrink:0,padding:"5px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:4,background:"#f8fafc",cursor:"pointer",whiteSpace:"nowrap"};function PN({value:e,onChange:t,t:n,bindingCandidates:o}){const r=e==null?"":String(e),s=DN(e),a=!!o&&o.length>0,[l,d]=u.useState(!1),c=p=>{const f=Og(p);t(f===""?void 0:f)};return s||l?i.jsxs("div",{"data-testid":"g7le-core-id-chip",children:[i.jsx(bs,{value:r,onChange:c,t:n,candidates:o,onDone:()=>d(!1),testidPrefix:"g7le-core-id-chip-input"}),i.jsx("div",{style:zN,children:n("layout_editor.core_props.id.binding_hint")})]}):i.jsx("div",{children:i.jsxs("div",{style:MN,children:[i.jsx("input",{type:"text",className:"g7le-widget g7le-widget--core-id","data-testid":"g7le-widget-core-id",value:r,onChange:p=>{const f=Og(p.target.value);t(f===""?void 0:f)},spellCheck:!1,autoComplete:"off",style:NN}),a&&i.jsxs("button",{type:"button","data-testid":"g7le-core-id-add-data",onClick:()=>d(!0),style:LN,title:n("layout_editor.core_props.id.add_data"),children:["🔗 ",n("layout_editor.core_props.id.add_data")]})]})})}const ON=/[^A-Za-z0-9.\-_]/g;function BN(e){return typeof e=="string"&&/\{\{[\s\S]*?\}\}/.test(e)}function WN(e){return e.replace(ON,"")}const Bg={width:"100%",padding:"6px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:4,fontFamily:"monospace",boxSizing:"border-box"},jN={...Bg,background:"#f1f5f9",color:"#64748b",cursor:"not-allowed"},Wg={marginTop:4,fontSize:11,color:"#94a3b8"};function HN({value:e,onChange:t,t:n}){const o=e==null?"":String(e);return BN(e)?i.jsxs("div",{"data-testid":"g7le-core-datakey-bound",children:[i.jsx("input",{type:"text",className:"g7le-widget g7le-widget--core-datakey-bound","data-testid":"g7le-widget-core-datakey",value:o,readOnly:!0,disabled:!0,style:jN}),i.jsx("div",{style:Wg,children:n("layout_editor.core_props.dataKey.bound_degraded")})]}):i.jsxs("div",{children:[i.jsx("input",{type:"text",className:"g7le-widget g7le-widget--core-datakey","data-testid":"g7le-widget-core-datakey",value:o,placeholder:n("layout_editor.core_props.dataKey.placeholder"),onChange:s=>{const a=WN(s.target.value);t(a===""?void 0:a)},spellCheck:!1,autoComplete:"off",style:Bg}),i.jsx("div",{style:Wg,children:n("layout_editor.core_props.dataKey.hint")})]})}let jg=!1;function FN(){jg||(Xe("segmented",kD),Xe("slider",SD),Xe("select",CD),Xe("dimension",ED),Xe("spacing",TD),Xe("toggle",$D),Xe("color",XD),Xe("image",rN),Xe("tag-input",ys),Xe("page-picker",$w),Xe("datasource-picker",Oc),Xe("binding-picker",Oc),Xe("binding-list",Aw),Xe("state-key-picker",Es),Xe("modal-picker",Ew),Xe("i18n-text",Iw),Xe("text",Tw),Xe("options-list",wN),Xe("core-id",PN),Xe("core-datakey",HN),Xe("component-target-picker",PT),jg=!0)}function Qo(e){return Array.isArray(e.children)?e.children:[]}function Ro(e){if(typeof e.text=="string")return[];let t=null;const n=(o,r)=>{const s=Qo(o);for(let a=0;ad===o?er(l,r,n):l);return{...e,children:a}}function Hg(e,t){const n=r=>typeof r.props?.[t]=="string";if(n(e))return[];const o=(r,s)=>{const a=Qo(r);for(let l=0;lc===r?Fg(d,s,n,o):d);return{...e,children:l}}function KN(e){return Array.isArray(e.children)?e.children:[]}function VN(e){const t=e?.itemFields;if(!Array.isArray(t))return[{kind:"text"}];const n=[];for(const o of t){if(!o||typeof o!="object")continue;const r=o;r.kind==="text"?n.push({kind:"text",label:typeof r.label=="string"?r.label:void 0}):r.kind==="prop"&&typeof r.prop=="string"&&r.prop.length>0&&n.push({kind:"prop",prop:r.prop,label:typeof r.label=="string"?r.label:void 0})}return n.length>0?n:[{kind:"text"}]}function el(e,t){if(!(typeof e!="string"||e.length===0))return e.startsWith("$t:")?t(e.slice(3)):e}function Kg({node:e,params:t,spec:n,manifest:o,t:r,onPatchNode:s,templateIdentifier:a,candidates:l}){const d=typeof t?.childComponent=="string"?t.childComponent:null,c=t?.childTemplate&&typeof t.childTemplate=="object"?t.childTemplate:null,p=VN(t),f=el(typeof t?.childLabel=="string"?t.childLabel:void 0,r)??d??"",y=KN(e),g=u.useCallback(_=>{s({...e,children:_})},[e,s]),m=u.useCallback(()=>{if(c)return JSON.parse(JSON.stringify(c));if(!d)return null;const _=n?.componentPalette?.entries?.[d];if(_?.defaultNode&&typeof _.defaultNode=="object")return JSON.parse(JSON.stringify(_.defaultNode));const S=o?.components??{};let E=null;for(const C of Object.values(S))if(Array.isArray(C)){const N=C.find($=>$.name===d);if(N){E=N;break}}return E?kf(E):{type:"basic",name:d}},[c,d,n,o]),h=u.useCallback(()=>{const _=m();if(_){if(_.text==="")_.text=r("layout_editor.list_editor.new_item");else{const S=Ro(_);if(S!==null&&S.length>0){const E=_i(_,S);if(E&&E.text===""){const C=er(_,S,r("layout_editor.list_editor.new_item"));g([...y,C]);return}}}g([...y,_])}},[m,g,y,r]),v=u.useCallback(_=>{g(y.filter((S,E)=>E!==_))},[g,y]),b=u.useCallback((_,S)=>{const E=_+S;if(E<0||E>=y.length)return;const C=[...y];[C[_],C[E]]=[C[E],C[_]],g(C)},[g,y]),x=u.useCallback((_,S)=>{if(typeof S!="string"||S.length===0)return;const E=y[_];if(!E)return;const C=Ro(E);if(C===null)return;const N=y.map(($,A)=>A===_?er($,C,S):$);g(N)},[y,g]),k=u.useCallback((_,S,E)=>{if(typeof E!="string"||E.length===0)return;const C=y[_];if(!C)return;const N=Hg(C,S);if(N===null)return;const $=y.map((A,z)=>z===_?Fg(A,N,S,E):A);g($)},[y,g]);if(!d&&!c)return i.jsx("div",{className:"g7le-node-editor g7le-node-editor--children","data-testid":"g7le-children-editor-misconfigured",style:qg,children:r("layout_editor.list_editor.no_child_component")});const w=p.length>1||p.some(_=>_.label);return i.jsxs("div",{className:"g7le-node-editor g7le-node-editor--children","data-testid":"g7le-children-editor",style:UN,children:[i.jsx("div",{style:qN,children:r("layout_editor.list_editor.items_title")}),y.length===0&&i.jsx("div",{"data-testid":"g7le-children-empty",style:qg,children:r("layout_editor.list_editor.empty")}),y.map((_,S)=>{const E=[];for(const N of p)if(N.kind==="text"){const $=Ro(_),A=$!==null?_i(_,$):null;A&&typeof A.text=="string"&&E.push({key:"text",caption:el(N.label,r)??(w?r("layout_editor.list_editor.item_label"):void 0),value:A.text,onChange:z=>x(S,z),testid:`g7le-children-i18n-${S}`})}else if(N.kind==="prop"&&N.prop){const $=Hg(_,N.prop);if($!==null){const z=_i(_,$)?.props?.[N.prop];E.push({key:`prop-${N.prop}`,caption:el(N.label,r)??N.prop,value:typeof z=="string"?z:"",onChange:D=>k(S,N.prop,D),testid:`g7le-children-prop-${N.prop}-${S}`})}}const C=typeof _?.name=="string"?_.name:r("layout_editor.list_editor.item");return i.jsxs("div",{"data-testid":`g7le-children-row-${S}`,style:GN,children:[E.length>0?E.map(N=>i.jsx("div",{style:Vg,children:i.jsxs("div",{"data-testid":N.key==="text"?`g7le-children-text-${S}`:`g7le-children-field-${N.key}-${S}`,style:YN,children:[N.caption!==void 0&&i.jsx("div",{"data-testid":`g7le-children-caption-${N.key}-${S}`,style:XN,children:N.caption}),i.jsx(vt,{value:N.value,onChange:N.onChange,t:r,placeholder:r("layout_editor.list_editor.item_text"),testidPrefix:N.testid,candidates:l,enableExpressionTree:!0,expressionTreeCollapsible:!0})]})},N.key)):i.jsx("div",{style:Vg,children:i.jsx("span",{"data-testid":`g7le-children-label-${S}`,style:ZN,children:C})}),i.jsxs("div",{style:JN,children:[i.jsx("button",{type:"button","data-testid":`g7le-children-up-${S}`,title:r("layout_editor.list_editor.move_up"),disabled:S===0,onClick:()=>b(S,-1),style:Ug,children:"↑"}),i.jsx("button",{type:"button","data-testid":`g7le-children-down-${S}`,title:r("layout_editor.list_editor.move_down"),disabled:S===y.length-1,onClick:()=>b(S,1),style:Ug,children:"↓"}),i.jsx("button",{type:"button","data-testid":`g7le-children-remove-${S}`,title:r("layout_editor.list_editor.remove"),onClick:()=>v(S),style:QN,children:"✕"})]})]},S)}),i.jsx("button",{type:"button","data-testid":"g7le-children-add",onClick:h,style:RN,children:r("layout_editor.list_editor.add_child",{component:f})})]})}const UN={display:"flex",flexDirection:"column",gap:6,width:"100%",marginBottom:12},qN={fontSize:12,fontWeight:700,color:"#0f172a",marginBottom:2},GN={display:"flex",flexDirection:"column",gap:4,width:"100%",minWidth:0,paddingBottom:6,borderBottom:"1px solid #f1f5f9"},Vg={display:"flex",gap:4,alignItems:"flex-start",width:"100%",minWidth:0},YN={flex:1,minWidth:0},XN={fontSize:11,color:"#64748b",marginBottom:2},JN={display:"flex",gap:4,alignItems:"center",justifyContent:"flex-end"},ZN={flex:1,minWidth:0,padding:"4px 6px",fontSize:12,color:"#475569",fontStyle:"italic",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},Ug={padding:"2px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},QN={padding:"2px 6px",fontSize:12,border:"1px solid #fecaca",borderRadius:6,background:"#fff",color:"#dc2626",cursor:"pointer"},RN={padding:"4px 8px",fontSize:12,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",alignSelf:"flex-start"},qg={fontSize:11,color:"#94a3b8",fontStyle:"italic"},fo={rowContainer:"Tbody",row:"Tr",cell:"Td",headerCell:"Th",colSpanProp:"colSpan",rowSpanProp:"rowSpan"};function ht(e){return{rowContainer:e?.rowContainer??fo.rowContainer,row:e?.row??fo.row,cell:e?.cell??fo.cell,headerCell:e?.headerCell??fo.headerCell,colSpanProp:e?.colSpanProp??fo.colSpanProp,rowSpanProp:e?.rowSpanProp??fo.rowSpanProp}}function Bn(e){return e?Array.isArray(e.children)?e.children:[]:[]}function Gg(e,t){const n=e.props?.[t],o=typeof n=="number"?n:typeof n=="string"?parseInt(n,10):NaN;return Number.isFinite(o)&&o>=1?Math.floor(o):1}function Be(e,t){const n=ht(t),o=[],r=Bn(e),s=[];r.forEach((f,y)=>{(Bn(f).some(h=>h.name===n.row)||f.name===n.rowContainer||f.name==="Thead"||f.name==="Tfoot")&&s.push({container:f,containerIndex:y,isHeader:f.name==="Thead"})}),s.length===0&&r.some(f=>f.name===n.row)&&s.push({container:e,containerIndex:-1,isHeader:!1});const a=[],l=[];let d=0,c=0;const p=f=>{for(;a.length<=f;)a.push([]);return a[f]};s.forEach((f,y)=>{Bn(f.container).filter(m=>m.name===n.row).forEach((m,h)=>{const v=[],b=p(d);let x=0;Bn(m).filter(w=>w.name===n.cell||w.name===n.headerCell).forEach((w,_)=>{for(;b[x];)x++;const S=Gg(w,n.colSpanProp),E=Gg(w,n.rowSpanProp),C={cell:w,sectionIndex:y,rowIndexInSection:h,cellIndexInRow:_,gridRow:d,gridCol:x,colSpan:S,rowSpan:E,isHeader:w.name===n.headerCell};v.push(C);for(let N=0;N=0?(a.push(s.containerIndex),l=Bn(e)[s.containerIndex]??e):l=e;let d=-1,c=-1,p=null;const f=Bn(l);for(let m=0;m=r.gridRow&&t=r.gridCol&&nr){s=!0;break}if(s)break}s||t.add(r)}const n=Array.from(t).sort((r,s)=>r-s),o=[];for(let r=0;re.rows.find(l=>(l.cells[0]?.gridRow??-1)===a)?.sectionIndex??e.rows[a]?.sectionIndex??0,o=new Set([0,t]);for(let a=1;aa){l=!0;break}if(l)break}l||o.add(a)}const r=Array.from(o).sort((a,l)=>a-l),s=[];for(let a=0;at>=a.start&&t=o.length?{ok:!1,reason:"boundary"}:o[r].sectionIndex!==o[s].sectionIndex?{ok:!1,reason:"section"}:{ok:!0}}function wi(e,t,n){const o=Yg(e),r=o.findIndex(a=>t>=a.start&&t=o.length?{ok:!1,reason:"boundary"}:{ok:!0}}function Ge(e){return e?Array.isArray(e.children)?e.children:[]:[]}function mn(e,t,n){const o={...e.props??{}};n<=1?delete o[t]:o[t]=n;const r={...e,props:o};return Object.keys(o).length===0&&delete r.props,r}function ki(e,t,n=!1){const o={type:"basic",name:n?e.headerCell:e.cell},r=t?.props?.className;return typeof r=="string"&&r&&(o.props={className:r}),o.text="",o}function tr(e,t){return e.name===t.cell||e.name===t.headerCell}function nt(e,t,n,o){const r=t.sections[n];if(!r)return e;if(r.containerIndex===-1)return o(e);const s=Ge(e).map((a,l)=>l===r.containerIndex?o(a):a);return{...e,children:s}}function yt(e,t,n,o){let r=-1;const s=Ge(e).map(a=>a.name===t&&(r++,r===n)?o(a):a);return{...e,children:s}}function Si(e,t,n){let o=-1;const r=Ge(e);for(let s=0;s0?nt(e,r,r.sections.length-1,x=>({...x,children:[...Ge(x),b]})):{...e,children:[...Ge(e),b]}}const s=Math.max(-1,Math.min(n,r.rows.length-1)),a=s<0?r.rows[0]:r.rows[s],l=a.cells[0]?.gridRow??s,d=s<0?0:l+1,c=a.sectionIndex,p=s<0?0:a.rowIndexInSection+1,f=[],y=[];let g=0;for(;g0?Ue(r,d-1,g):null;b&&b.gridRow+b.rowSpan>d&&b.rowSpan>1?(y.push(b),g+=b.colSpan):(f.push(ki(o)),g+=1)}let m=e;for(const b of y)m=nt(m,r,b.sectionIndex,x=>yt(x,o.row,b.rowIndexInSection,k=>({...k,children:Ge(k).map((w,_)=>_===b.cellIndexInRow?mn(w,o.rowSpanProp,b.rowSpan+1):w)})));const h={type:"basic",name:o.row,children:f},v=Be(m,t);return m=nt(m,v,c,b=>{const x=Ge(b);let k=0,w=x.length;for(let _=0;_=r.rows.length||r.rows.length<=1)return e;const s=r.rows[n],a=s.cells[0]?.gridRow??n;let l=e;const d=new Set;for(let p=0;pyt(y,o.row,f.rowIndexInSection,g=>({...g,children:Ge(g).map((m,h)=>h===f.cellIndexInRow?mn(m,o.rowSpanProp,f.rowSpan-1):m)})))),p+=f?f.colSpan:1}const c=Be(l,t);return l=nt(l,c,s.sectionIndex,p=>{let f=-1;const y=Ge(p).filter(g=>g.name===o.row?(f++,f!==s.rowIndexInSection):!0);return{...p,children:y}}),l}function Zg(e,t,n,o){const r=ht(t),s=Be(e,t);if(!xi(s,n,o).ok)return e;const a=Xg(s),l=a.findIndex(h=>n>=h.start&&ns.rows.filter(v=>{const b=v.cells[0]?.gridRow??-1;return v.sectionIndex===f&&b>=h.start&&bv.rowIndexInSection),g=y(c),m=y(p);return g.length===0||m.length===0?e:nt(e,s,f,h=>{const v=[...Ge(h)],b=[];v.forEach((M,B)=>{M.name===r.row&&b.push(B)});const x=g.map(M=>b[M]).filter(M=>M!==void 0),k=m.map(M=>b[M]).filter(M=>M!==void 0);if(x.length===0||k.length===0)return h;const w=x.map(M=>v[M]),_=k.map(M=>v[M]),S=Math.min(...x)n>=m.start&&nw.gridCol>=f.start&&w.gridColw.gridCol>=y.start&&w.gridColw.cellIndexInRow),x=v.map(w=>w.cellIndexInRow),k=Be(g,t);g=nt(g,k,m.sectionIndex,w=>yt(w,r.row,m.rowIndexInSection,_=>{const S=[...Ge(_)],E=b.map(M=>Si(_,r,M)).filter(M=>M>=0),C=x.map(M=>Si(_,r,M)).filter(M=>M>=0);if(E.length===0||C.length===0)return _;const N=E.map(M=>S[M]),$=C.map(M=>S[M]),A=Math.min(...E,...C),z=Math.max(...E,...C),D=[...$,...N],O=[...S.slice(0,A),...D,...S.slice(z+1)];return{..._,children:O}}))}return g}function Rg(e,t,n){const o=ht(t),r=Be(e,t);if(r.rows.length===0||r.colCount===0)return nl(e,t,-1);const s=Math.max(0,Math.min(n+1,r.colCount));let a=e;const l=new Set;for(const d of r.rows){const c=d.cells[0]?.gridRow??0,p=s>0?Ue(r,c,s-1):null,f=s1){if(!l.has(p.cell)){l.add(p.cell);const h=Be(a,t);a=nt(a,h,p.sectionIndex,v=>yt(v,o.row,p.rowIndexInSection,b=>({...b,children:Ge(b).map((x,k)=>k===p.cellIndexInRow?mn(x,o.colSpanProp,p.colSpan+1):x)})))}continue}if(p&&p.gridRow0&&d.cells.every(h=>h.isHeader),m=Be(a,t);a=nt(a,m,d.sectionIndex,h=>yt(h,o.row,d.rowIndexInSection,v=>{const b=[...Ge(v)];let x;if(y<0)x=b.findIndex(k=>tr(k,o)),x<0&&(x=b.length);else{const k=Si(v,o,y);x=k<0?b.length:k+1}return b.splice(x,0,ki(o,void 0,g)),{...v,children:b}}))}return a}function eh(e,t,n){const o=ht(t),r=Be(e,t);if(n<0||n>=r.colCount||r.colCount<=1)return e;let s=e;const a=new Set;for(const l of r.rows){const d=l.cells[0]?.gridRow??0,c=Ue(r,d,n);if(!(!c||a.has(c.cell)||c.gridRow1){const p=Be(s,t);s=nt(s,p,c.sectionIndex,f=>yt(f,o.row,c.rowIndexInSection,y=>({...y,children:Ge(y).map((g,m)=>m===c.cellIndexInRow?mn(g,o.colSpanProp,c.colSpan-1):g)})))}else{const p=Be(s,t);s=nt(s,p,c.sectionIndex,f=>yt(f,o.row,c.rowIndexInSection,y=>{let g=-1;const m=Ge(y).filter(h=>tr(h,o)?(g++,g!==c.cellIndexInRow):!0);return{...y,children:m}}))}}return s}function ol(e,t,n,o,r,s){const a=ht(t),l=Be(e,t),d=Math.min(n,r),c=Math.max(n,r),p=Math.min(o,s),f=Math.max(o,s);if(d===c&&p===f)return{table:e,ok:!1,reason:"single"};if(!l.valid)return{table:e,ok:!1,reason:"invalid-grid"};const y=new Set;for(let b=d;b<=c;b++)for(let x=p;x<=f;x++){const k=Ue(l,b,x);if(!k)return{table:e,ok:!1,reason:"hole"};if(k.gridRowc||k.gridCol+k.colSpan-1>f)return{table:e,ok:!1,reason:"not-rectangular"};y.add(k)}const g=Ue(l,d,p),m=Array.from(y).filter(b=>b!==g);let h=nt(e,l,g.sectionIndex,b=>yt(b,a.row,g.rowIndexInSection,x=>({...x,children:Ge(x).map((k,w)=>{if(w!==g.cellIndexInRow)return k;let _=mn(k,a.colSpanProp,f-p+1);return _=mn(_,a.rowSpanProp,c-d+1),_})})));const v=new Map;for(const b of m){const x=`${b.sectionIndex}:${b.rowIndexInSection}`,k=v.get(x)??[];k.push(b),v.set(x,k)}for(const[b,x]of v){const k=parseInt(b.split(":")[0],10),w=x[0].rowIndexInSection,_=new Set(x.map(E=>E.cellIndexInRow)),S=Be(h,t);h=nt(h,S,k,E=>yt(E,a.row,w,C=>{let N=-1;const $=Ge(C).filter(A=>tr(A,a)?(N++,!_.has(N)):!0);return{...C,children:$}}))}return{table:h,ok:!0}}function th(e,t,n,o){const r=ht(t),s=Be(e,t),a=Ue(s,n,o);if(!a||a.colSpan<=1&&a.rowSpan<=1)return e;const l=a.gridRow,d=a.gridCol,c=a.gridRow+a.rowSpan-1,p=a.gridCol+a.colSpan-1,f=a.isHeader,y=typeof a.cell.props?.className=="string"?a.cell.props.className:void 0;let g=nt(e,s,a.sectionIndex,m=>yt(m,r.row,a.rowIndexInSection,h=>({...h,children:Ge(h).map((v,b)=>{if(b!==a.cellIndexInRow)return v;let x=mn(v,r.colSpanProp,1);return x=mn(x,r.rowSpanProp,1),x})})));for(let m=l;m<=c;m++)for(let h=d;h<=p;h++){if(m===l&&h===d)continue;const v=Be(g,t),b=v.rows.find(w=>w.cells.some(_=>_.gridRow===m))??v.rows[m];if(!b)continue;let x=-1;for(const w of b.cells)w.gridRow===m&&w.gridColyt(w,r.row,b.rowIndexInSection,_=>{const S=[...Ge(_)];let E;if(x<0)E=S.findIndex(C=>tr(C,r)),E<0&&(E=S.length);else{const C=Si(_,r,x);E=C<0?S.length:C+1}return S.splice(E,0,ki(r,k,f)),{..._,children:S}}))}return g}function Ci(e,t,n,o,r){const s=ht(t),a=Be(e,t),l=Ue(a,n,o);return l?nt(e,a,l.sectionIndex,d=>yt(d,s.row,l.rowIndexInSection,c=>({...c,children:Ge(c).map((p,f)=>{if(f!==l.cellIndexInRow)return p;const y={...p.props??{}};r.trim()===""?delete y.className:y.className=r;const g={...p,props:y};return Object.keys(y).length===0&&delete g.props,g})}))):e}function Jt(e,t,n,o,r,s){const a=ht(t),l=Be(e,t),d=Ue(l,n,o);return d?nt(e,l,d.sectionIndex,c=>yt(c,a.row,d.rowIndexInSection,p=>({...p,children:Ge(p).map((f,y)=>{if(y!==d.cellIndexInRow)return f;const g={...f.props??{}},m={...g.style??{}};!s||s.trim()===""?delete m[r]:m[r]=s,Object.keys(m).length===0?delete g.style:g.style=m;const h={...f,props:g};return Object.keys(g).length===0&&delete h.props,h})}))):e}function go(e,t,n,o,r,s,a){const l=ht(t),d=Be(e,t),c=Ue(d,n,o);if(!c)return e;const p=a==="dark";return nt(e,d,c.sectionIndex,f=>yt(f,l.row,c.rowIndexInSection,y=>({...y,children:Ge(y).map((g,m)=>{if(m!==c.cellIndexInRow)return g;const h={...g.props??{}},v=typeof h.className=="string"?h.className:"",b=lC(v,s,r,p);b===""?delete h.className:h.className=b;const x={...g,props:h};return Object.keys(h).length===0&&delete x.props,x})})))}function nh(e,t,n,o,r){const s=ht(t),a=Be(e,t),l=Ue(a,n,o);return l?nt(e,a,l.sectionIndex,d=>yt(d,s.row,l.rowIndexInSection,c=>({...c,children:Ge(c).map((p,f)=>f===l.cellIndexInRow?{...p,text:r}:p)}))):e}function oh(e,t,n,o,r){const s=ht(t),a=Be(e,t),l=Ue(a,n,o);return l?nt(e,a,l.sectionIndex,d=>yt(d,s.row,l.rowIndexInSection,c=>({...c,children:Ge(c).map((p,f)=>f===l.cellIndexInRow?r:p)}))):e}const rh=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;function e8(e){return e.split(/\s+/).filter(Boolean)}function ih(e,t){for(const n of t)if(e===n||/^-?\d+$/.test(e.slice(n.length+1))&&e.startsWith(n+"-"))return!0;return!1}function sh({className:e,catalog:t,t:n,onChange:o,colorScheme:r="light",onPresetToken:s,colorStyle:a,onColorStyle:l,disabled:d}){const c=t?.sides??[],p=t?.widths??[],f=t?.colors??[],y=r==="dark",g=u.useMemo(()=>c.map($=>$.prefix),[c]),m=u.useMemo(()=>new Set(f.map($=>$.token)),[f]),h=u.useMemo(()=>e8(e),[e]),v=u.useMemo(()=>Vr(e,y),[e,y]),b=u.useMemo(()=>v.find($=>m.has($))??null,[v,m]),x=u.useMemo(()=>{const $=new Set;for(const A of c)h.some(D=>D===A.prefix||D.startsWith(A.prefix+"-")&&/^-?\d+$/.test(D.slice(A.prefix.length+1)))&&$.add(A.value);return $},[h,c]),k=u.useMemo(()=>{const $=h.find(z=>ih(z,g));if(!$)return"none";const A=p.filter(z=>z.value!=="none");for(const z of c){if($===z.prefix)return A.find(D=>(D.suffix??"")==="")?.value??"thin";if($.startsWith(z.prefix+"-")){const D=$.slice(z.prefix.length),O=A.find(M=>(M.suffix??"")===D);if(O)return O.value}}return"thin"},[h,g,c,p]);if(!t||c.length===0||p.length===0)return null;function w($){return $.filter(A=>!ih(A,g))}function _($,A){const z=w(h),D=p.find(B=>B.value===A);if(!D||A==="none"||$.size===0)return z.join(" ").trim();const O=D.suffix??"",M=[...z];for(const B of c)$.has(B.value)&&M.push(O?`${B.prefix}${O}`:B.prefix);return M.join(" ").trim()}const S=$=>{const A=new Set(x);A.has($)?A.delete($):($==="all"?A.clear():A.delete("all"),A.add($));const z=k==="none"?p.find(D=>D.value!=="none")?.value??"thin":k;o(_(A,z))},E=$=>{const A=x.size===0?new Set(["all"]):x;o(_(A,$))},C=$=>{s?.($)},N=($,A)=>$&&$.startsWith("$t:")?n($.slice(3)):$||A;return i.jsxs("div",{className:"g7le-cell-border","data-testid":"g7le-cell-border",style:t8,children:[i.jsx("div",{style:n8,children:i.jsx("span",{style:o8,children:n("layout_editor.table_editor.cell_border")})}),i.jsx("div",{style:rl,"data-testid":"g7le-cell-border-widths",children:p.map($=>i.jsx("button",{type:"button",disabled:d,"data-testid":`g7le-cell-border-width-${$.value}`,"aria-pressed":k===$.value,onClick:()=>E($.value),style:k===$.value?ah:il,children:N($.label,$.value)},$.value))}),k!=="none"&&i.jsx("div",{style:rl,"data-testid":"g7le-cell-border-sides",children:c.map($=>i.jsx("button",{type:"button",disabled:d,"data-testid":`g7le-cell-border-side-${$.value}`,"aria-pressed":x.has($.value),onClick:()=>S($.value),style:x.has($.value)?ah:il,children:N($.label,$.value)},$.value))}),k!=="none"&&(f.length>0||l)&&i.jsx(i.Fragment,{children:i.jsxs("div",{style:rl,"data-testid":"g7le-cell-border-colors",children:[f.map($=>{const A=b===$.token;return i.jsx("button",{type:"button",disabled:d,title:N($.label,$.value),"data-testid":`g7le-cell-border-color-${$.value}`,"aria-pressed":A,onClick:()=>C($.token),style:{...lh,background:$.swatch??"#fff",outline:A?"2px solid #2563eb":"1px solid #cbd5e1"}},$.value)}),l&&(()=>{const $=!!a&&f.some(z=>z.swatch&&z.swatch.toLowerCase()===a.toLowerCase()),A=!y&&!!a&&!$;return i.jsx("label",{title:n(y?"layout_editor.table_editor.dark_free_color_hint":"layout_editor.table_inplace.custom_color"),"data-testid":"g7le-cell-border-color-custom",style:{...lh,position:"relative",overflow:"hidden",display:"inline-flex",alignItems:"center",justifyContent:"center",background:A&&rh.test(a)?a:"conic-gradient(red, yellow, lime, aqua, blue, magenta, red)",outline:A?"2px solid #2563eb":"1px solid #cbd5e1",opacity:y?.4:1,cursor:y?"not-allowed":"pointer"},children:i.jsx("input",{type:"color",disabled:d||y,"data-testid":"g7le-cell-border-color-picker",value:a&&rh.test(a)?a:"#000000",onChange:z=>l(z.target.value),style:{position:"absolute",width:0,height:0,opacity:0}})})})()]})})]})}const t8={display:"flex",flexDirection:"column",gap:6},n8={display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},o8={fontSize:12,fontWeight:600,color:"#475569"},rl={display:"flex",gap:4,flexWrap:"wrap",alignItems:"center"},il={padding:"3px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},ah={...il,border:"1px solid #2563eb",background:"#eff6ff",color:"#1d4ed8",fontWeight:600},lh={width:22,height:22,borderRadius:5,padding:0,cursor:"pointer",boxSizing:"border-box"},dh=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;function ch({colorStyle:e,className:t,catalog:n,t:o,colorScheme:r="light",onPresetToken:s,onCustomColor:a,onClear:l,disabled:d}){const c=n?.colors??[],p=r==="dark",f=e??"",y=Vr(t??"",p),g=c.find(x=>x.token&&y.includes(x.token))?.token??null,m=(x,k)=>x&&x.startsWith("$t:")?o(x.slice(3)):x||k,h=!g&&(p||f.trim()===""),v=!!f&&c.some(x=>x.swatch&&x.swatch.toLowerCase()===f.toLowerCase()),b=!p&&!!f&&!v;return i.jsxs("div",{className:"g7le-cell-fill","data-testid":"g7le-cell-fill",style:r8,children:[i.jsx("div",{style:i8,children:i.jsx("span",{style:s8,children:o("layout_editor.table_editor.cell_fill")})}),i.jsxs("div",{style:a8,"data-testid":"g7le-cell-fill-colors",children:[i.jsx("button",{type:"button",disabled:d,title:o("layout_editor.table_editor.cell_fill_none"),"data-testid":"g7le-cell-fill-none","aria-pressed":h,onClick:()=>l?.(),style:{...sl,background:"repeating-conic-gradient(#e2e8f0 0% 25%, #ffffff 0% 50%) 50% / 10px 10px",outline:h?"2px solid #2563eb":"1px solid #cbd5e1"}}),c.map(x=>{const k=!!x.token&&g===x.token,w=!p&&!!x.swatch&&f.toLowerCase()===(x.swatch??"").toLowerCase(),_=k||w,S=d||p&&!x.token;return i.jsx("button",{type:"button",disabled:S,title:m(x.label,x.value),"data-testid":`g7le-cell-fill-color-${x.value}`,"aria-pressed":_,onClick:()=>{x.token&&s?s(x.token):!p&&x.swatch&&a&&a(x.swatch)},style:{...sl,background:x.swatch??"#fff",outline:_?"2px solid #2563eb":"1px solid #cbd5e1",opacity:S?.4:1,cursor:S?"not-allowed":"pointer"}},x.value)}),a&&i.jsx("label",{title:o(p?"layout_editor.table_editor.dark_free_color_hint":"layout_editor.table_editor.cell_fill_custom"),"data-testid":"g7le-cell-fill-custom",style:{...sl,position:"relative",overflow:"hidden",display:"inline-flex",alignItems:"center",justifyContent:"center",background:b&&dh.test(f)?f:"conic-gradient(red, yellow, lime, aqua, blue, magenta, red)",outline:b?"2px solid #2563eb":"1px solid #cbd5e1",opacity:p?.4:1,cursor:p?"not-allowed":"pointer"},children:i.jsx("input",{type:"color",disabled:d||p,"data-testid":"g7le-cell-fill-color-picker",value:f&&dh.test(f)?f:"#ffffff",onChange:x=>a(x.target.value),style:{position:"absolute",width:0,height:0,opacity:0}})})]})]})}const r8={display:"flex",flexDirection:"column",gap:6},i8={display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},s8={fontSize:12,fontWeight:600,color:"#475569"},a8={display:"flex",gap:4,flexWrap:"wrap",alignItems:"center"},sl={width:22,height:22,borderRadius:5,padding:0,cursor:"pointer",boxSizing:"border-box"};function l8(e){const t=/^(\d+)px$/.exec(e.trim());return t?parseInt(t[1],10):null}function uh({paddingStyle:e,catalog:t,t:n,onChange:o,disabled:r}){const s=t?.steps??[],a=e??"",l=l8(a),d=(h,v)=>h&&h.startsWith("$t:")?n(h.slice(3)):h||v,c=s.some(h=>(h.px??0)===(l??-1)),p=l!==null&&!c?String(l):"",[f,y]=u.useState(p);u.useEffect(()=>{y(p)},[e]);const g=h=>{o(h&&h>0?`${h}px`:""),y("")},m=h=>{const v=parseInt(h,10);Number.isFinite(v)&&v>=0&&o(v>0?`${v}px`:"")};return i.jsxs("div",{className:"g7le-cell-padding","data-testid":"g7le-cell-padding",style:d8,children:[i.jsx("div",{style:c8,children:n("layout_editor.table_editor.cell_padding")}),i.jsxs("div",{style:u8,"data-testid":"g7le-cell-padding-steps",children:[s.map(h=>{const v=(h.px??0)===(l??-1)||!h.px&&a.trim()==="";return i.jsx("button",{type:"button",disabled:r,"data-testid":`g7le-cell-padding-step-${h.value}`,"aria-pressed":v,onClick:()=>g(h.px),style:v?p8:ph,children:d(h.label,h.value)},h.value)}),i.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:3},children:[i.jsx("input",{type:"number",min:0,disabled:r,"data-testid":"g7le-cell-padding-free",value:f,placeholder:n("layout_editor.table_editor.cell_padding_custom"),onChange:h=>y(h.target.value),onBlur:()=>f.trim()!==""&&m(f),onKeyDown:h=>{h.key==="Enter"&&f.trim()!==""&&m(f)},style:f8}),i.jsx("span",{style:{fontSize:11,color:"#94a3b8"},children:"px"})]})]})]})}const d8={display:"flex",flexDirection:"column",gap:6},c8={fontSize:12,fontWeight:600,color:"#475569"},u8={display:"flex",gap:4,flexWrap:"wrap",alignItems:"center"},ph={padding:"3px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},p8={...ph,border:"1px solid #2563eb",background:"#eff6ff",color:"#1d4ed8",fontWeight:600},f8={width:48,padding:"3px 5px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,boxSizing:"border-box"};function fh({colorScheme:e,onChange:t,t:n,disabled:o}){const r=e==="dark";return i.jsxs("div",{className:"g7le-color-scheme-tabs","data-testid":"g7le-color-scheme-tabs",style:g8,children:[i.jsxs("div",{style:h8,children:[i.jsx("span",{style:y8,children:n("layout_editor.table_editor.cell_color")}),i.jsxs("div",{style:b8,children:[i.jsx("button",{type:"button",disabled:o,"data-testid":"g7le-color-scheme-light","aria-pressed":!r,onClick:()=>t("light"),style:r?al:gh,children:n("layout_editor.property_modal.scope.scheme_light")}),i.jsx("button",{type:"button",disabled:o,"data-testid":"g7le-color-scheme-dark","aria-pressed":r,onClick:()=>t("dark"),style:r?gh:al,children:n("layout_editor.property_modal.scope.scheme_dark")})]})]}),r&&i.jsx("div",{style:m8,"data-testid":"g7le-color-scheme-dark-hint",children:n("layout_editor.table_editor.dark_free_color_hint")})]})}const g8={display:"flex",flexDirection:"column",gap:3},h8={display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},y8={fontSize:12,fontWeight:700,color:"#0f172a"},b8={display:"flex",gap:2},al={padding:"2px 9px",fontSize:11,border:"none",borderBottom:"2px solid transparent",background:"transparent",color:"#94a3b8",cursor:"pointer"},gh={...al,color:"#1d4ed8",borderBottom:"2px solid #2563eb",fontWeight:600},m8={fontSize:10,color:"#94a3b8",fontStyle:"italic"},ll="dark:";function hh(e){return typeof e=="string"?e.split(/\s+/).filter(Boolean):[]}function yh(e,t){return t==="dark"?e.filter(n=>n.startsWith(ll)).map(n=>n.slice(ll.length)):e.filter(n=>!n.startsWith(ll))}const v8={none:0,thin:1,medium:2,thick:4},bh={top:{w:"borderTopWidth",s:"borderTopStyle",c:"borderTopColor"},bottom:{w:"borderBottomWidth",s:"borderBottomStyle",c:"borderBottomColor"},left:{w:"borderLeftWidth",s:"borderLeftStyle",c:"borderLeftColor"},right:{w:"borderRightWidth",s:"borderRightStyle",c:"borderRightColor"}},mh=["top","bottom","left","right"];function _8(e,t,n="light"){if(!e||!t)return{};const o=t.sides??[],r=t.widths??[],s=t.colors??[],a=hh(e.props?.className);if(a.length===0&&!e.props?.style)return{};const l=[...r].filter(b=>b.value!=="none").sort((b,x)=>(x.suffix??"").length-(b.suffix??"").length),d={};for(const b of o)for(const x of l){const k=x.suffix?`${b.prefix}${x.suffix}`:b.prefix;if(a.includes(k)){d[b.value]=x.value;break}}const c=e.props?.style??{},p=yh(a,n),f=s.find(b=>p.includes(b.token))?.swatch??"",g=(n==="light"&&typeof c.borderColor=="string"?c.borderColor:"")||f||"#94a3b8",m=b=>{const x=bh[b]?.c,k=x?c[x]:void 0;return typeof k=="string"&&k?k:g},h={},v=(b,x)=>{const k=bh[b];if(!k)return;const w=v8[x]??1;h[k.w]=`${w}px`,h[k.s]=w>0?"solid":"none",w>0&&(h[k.c]=m(b))};if(d.all)for(const b of mh)v(b,d.all);for(const b of mh)d[b]&&v(b,d[b]);return h}function x8(e,t,n="light"){if(!e?.props)return{};const o=e.props.style??{},r={},s=hh(e.props.className),a=t?.colors?.find(c=>c.token&&yh(s,n).includes(c.token))?.swatch??"",d=(n==="light"&&typeof o.backgroundColor=="string"?o.backgroundColor:"")||a;return d&&(r.backgroundColor=d),typeof o.padding=="string"&&o.padding&&(r.padding=o.padding),r}const w8=/^\s*\$t:(custom\.[a-zA-Z0-9._-]+)\s*$/,k8=/^\s*\$t:([a-zA-Z0-9._-]+)\s*$/,S8=/\{\{.*?\}\}/;function vh(e,t,n){const o=e?.text;if(typeof o!="string")return{display:"",editable:!1,isKey:!1};const r=mt(o);if(r&&r.key.startsWith("custom.")){let a="";try{const l=Pt.getInstance().translate(r.key,{templateId:t,locale:n});a=l&&l!==r.key?l:""}catch{a=""}return{display:a,editable:!0,isKey:!0}}if(S8.test(o))return{display:o,editable:!1,isKey:!1};const s=k8.exec(o);if(s){const a=s[1];let l="";try{const d=Pt.getInstance().translate(a,{templateId:t,locale:n});l=d&&d!==a?d:""}catch{l=""}return{display:l,editable:!0,isKey:!0}}return{display:o,editable:!0,isKey:!1}}function dl(e){const t=Ro(e);return t===null?{node:null,path:null}:{node:_i(e,t),path:t}}function C8(e){if(!e||typeof e.text!="string")return null;const t=w8.exec(e.text);if(t)return t[1];const n=mt(e.text);return n&&n.key.startsWith("custom.")?n.key:null}function $8({node:e,params:t,t:n,onPatchNode:o,templateIdentifier:r,candidates:s}){const{state:a}=Je(),l=a.selectedRoute?.layoutName??null,d=a.locale,c=r??a.templateIdentifier,p=u.useMemo(()=>t&&typeof t=="object"?t:null,[t]);u.useMemo(()=>ht(p),[p]);const f=u.useMemo(()=>Be(e,p),[e,p]),y=u.useMemo(()=>{const q=p?.cellBorder;return q&&typeof q=="object"?q:null},[p]),g=u.useMemo(()=>{const q=p?.cellBackground;return q&&typeof q=="object"?q:null},[p]),m=u.useMemo(()=>{const q=p?.cellPadding;return q&&typeof q=="object"?q:null},[p]),[h,v]=u.useState(null),[b,x]=u.useState(null),[k,w]=u.useState({}),[_,S]=u.useState(!1),[E,C]=u.useState(null),[N,$]=u.useState(null),[A,z]=u.useState("light"),D=u.useCallback(q=>o(q),[o]),O=u.useMemo(()=>h?Ue(f,h.r,h.c):null,[f,h]),M=N!==null?N:h?.c??null,B=E!==null?E:h?.r??null,T=u.useMemo(()=>{const q=(y?.sides??[]).find($e=>$e.value==="all")??(y?.sides??[])[0],ae=(y?.widths??[]).find($e=>$e.value!=="none");if(!q||!ae)return[];const pe=ae.suffix??"";return[pe?`${q.prefix}${pe}`:q.prefix]},[y]),H=u.useCallback((q,ae,pe)=>{if(T.length===0)return q;const $e=(y?.sides??[]).map(J=>J.prefix),be=Ue(Be(q,p),ae,pe),oe=(typeof be?.cell?.props?.className=="string"?be.cell.props.className:"").split(/\s+/).filter(Boolean);return oe.some(J=>$e.some(le=>J===le||J.startsWith(le+"-")&&/^-?\d+$/.test(J.slice(le.length+1))))?q:Ci(q,p,ae,pe,[...oe,...T].join(" ").trim())},[T,y,p]),L=u.useCallback(q=>{if(!h)return;const ae=Math.min(h.r,b?.r??h.r),pe=Math.max(h.r,b?.r??h.r),$e=Math.min(h.c,b?.c??h.c),be=Math.max(h.c,b?.c??h.c),j=new Set,oe=[];for(let J=ae;J<=pe;J++)for(let le=$e;le<=be;le++)j.add(`${J}:${le}`),oe.push({r:J,c:le});let ue=e;for(const J of oe){if(ue=H(ue,J.r,J.c),ue=Jt(ue,p,J.r,J.c,"borderColor",q),J.r>0&&!j.has(`${J.r-1}:${J.c}`)){const le=Ue(Be(ue,p),J.r-1,J.c);le&&(ue=Jt(ue,p,le.gridRow,le.gridCol,"borderBottomColor",q))}if(J.c>0&&!j.has(`${J.r}:${J.c-1}`)){const le=Ue(Be(ue,p),J.r,J.c-1);le&&(ue=Jt(ue,p,le.gridRow,le.gridCol,"borderRightColor",q))}}D(ue)},[h,b,e,p,D,H]),I=u.useCallback(q=>L(q),[L]),P=u.useMemo(()=>(y?.colors??[]).map(q=>q.token).filter(Boolean),[y]),F=u.useCallback(q=>{if(!h||P.length===0)return;const ae=Math.min(h.r,b?.r??h.r),pe=Math.max(h.r,b?.r??h.r),$e=Math.min(h.c,b?.c??h.c),be=Math.max(h.c,b?.c??h.c);let j=e;for(let oe=ae;oe<=pe;oe++)for(let ue=$e;ue<=be;ue++)j=H(j,oe,ue),j=go(j,p,oe,ue,q,P,A);D(j)},[h,b,e,p,D,H,P,A]),G=u.useMemo(()=>{if(A==="dark")return"";const q=O?.cell.props?.style;return typeof q?.borderColor=="string"?q.borderColor:""},[O,A]),V=u.useCallback((q,ae)=>{if(!h)return;const pe=Math.min(h.r,b?.r??h.r),$e=Math.max(h.r,b?.r??h.r),be=Math.min(h.c,b?.c??h.c),j=Math.max(h.c,b?.c??h.c);let oe=e;for(let ue=pe;ue<=$e;ue++)for(let J=be;J<=j;J++)oe=Jt(oe,p,ue,J,q,ae);D(oe)},[h,b,e,p,D]),Y=u.useMemo(()=>(g?.colors??[]).map(q=>q.token).filter(q=>!!q),[g]),Z=u.useCallback(()=>h?{r0:Math.min(h.r,b?.r??h.r),r1:Math.max(h.r,b?.r??h.r),c0:Math.min(h.c,b?.c??h.c),c1:Math.max(h.c,b?.c??h.c)}:null,[h,b]),se=u.useCallback(q=>{const ae=Z();if(!ae||Y.length===0)return;let pe=e;for(let $e=ae.r0;$e<=ae.r1;$e++)for(let be=ae.c0;be<=ae.c1;be++)pe=go(pe,p,$e,be,q,Y,A);D(pe)},[Z,e,p,D,Y,A]),re=u.useCallback(q=>V("backgroundColor",q),[V]),U=u.useCallback(()=>{const q=Z();if(!q)return;let ae=e;for(let pe=q.r0;pe<=q.r1;pe++)for(let $e=q.c0;$e<=q.c1;$e++)ae=go(ae,p,pe,$e,void 0,Y,A),A==="light"&&(ae=Jt(ae,p,pe,$e,"backgroundColor",void 0));D(ae)},[Z,e,p,D,Y,A]),ee=u.useCallback(q=>V("padding",q),[V]),fe=u.useMemo(()=>{if(A==="dark")return"";const q=O?.cell.props?.style;return typeof q?.backgroundColor=="string"?q.backgroundColor:""},[O,A]),K=u.useMemo(()=>typeof O?.cell.props?.className=="string"?O.cell.props.className:"",[O]),ne=u.useMemo(()=>{const q=O?.cell.props?.style;return typeof q?.padding=="string"?q.padding:""},[O]),me=u.useCallback(q=>q==="section"?n("layout_editor.table_editor.move_blocked_section"):"",[n]),Ce=u.useCallback((q,ae)=>xi(f,q,ae),[f]),ze=u.useCallback((q,ae)=>wi(f,q,ae),[f]),Se=u.useCallback(q=>D(nl(e,p,q)),[e,p,D]),qe=u.useCallback(q=>{D(Jg(e,p,q)),v(null),x(null)},[e,p,D]),De=u.useCallback((q,ae)=>D(Zg(e,p,q,ae)),[e,p,D]),Pe=u.useCallback(q=>D(Rg(e,p,q)),[e,p,D]),Qe=u.useCallback(q=>{D(eh(e,p,q)),v(null),x(null)},[e,p,D]),Me=u.useCallback((q,ae)=>D(Qg(e,p,q,ae)),[e,p,D]),Re=u.useCallback(()=>{if(!h||!b)return;const q=ol(e,p,h.r,h.c,b.r,b.c);q.ok&&(D(q.table),v({r:Math.min(h.r,b.r),c:Math.min(h.c,b.c)}),x(null))},[e,p,h,b,D]),ve=u.useCallback(()=>{h&&(D(th(e,p,h.r,h.c)),x(null))},[e,p,h,D]),te=u.useCallback(q=>{if(!h)return;const ae=Math.min(h.r,b?.r??h.r),pe=Math.max(h.r,b?.r??h.r),$e=Math.min(h.c,b?.c??h.c),be=Math.max(h.c,b?.c??h.c);let j=e;for(let oe=ae;oe<=pe;oe++)for(let ue=$e;ue<=be;ue++)j=Ci(j,p,oe,ue,q);D(j)},[e,p,h,b,D]),he=u.useCallback(async(q,ae)=>{const pe=`${q}:${ae}`,$e=k[pe];if($e===void 0)return;const be=Ue(f,q,ae);if(!be)return;const{node:j,path:oe}=dl(be.cell);if(oe===null)return;const ue=vh(j,c,d);if(ue.editable){if($e===ue.display){w(J=>{const le={...J};return delete le[pe],le});return}S(!0);try{const J=C8(j);if(J)await yr(c,J,d,$e),await tn(c,d);else{const le=await qn(c,l,d,$e);if(le.kind==="ok"&&le.resource){const Ie=`$t:${le.resource.translation_key}`;if(oe.length===0)D(nh(e,p,q,ae,Ie));else{const dt=er(be.cell,oe,Ie);D(oh(e,p,q,ae,dt))}await tn(c,d)}}}finally{S(!1),w(J=>{const le={...J};return delete le[pe],le})}}},[k,f,c,d,l,e,p,D]),Q=u.useMemo(()=>{if(!O)return null;const{node:q,path:ae}=dl(O.cell);return ae===null?null:{value:typeof q?.text=="string"?q.text:"",editable:!0}},[O]),ie=u.useCallback(q=>{if(typeof q!="string"||q.length===0||!h)return;const ae=Ue(f,h.r,h.c);if(!ae)return;const pe=Ro(ae.cell);if(pe!==null)if(pe.length===0)D(nh(e,p,h.r,h.c,q));else{const $e=er(ae.cell,pe,q);D(oh(e,p,h.r,h.c,$e))}},[h,f,e,p,D]),_e=u.useCallback((q,ae,pe)=>{pe?x({r:q,c:ae}):(v({r:q,c:ae}),x(null))},[]),ge=u.useMemo(()=>Array.from({length:f.colCount},(q,ae)=>ae),[f.colCount]),Ae=!!(h&&b&&(h.r!==b.r||h.c!==b.c)),Ne=!!(O&&(O.colSpan>1||O.rowSpan>1)),Le=O&&typeof O.cell.props?.className=="string"?O.cell.props.className:"";return i.jsxs("div",{className:"g7le-node-editor g7le-node-editor--table","data-testid":"g7le-table-editor",style:E8,children:[i.jsx("div",{style:I8,children:n("layout_editor.table_editor.title")}),i.jsx("div",{style:{overflowX:"auto"},children:i.jsxs("table",{"data-testid":"g7le-table-editor-grid",style:A8,children:[i.jsx("thead",{children:i.jsxs("tr",{children:[i.jsx("th",{style:T8}),ge.map(q=>{const ae=ze(q,-1),pe=ze(q,1),$e=M===q;return i.jsx("th",{style:D8,"data-testid":`g7le-table-colgutter-${q}`,onMouseEnter:()=>$(q),onMouseLeave:()=>$(be=>be===q?null:be),children:i.jsxs("div",{style:{...z8,visibility:$e?"visible":"hidden"},children:[i.jsx("button",{type:"button",title:ae.ok?n("layout_editor.table_editor.move_col_left"):me(ae.reason)||n("layout_editor.table_editor.move_col_left"),disabled:!ae.ok||_,onClick:()=>Me(q,-1),"data-testid":`g7le-table-col-left-${q}`,style:ae.ok?vn:$i,children:"←"}),i.jsx("button",{type:"button",title:n("layout_editor.table_editor.add_col"),disabled:_,onClick:()=>Pe(q),"data-testid":`g7le-table-col-add-${q}`,style:vn,children:"+"}),i.jsx("button",{type:"button",title:n("layout_editor.table_editor.remove_col"),disabled:f.colCount<=1||_,onClick:()=>Qe(q),"data-testid":`g7le-table-col-remove-${q}`,style:_h,children:"✕"}),i.jsx("button",{type:"button",title:pe.ok?n("layout_editor.table_editor.move_col_right"):me(pe.reason)||n("layout_editor.table_editor.move_col_right"),disabled:!pe.ok||_,onClick:()=>Me(q,1),"data-testid":`g7le-table-col-right-${q}`,style:pe.ok?vn:$i,children:"→"})]})},q)})]})}),i.jsx("tbody",{children:f.rows.map((q,ae)=>{const pe=q.cells[0]?.gridRow??ae,$e=B===pe;return i.jsxs("tr",{"data-testid":`g7le-table-row-${pe}`,onMouseEnter:()=>C(pe),onMouseLeave:()=>C(be=>be===pe?null:be),children:[i.jsx("td",{style:N8,"data-testid":`g7le-table-rowgutter-${pe}`,children:(()=>{const be=Ce(pe,-1),j=Ce(pe,1);return i.jsxs("div",{style:{...M8,visibility:$e?"visible":"hidden"},children:[i.jsx("button",{type:"button",title:be.ok?n("layout_editor.table_editor.move_row_up"):me(be.reason)||n("layout_editor.table_editor.move_row_up"),disabled:!be.ok||_,onClick:()=>De(pe,-1),"data-testid":`g7le-table-row-up-${pe}`,style:be.ok?vn:$i,children:"↑"}),i.jsx("button",{type:"button",title:n("layout_editor.table_editor.add_row"),disabled:_,onClick:()=>Se(pe),"data-testid":`g7le-table-row-add-${pe}`,style:vn,children:"+"}),i.jsx("button",{type:"button",title:n("layout_editor.table_editor.remove_row"),disabled:f.rows.length<=1||_,onClick:()=>qe(pe),"data-testid":`g7le-table-row-remove-${pe}`,style:_h,children:"✕"}),i.jsx("button",{type:"button",title:j.ok?n("layout_editor.table_editor.move_row_down"):me(j.reason)||n("layout_editor.table_editor.move_row_down"),disabled:!j.ok||_,onClick:()=>De(pe,1),"data-testid":`g7le-table-row-down-${pe}`,style:j.ok?vn:$i,children:"↓"})]})})()}),q.cells.map(be=>{const j=`${be.gridRow}:${be.gridCol}`,{node:oe,path:ue}=dl(be.cell),J=vh(oe,c,d),le=ue!==null&&J.editable,Ie=ue===null,dt=k[j],pt=dt!==void 0?dt:J.display,ot=h&&h.r===be.gridRow&&h.c===be.gridCol,Oe=h&&b&&be.gridRow>=Math.min(h.r,b.r)&&be.gridRow<=Math.max(h.r,b.r)&&be.gridCol>=Math.min(h.c,b.c)&&be.gridCol<=Math.max(h.c,b.c);return i.jsx("td",{colSpan:be.colSpan,rowSpan:be.rowSpan,"data-testid":`g7le-table-cell-${be.gridRow}-${be.gridCol}`,onClick:He=>_e(be.gridRow,be.gridCol,He.shiftKey),style:{...L8,..._8(be.cell,y,A),...x8(be.cell,g,A),...be.isHeader?P8:{},...ot?O8:{},...Oe&&!ot?B8:{}},children:le?i.jsx("input",{type:"text","data-testid":`g7le-table-cell-input-${be.gridRow}-${be.gridCol}`,value:pt,placeholder:n("layout_editor.table_editor.cell_text"),disabled:_,onMouseDown:He=>{He.shiftKey&&He.preventDefault(),_e(be.gridRow,be.gridCol,He.shiftKey)},onClick:He=>He.stopPropagation(),onChange:He=>w(Ye=>({...Ye,[j]:He.target.value})),onBlur:()=>{he(be.gridRow,be.gridCol)},style:W8}):Ie?i.jsx("span",{"data-testid":`g7le-table-cell-struct-${be.gridRow}-${be.gridCol}`,style:xh,children:n("layout_editor.table_editor.structural_cell")}):i.jsx("span",{style:xh,children:J.display})},j)})]},ae)})})]})}),i.jsxs("button",{type:"button","data-testid":"g7le-table-add-row-bottom",onClick:()=>Se(f.rows.length-1),disabled:_,style:j8,children:["+ ",n("layout_editor.table_editor.add_row")]}),i.jsxs("div",{style:H8,"data-testid":"g7le-table-cell-tools",children:[i.jsx("button",{type:"button","data-testid":"g7le-table-merge",onClick:Re,disabled:!Ae||_,style:wh,children:n("layout_editor.table_editor.merge_cells")}),i.jsx("button",{type:"button","data-testid":"g7le-table-unmerge",onClick:ve,disabled:!Ne||_,style:wh,children:n("layout_editor.table_editor.unmerge_cells")})]}),O&&Q&&i.jsxs("div",{style:K8,"data-testid":"g7le-table-cell-i18n-section",children:[i.jsx("div",{style:V8,children:n("layout_editor.table_editor.cell_i18n_label")}),i.jsx(vt,{value:Q.value,onChange:ie,t:n,placeholder:n("layout_editor.table_editor.cell_text"),testidPrefix:"g7le-table-cell-i18n",candidates:s,enableExpressionTree:!0,expressionTreeCollapsible:!0})]}),O&&i.jsxs("div",{style:F8,"data-testid":"g7le-table-cell-color-section",children:[i.jsx(fh,{colorScheme:A,onChange:z,t:n,disabled:_}),y&&i.jsx("div",{style:cl,"data-testid":"g7le-table-cell-border-row",children:i.jsx(sh,{className:Le,catalog:y,t:n,onChange:te,colorScheme:A,onPresetToken:F,colorStyle:G,onColorStyle:I,disabled:_})}),i.jsx("div",{style:cl,"data-testid":"g7le-table-cell-fill-row",children:i.jsx(ch,{colorStyle:fe,className:K,catalog:g,t:n,colorScheme:A,onPresetToken:se,onCustomColor:re,onClear:U,disabled:_})})]}),O&&i.jsx("div",{style:cl,"data-testid":"g7le-table-cell-padding-row",children:i.jsx(uh,{paddingStyle:ne,catalog:m,t:n,onChange:ee,disabled:_})}),O&&!y&&i.jsxs("label",{style:U8,"data-testid":"g7le-table-cell-border-row",children:[i.jsx("span",{style:q8,children:n("layout_editor.table_editor.cell_border")}),i.jsx("input",{type:"text","data-testid":"g7le-table-cell-border-input",value:Le,placeholder:n("layout_editor.table_editor.cell_class_placeholder"),onChange:q=>te(q.target.value),disabled:_,style:G8})]}),!f.valid&&i.jsx("div",{"data-testid":"g7le-table-grid-warning",style:Y8,children:n("layout_editor.table_editor.grid_invalid")}),i.jsx("div",{style:X8,children:n("layout_editor.table_editor.select_hint")})]})}const E8={display:"flex",flexDirection:"column",gap:8,width:"100%",marginBottom:12},I8={fontSize:12,fontWeight:700,color:"#0f172a"},A8={borderCollapse:"collapse",width:"auto"},T8={width:28,background:"transparent",border:"none"},D8={padding:2,border:"none",background:"transparent"},N8={padding:2,border:"none",background:"transparent",verticalAlign:"middle"},z8={display:"flex",gap:2,justifyContent:"center"},M8={display:"grid",gridTemplateColumns:"repeat(2, 16px)",gap:2,justifyContent:"center"},vn={width:16,height:16,lineHeight:"14px",padding:0,fontSize:10,border:"1px solid #cbd5e1",borderRadius:4,background:"#fff",color:"#475569",cursor:"pointer"},_h={...vn,border:"1px solid #fecaca",color:"#dc2626"},$i={...vn,cursor:"not-allowed",opacity:.4,color:"#94a3b8",borderColor:"#e2e8f0"},L8={border:"1px solid #cbd5e1",padding:0,width:64,minWidth:64,maxWidth:120,height:24,background:"#fff",cursor:"pointer"},P8={background:"#f1f5f9",fontWeight:600},O8={outline:"2px solid #2563eb",outlineOffset:-2},B8={background:"#dbeafe"},W8={width:"100%",boxSizing:"border-box",padding:"2px 5px",fontSize:11,height:22,lineHeight:"18px",border:"none",background:"transparent",outline:"none"},xh={display:"block",padding:"2px 5px",fontSize:10,color:"#64748b",fontStyle:"italic",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:110},j8={padding:"4px 8px",fontSize:12,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",alignSelf:"flex-start"},H8={display:"flex",gap:6},wh={padding:"4px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},F8={display:"flex",flexDirection:"column",gap:8,borderTop:"1px solid #f1f5f9",paddingTop:8},K8={display:"flex",flexDirection:"column",gap:6,borderTop:"1px solid #f1f5f9",paddingTop:8},V8={fontSize:12,fontWeight:700,color:"#0f172a"},cl={display:"flex",flexDirection:"column",gap:6},U8={display:"flex",alignItems:"center",gap:6},q8={fontSize:12,color:"#475569",minWidth:60},G8={flex:1,minWidth:0,padding:"4px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6},Y8={fontSize:11,color:"#b45309",background:"#fffbeb",border:"1px solid #fde68a",borderRadius:6,padding:"4px 6px"},X8={fontSize:11,color:"#94a3b8"},J8=/\{\{.*?\}\}/;function Z8(e,t,n){const r=(e.props??{})[t];return Array.isArray(r)?r:r===void 0&&n?JSON.parse(JSON.stringify(n)):[]}function Q8(e){return typeof e=="string"&&J8.test(e)}function ul(e,t,n){return e?e.startsWith("$t:")?t(e.slice(3)):e:n}function R8(e,t,n){return typeof e=="object"&&e!==null?e[t.key]:n?e:void 0}function ez(e,t,n,o){if(typeof e=="object"&&e!==null){const r={...e};return o===void 0?delete r[t.key]:r[t.key]=o,r}return n?o:{[t.key]:o}}function kh({node:e,params:t,t:n,onPatchNode:o,templateIdentifier:r,candidates:s}){const a=typeof t?.arrayProp=="string"?t.arrayProp:null,l=Array.isArray(t?.fields)?t.fields:[],d=ul(typeof t?.itemLabel=="string"?t.itemLabel:void 0,n,n("layout_editor.array_editor.item")),c=t?.newItem,p=c&&typeof c=="object"?c:null,f=typeof c=="string"||typeof c=="number"?c:null,y=(l.find(S=>S.primary)??l[0])?.key,g=(e.props??{})[a??""],m=Array.isArray(t?.defaultItems)?t.defaultItems:null,h=a?Z8(e,a,m):[],v=u.useCallback(S=>{if(!a)return;const E={...e.props??{}};E[a]=S,o({...e,props:E})},[a,e,o]),b=u.useCallback(()=>{if(p)return JSON.parse(JSON.stringify(p));if(f!==null)return f;const S={};for(const E of l)(E.widget??"text")==="boolean"?S[E.key]=!1:S[E.key]="";return S},[p,f,l]),x=u.useCallback(()=>{v([...h,b()])},[v,h,b]),k=u.useCallback(S=>{v(h.filter((E,C)=>C!==S))},[v,h]),w=u.useCallback((S,E)=>{const C=S+E;if(C<0||C>=h.length)return;const N=[...h];[N[S],N[C]]=[N[C],N[S]],v(N)},[v,h]),_=u.useCallback((S,E,C)=>{const N=E.key===y,$=h.map((A,z)=>z===S?ez(A,E,N,C):A);v($)},[h,v,y]);return a?Q8(g)||g!==void 0&&!Array.isArray(g)?i.jsx("div",{className:"g7le-node-editor g7le-node-editor--array","data-testid":"g7le-array-editor-bound",style:dz,children:n("layout_editor.array_editor.bound_degraded")}):i.jsxs("div",{className:"g7le-node-editor g7le-node-editor--array","data-testid":"g7le-array-editor",style:tz,children:[i.jsx("div",{style:nz,children:n("layout_editor.array_editor.items_title")}),h.length===0&&i.jsx("div",{"data-testid":"g7le-array-empty",style:Ch,children:n("layout_editor.array_editor.empty")}),h.map((S,E)=>i.jsxs("div",{"data-testid":`g7le-array-row-${E}`,style:oz,children:[i.jsxs("div",{style:rz,children:[i.jsxs("span",{style:iz,children:["#",E+1]}),i.jsx("div",{style:{flex:1}}),i.jsx("button",{type:"button","data-testid":`g7le-array-up-${E}`,title:n("layout_editor.array_editor.move_up"),disabled:E===0,onClick:()=>w(E,-1),style:Sh,children:"↑"}),i.jsx("button",{type:"button","data-testid":`g7le-array-down-${E}`,title:n("layout_editor.array_editor.move_down"),disabled:E===h.length-1,onClick:()=>w(E,1),style:Sh,children:"↓"}),i.jsx("button",{type:"button","data-testid":`g7le-array-remove-${E}`,title:n("layout_editor.array_editor.remove"),onClick:()=>k(E),style:az,children:"✕"})]}),l.map(C=>{const N=C.widget??"text",$=C.key===y,A=ul(C.label,n,C.key),z=R8(S,C,$),D=`g7le-array-field-${E}-${C.key}`;if(N==="boolean")return i.jsxs("label",{style:Wn,children:[i.jsx("span",{style:jn,children:A}),i.jsx("input",{type:"checkbox","data-testid":D,checked:z===!0,onChange:M=>_(E,C,M.target.checked)})]},C.key);if(N==="select"){const M=Array.isArray(C.options)?C.options:[];return i.jsxs("label",{style:Wn,children:[i.jsx("span",{style:jn,children:A}),i.jsxs("select",{"data-testid":D,value:z==null?"":String(z),onChange:B=>_(E,C,B.target.value===""?void 0:B.target.value),style:nr,children:[i.jsx("option",{value:"",children:"—"}),M.map((B,T)=>i.jsx("option",{value:String(B.value),children:ul(B.label,n,String(B.value))},T))]})]},C.key)}if(N==="i18n-text"){const M=typeof z=="string"?z:z==null?"":String(z);return i.jsxs("label",{style:Wn,children:[i.jsx("span",{style:jn,children:A}),i.jsx("div",{"data-testid":D,style:{flex:1,minWidth:0},children:i.jsx(vt,{value:M,onChange:B=>_(E,C,B===""?void 0:B),t:n,placeholder:A,testidPrefix:`${D}-i18n`,candidates:s,enableExpressionTree:!0,expressionTreeCollapsible:!0})})]},C.key)}if(N==="number"){const M=z==null?"":String(z);return i.jsxs("label",{style:Wn,children:[i.jsx("span",{style:jn,children:A}),i.jsx("input",{type:"number","data-testid":D,value:M,onChange:B=>{const T=B.target.value;_(E,C,T===""?void 0:Number(T))},style:nr})]},C.key)}if(N==="color"){const M=typeof z=="string"?z:"",B=/^#[0-9a-fA-F]{6}$/.test(M)?M:"#000000";return i.jsxs("label",{style:Wn,children:[i.jsx("span",{style:jn,children:A}),i.jsx("input",{type:"color","data-testid":`${D}-swatch`,value:B,onChange:T=>_(E,C,T.target.value),style:sz}),i.jsx("input",{type:"text","data-testid":D,value:M,placeholder:"#7C3AED",onChange:T=>_(E,C,T.target.value===""?void 0:T.target.value),style:nr})]},C.key)}if(N==="number-list"){const M=Array.isArray(z)?z.join(", "):"";return i.jsxs("label",{style:Wn,children:[i.jsx("span",{style:jn,children:A}),i.jsx("input",{type:"text","data-testid":D,value:M,placeholder:n("layout_editor.array_editor.number_list_placeholder"),onChange:B=>{const T=B.target.value.split(",").map(H=>H.trim()).filter(H=>H!=="").map(H=>Number(H)).filter(H=>!Number.isNaN(H));_(E,C,T)},style:nr})]},C.key)}const O=z==null?"":String(z);return i.jsxs("label",{style:Wn,children:[i.jsx("span",{style:jn,children:A}),i.jsx("input",{type:"text","data-testid":D,value:O,placeholder:N==="icon"?n("layout_editor.array_editor.icon_placeholder"):A,onChange:M=>_(E,C,M.target.value===""?void 0:M.target.value),style:nr})]},C.key)})]},E)),i.jsx("button",{type:"button","data-testid":"g7le-array-add",onClick:x,style:lz,children:n("layout_editor.array_editor.add",{item:d})})]}):i.jsx("div",{className:"g7le-node-editor g7le-node-editor--array","data-testid":"g7le-array-editor-misconfigured",style:Ch,children:n("layout_editor.array_editor.no_array_prop")})}const tz={display:"flex",flexDirection:"column",gap:8,width:"100%",marginBottom:12},nz={fontSize:12,fontWeight:700,color:"#0f172a",marginBottom:2},oz={display:"flex",flexDirection:"column",gap:4,padding:8,border:"1px solid #e2e8f0",borderRadius:8,background:"#f8fafc"},rz={display:"flex",gap:4,alignItems:"center"},iz={fontSize:11,fontWeight:700,color:"#64748b"},Wn={display:"flex",flexWrap:"wrap",gap:6,alignItems:"center"},jn={fontSize:11,color:"#475569",minWidth:64,flexShrink:0},nr={flex:1,minWidth:0,padding:"4px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6},sz={width:32,height:28,padding:0,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",cursor:"pointer",flexShrink:0},Sh={padding:"2px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},az={padding:"2px 6px",fontSize:12,border:"1px solid #fecaca",borderRadius:6,background:"#fff",color:"#dc2626",cursor:"pointer"},lz={padding:"4px 8px",fontSize:12,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",alignSelf:"flex-start"},Ch={fontSize:11,color:"#94a3b8",fontStyle:"italic"},dz={fontSize:11,color:"#b45309",fontStyle:"italic",padding:"4px 2px"};function cz(e,t){return e?e.startsWith("$t:")?t(e.slice(3)):e:null}function uz(e){const{params:t,t:n}=e,o=Array.isArray(t?.groups)?t.groups:[];return o.length===0?i.jsx("div",{className:"g7le-node-editor g7le-node-editor--array-group","data-testid":"g7le-array-group-misconfigured",style:hz,children:n("layout_editor.array_editor.no_array_prop")}):i.jsx("div",{className:"g7le-node-editor g7le-node-editor--array-group","data-testid":"g7le-array-group-editor",style:pz,children:o.map((r,s)=>{const a=cz(r.title,n),{title:l,...d}=r;return i.jsxs("div",{"data-testid":`g7le-array-group-${r.arrayProp??s}`,style:fz,children:[a&&i.jsx("div",{style:gz,children:a}),i.jsx(kh,{...e,params:d})]},r.arrayProp??s)})})}const pz={display:"flex",flexDirection:"column",gap:16,width:"100%",marginBottom:12},fz={display:"flex",flexDirection:"column",gap:4},gz={fontSize:12,fontWeight:700,color:"#1e293b",borderBottom:"1px solid #e2e8f0",paddingBottom:4},hz={fontSize:11,color:"#94a3b8",fontStyle:"italic"},yz=/\{\{.*?\}\}/;function bz(e){return typeof e=="string"&&yz.test(e)}function mz(e,t,n){return e?e.startsWith("$t:")?t(e.slice(3)):e:n}function vz(e){const{node:t,params:n,t:o,onPatchNode:r}=e,s=typeof n?.arrayProp=="string"?n.arrayProp:null,a=typeof n?.idField=="string"?n.idField:"id",l=typeof n?.cellChildrenProp=="string"?n.cellChildrenProp:"cellChildren",d=typeof n?.cellChildComponent=="string"?n.cellChildComponent:"Div",c=mz(typeof n?.itemLabel=="string"?n.itemLabel:void 0,o,o("layout_editor.array_editor.item")),[p,f]=u.useState(null),y=s?(t.props??{})[s]:void 0,g=Array.isArray(y)?y:[],m=u.useCallback(S=>{if(!s)return;const E={...t.props??{}};E[s]=S,r({...t,props:E})},[s,t,r]),h=u.useCallback(()=>{const S=n?.newItem;return S&&typeof S=="object"?JSON.parse(JSON.stringify(S)):{[a]:"",[l]:[]}},[n,a,l]),v=u.useCallback(()=>{m([...g,h()])},[m,g,h]),b=u.useCallback(S=>{m(g.filter((E,C)=>C!==S)),f(null)},[m,g]),x=u.useCallback((S,E)=>{const C=S+E;if(C<0||C>=g.length)return;const N=[...g];[N[S],N[C]]=[N[C],N[S]],m(N)},[m,g]),k=u.useCallback((S,E)=>{const C=g.map((N,$)=>$===S?{...N,[a]:E}:N);m(C)},[g,m,a]),w=u.useCallback(S=>({type:"composite",name:"CardGridCell",children:Array.isArray(S[l])?S[l]:[]}),[l]),_=u.useCallback(S=>E=>{const C=Array.isArray(E.children)?E.children:[],N=g.map(($,A)=>A===S?{...$,[l]:C}:$);m(N)},[g,m,l]);return s?bz(y)||y!==void 0&&!Array.isArray(y)?i.jsx("div",{className:"g7le-node-editor g7le-node-editor--cell-tree","data-testid":"g7le-cell-tree-bound",style:Tz,children:o("layout_editor.array_editor.bound_degraded")}):i.jsxs("div",{className:"g7le-node-editor g7le-node-editor--cell-tree","data-testid":"g7le-cell-tree-editor",style:_z,children:[i.jsx("div",{style:xz,children:o("layout_editor.cell_tree_editor.columns_title")}),g.length===0&&i.jsx("div",{"data-testid":"g7le-cell-tree-empty",style:Eh,children:o("layout_editor.array_editor.empty")}),g.map((S,E)=>{const C=typeof S[a]=="string"?S[a]:"",N=p===E;return i.jsxs("div",{"data-testid":`g7le-cell-tree-row-${E}`,style:wz,children:[i.jsxs("div",{style:kz,children:[i.jsxs("span",{style:Sz,children:["#",E+1]}),i.jsx("input",{type:"text","data-testid":`g7le-cell-tree-id-${E}`,value:C,placeholder:o("layout_editor.cell_tree_editor.id_placeholder"),onChange:$=>k(E,$.target.value),style:Cz}),i.jsx("button",{type:"button","data-testid":`g7le-cell-tree-up-${E}`,title:o("layout_editor.array_editor.move_up"),disabled:E===0,onClick:()=>x(E,-1),style:$h,children:"↑"}),i.jsx("button",{type:"button","data-testid":`g7le-cell-tree-down-${E}`,title:o("layout_editor.array_editor.move_down"),disabled:E===g.length-1,onClick:()=>x(E,1),style:$h,children:"↓"}),i.jsx("button",{type:"button","data-testid":`g7le-cell-tree-remove-${E}`,title:o("layout_editor.array_editor.remove"),onClick:()=>b(E),style:$z,children:"✕"})]}),i.jsx("button",{type:"button","data-testid":`g7le-cell-tree-toggle-${E}`,onClick:()=>f(N?null:E),style:Ez,children:o(N?"layout_editor.cell_tree_editor.collapse_cells":"layout_editor.cell_tree_editor.expand_cells")}),N&&i.jsx("div",{"data-testid":`g7le-cell-tree-cells-${E}`,style:Iz,children:i.jsx(Kg,{...e,node:w(S),params:{childComponent:d},onPatchNode:_(E)})})]},E)}),i.jsx("button",{type:"button","data-testid":"g7le-cell-tree-add",onClick:v,style:Az,children:o("layout_editor.cell_tree_editor.add_column",{item:c})})]}):i.jsx("div",{className:"g7le-node-editor g7le-node-editor--cell-tree","data-testid":"g7le-cell-tree-misconfigured",style:Eh,children:o("layout_editor.array_editor.no_array_prop")})}const _z={display:"flex",flexDirection:"column",gap:8,width:"100%",marginBottom:12},xz={fontSize:12,fontWeight:700,color:"#0f172a",marginBottom:2},wz={display:"flex",flexDirection:"column",gap:6,padding:8,border:"1px solid #e2e8f0",borderRadius:8,background:"#f8fafc"},kz={display:"flex",gap:4,alignItems:"center"},Sz={fontSize:11,fontWeight:700,color:"#64748b",flexShrink:0},Cz={flex:1,minWidth:0,padding:"4px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6},$h={padding:"2px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},$z={padding:"2px 6px",fontSize:12,border:"1px solid #fecaca",borderRadius:6,background:"#fff",color:"#dc2626",cursor:"pointer"},Ez={padding:"3px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#2563eb",cursor:"pointer",alignSelf:"flex-start"},Iz={paddingLeft:8,borderLeft:"2px solid #e2e8f0"},Az={padding:"4px 8px",fontSize:12,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",alignSelf:"flex-start"},Eh={fontSize:11,color:"#94a3b8",fontStyle:"italic"},Tz={fontSize:11,color:"#b45309",fontStyle:"italic",padding:"4px 2px"};function Dz(e,t,n){const o=Be(e,t);if(!n||n.length===0)return{measured:[],grid:o};const r=[];for(const s of o.rows)for(const a of s.cells){const d=tl(e,a,t).map(p=>`children.${p}`).join("."),c=n.find(p=>p.path===d||p.path.endsWith("."+d));c&&r.push({ref:a,box:{top:c.top,left:c.left,width:c.width,height:c.height}})}return{measured:r,grid:o}}const pl=26,fl=50,gl=6,Ih=44,Ah=18,Th="g7le-table-inplace-empty-cell-style";function Nz(){if(typeof document>"u"||document.getElementById(Th))return;const e=document.createElement("style");e.id=Th,e.textContent=".g7le-preview-frame td[data-editor-name],.g7le-preview-frame th[data-editor-name]{min-width:56px;height:38px;}.g7le-preview-frame table[data-editor-name]{min-width:120px;}",document.head.appendChild(e)}function zz({node:e,params:t,nodeBox:n,cellBoxes:o,selectedCellPath:r,colorScheme:s,t:a,onPatchNode:l,onRequestInlineEdit:d}){const c=u.useMemo(()=>t&&typeof t=="object"?t:null,[t]),{measured:p,grid:f}=u.useMemo(()=>Dz(e,c,o),[e,c,o]),[y,g]=u.useState(null),[m,h]=u.useState(null),v=u.useMemo(()=>{if(!r)return null;for(const j of f.rows)for(const oe of j.cells){const ue=tl(e,oe,c).map(J=>`children.${J}`).join(".");if(r===ue||r.startsWith(ue+"."))return{r:oe.gridRow,c:oe.gridCol}}return null},[r,f,e,c]),b=u.useMemo(()=>y&&Ue(f,y.r,y.c)?y:v,[y,v,f]),[x,k]=u.useState(!1),[w,_]=u.useState(s==="dark"?"dark":"light"),[S,E]=u.useState(null),[C,N]=u.useState(null),$=u.useRef(null),A=u.useCallback(()=>{$.current!==null&&(clearTimeout($.current),$.current=null)},[]),z=u.useCallback(()=>{A(),$.current=setTimeout(()=>{E(null),N(null),$.current=null},240)},[A]);u.useEffect(()=>()=>A(),[A]),u.useEffect(()=>{Nz()},[]);const D=u.useCallback(j=>l(j),[l]),O=u.useMemo(()=>b?Ue(f,b.r,b.c):null,[f,b]),M=u.useMemo(()=>O&&typeof O.cell.props?.className=="string"?O.cell.props.className:"",[O]),B=u.useCallback(j=>D(nl(e,c,j)),[e,c,D]),T=u.useCallback(j=>D(Jg(e,c,j)),[e,c,D]),H=u.useCallback((j,oe)=>D(Zg(e,c,j,oe)),[e,c,D]),L=u.useCallback(j=>D(Rg(e,c,j)),[e,c,D]),I=u.useCallback(j=>D(eh(e,c,j)),[e,c,D]),P=u.useCallback((j,oe)=>D(Qg(e,c,j,oe)),[e,c,D]),F=u.useCallback(j=>{if(!O)return;const oe=O.gridRow,ue=O.gridCol,J=j==="down"?oe+O.rowSpan:oe+O.rowSpan-1,le=j==="right"?ue+O.colSpan:ue+O.colSpan-1;if(J>=f.rows.length||le>=f.colCount)return;const Ie=ol(e,c,oe,ue,J,le);Ie.ok&&D(Ie.table)},[O,f,e,c,D]),G=!!(O&&O.gridCol+O.colSpan!b||!m||!Ue(f,m.r,m.c)?null:{r0:Math.min(b.r,m.r),c0:Math.min(b.c,m.c),r1:Math.max(b.r,m.r),c1:Math.max(b.c,m.c)},[b,m,f]),Z=u.useMemo(()=>{if(!Y)return[];const j=new Set,oe=[];for(const ue of f.rows)for(const J of ue.cells)if(J.gridRow>=Y.r0&&J.gridRow<=Y.r1&&J.gridCol>=Y.c0&&J.gridCol<=Y.c1){const le=`${J.gridRow}:${J.gridCol}`;j.has(le)||(j.add(le),oe.push({r:J.gridRow,c:J.gridCol}))}return oe},[Y,f]),se=Z.length>1,re=u.useCallback(()=>{if(!Y)return;const j=ol(e,c,Y.r0,Y.c0,Y.r1,Y.c1);j.ok&&(D(j.table),h(null))},[Y,e,c,D]),U=u.useCallback(()=>{b&&D(th(e,c,b.r,b.c))},[e,c,b,D]),ee=u.useMemo(()=>{const j=c?.cellBorder;return j&&typeof j=="object"?j:null},[c]),fe=u.useMemo(()=>{const j=c?.cellBackground;return j&&typeof j=="object"?j:null},[c]),K=u.useMemo(()=>{const j=c?.cellPadding;return j&&typeof j=="object"?j:null},[c]),ne=u.useMemo(()=>{if(x){const j=new Set,oe=[];for(const ue of f.rows)for(const J of ue.cells){const le=`${J.gridRow}:${J.gridCol}`;j.has(le)||(j.add(le),oe.push({r:J.gridRow,c:J.gridCol}))}return oe}return se?Z:b?[{r:b.r,c:b.c}]:[]},[x,se,Z,b,f]),me=u.useCallback(j=>{if(ne.length===0)return;let oe=e;for(const ue of ne){const J=(ee?.colors??[]).map(Ie=>Ie.token),le=j.split(/\s+/).filter(Ie=>Ie&&!J.includes(Ie)).join(" ");oe=Ci(oe,c,ue.r,ue.c,le)}D(oe)},[e,c,ne,ee,D]),Ce=u.useMemo(()=>{const j=(ee?.sides??[]).find(J=>J.value==="all")??(ee?.sides??[])[0],oe=(ee?.widths??[]).find(J=>J.value!=="none");if(!j||!oe)return[];const ue=oe.suffix??"";return[ue?`${j.prefix}${ue}`:j.prefix]},[ee]),ze=u.useCallback((j,oe,ue)=>{if(Ce.length===0)return j;const J=(ee?.sides??[]).map(Oe=>Oe.prefix),le=Ue(Be(j,c),oe,ue),dt=(typeof le?.cell?.props?.className=="string"?le.cell.props.className:"").split(/\s+/).filter(Boolean);if(dt.some(Oe=>J.some(He=>Oe===He||Oe.startsWith(He+"-")&&/^-?\d+$/.test(Oe.slice(He.length+1)))))return j;const ot=[...dt,...Ce].join(" ").trim();return Ci(j,c,oe,ue,ot)},[Ce,ee,c]),Se=u.useCallback((j,oe)=>{if(j.length===0)return;const ue=new Set(j.map(le=>`${le.r}:${le.c}`));let J=e;for(const le of j){if(J=ze(J,le.r,le.c),J=Jt(J,c,le.r,le.c,"borderColor",oe),le.r>0&&!ue.has(`${le.r-1}:${le.c}`)){const Ie=Ue(Be(J,c),le.r-1,le.c);Ie&&(J=Jt(J,c,Ie.gridRow,Ie.gridCol,"borderBottomColor",oe))}if(le.c>0&&!ue.has(`${le.r}:${le.c-1}`)){const Ie=Ue(Be(J,c),le.r,le.c-1);Ie&&(J=Jt(J,c,Ie.gridRow,Ie.gridCol,"borderRightColor",oe))}}D(J)},[e,c,D,ze]),qe=u.useMemo(()=>(ee?.colors??[]).map(j=>j.token).filter(Boolean),[ee]),De=u.useCallback(j=>{if(ne.length===0||qe.length===0)return;let oe=e;for(const ue of ne)oe=ze(oe,ue.r,ue.c),oe=go(oe,c,ue.r,ue.c,j,qe,w);D(oe)},[ne,e,c,D,ze,qe,w]),Pe=u.useCallback(j=>Se(ne,j),[Se,ne]),Qe=u.useMemo(()=>{if(w==="dark")return"";const j=O?.cell.props?.style;return typeof j?.borderColor=="string"?j.borderColor:""},[O,w]),Me=u.useCallback((j,oe)=>{if(ne.length===0)return;let ue=e;for(const J of ne)ue=Jt(ue,c,J.r,J.c,j,oe);D(ue)},[ne,e,c,D]),Re=u.useMemo(()=>(fe?.colors??[]).map(j=>j.token).filter(j=>!!j),[fe]),ve=u.useCallback(j=>{if(ne.length===0||Re.length===0)return;let oe=e;for(const ue of ne)oe=go(oe,c,ue.r,ue.c,j,Re,w);D(oe)},[ne,e,c,D,Re,w]),te=u.useCallback(j=>Me("backgroundColor",j),[Me]),he=u.useCallback(()=>{if(ne.length===0)return;let j=e;for(const oe of ne)j=go(j,c,oe.r,oe.c,void 0,Re,w),w==="light"&&(j=Jt(j,c,oe.r,oe.c,"backgroundColor",void 0));D(j)},[ne,e,c,D,Re,w]),Q=u.useCallback(j=>Me("padding",j),[Me]),ie=u.useMemo(()=>{if(w==="dark")return"";const j=O?.cell.props?.style;return typeof j?.backgroundColor=="string"?j.backgroundColor:""},[O,w]),_e=u.useMemo(()=>typeof O?.cell.props?.className=="string"?O.cell.props.className:"",[O]),ge=u.useMemo(()=>{const j=O?.cell.props?.style;return typeof j?.padding=="string"?j.padding:""},[O]),Ae=u.useCallback(j=>{const oe=j.currentTarget,ue=oe.style.pointerEvents;oe.style.pointerEvents="none";const J=document.elementFromPoint(j.clientX,j.clientY);oe.style.pointerEvents=ue;const le=J?.closest?.("[data-dnd-handle-path]");le&&le.dispatchEvent(new PointerEvent("pointerdown",{bubbles:!0,cancelable:!0,clientX:j.clientX,clientY:j.clientY,pointerId:j.pointerId,pointerType:j.pointerType,button:j.button,isPrimary:!0}))},[]),Ne=u.useMemo(()=>{const j=new Map;for(const oe of p)j.has(oe.ref.gridCol)||j.set(oe.ref.gridCol,oe.box);return j},[p]),Le=u.useMemo(()=>{const j=new Map;for(const oe of p)j.has(oe.ref.gridRow)||j.set(oe.ref.gridRow,oe.box);return j},[p]);if(p.length===0)return null;const q=!!(O&&(O.colSpan>1||O.rowSpan>1)),ae=C!==null?C:b?.c??null,pe=S!==null?S:b?.r??null,$e=n.top-pl-gl-Ih,be=n.left-fl-gl-Ih;return i.jsxs("div",{className:"g7le-table-inplace","data-testid":"g7le-table-inplace",style:{position:"absolute",inset:0,pointerEvents:"none",zIndex:c7},children:[p.map(j=>{const oe=b&&b.r===j.ref.gridRow&&b.c===j.ref.gridCol,ue=Y&&j.ref.gridRow>=Y.r0&&j.ref.gridRow<=Y.r1&&j.ref.gridCol>=Y.c0&&j.ref.gridCol<=Y.c1;return i.jsx("div",{"data-testid":`g7le-inplace-cell-${j.ref.gridRow}-${j.ref.gridCol}`,role:"button",tabIndex:-1,"aria-label":a("layout_editor.table_inplace.select_cell"),onMouseEnter:()=>{A(),E(j.ref.gridRow),N(j.ref.gridCol)},onMouseLeave:()=>{z()},onPointerDown:J=>Ae(J),onClick:J=>{if(J.stopPropagation(),J.shiftKey&&(y||b))h({r:j.ref.gridRow,c:j.ref.gridCol});else{g({r:j.ref.gridRow,c:j.ref.gridCol}),h(null);const le=tl(e,j.ref,c).map(Ie=>`children.${Ie}`).join(".");d?.(le)}},style:{position:"absolute",top:j.box.top,left:j.box.left,width:j.box.width,height:j.box.height,minWidth:Ah,minHeight:Ah,boxSizing:"border-box",pointerEvents:"auto",cursor:"pointer",outline:oe?"2px solid #2563eb":"none",outlineOffset:-2,background:ue&&!oe?"rgba(37,99,235,0.14)":"transparent"}},`cell-${j.ref.gridRow}-${j.ref.gridCol}`)}),i.jsx("div",{"data-testid":"g7le-inplace-col-rail",onMouseEnter:A,onMouseLeave:z,style:{position:"absolute",top:$e,left:n.left,width:n.width,height:pl,pointerEvents:"none"},children:ae!==null&&Ne.has(ae)&&(()=>{const j=ae,oe=Ne.get(j),ue=wi(f,j,-1),J=wi(f,j,1),le=oe.left-n.left;return i.jsxs("div",{"data-testid":`g7le-inplace-colgutter-${j}`,onMouseEnter:()=>{A(),N(j)},onMouseLeave:z,style:{position:"absolute",top:0,left:le,width:oe.width,minWidth:96,height:pl,display:"flex",gap:3,justifyContent:"center",alignItems:"center",pointerEvents:"auto"},children:[i.jsx("button",{type:"button",title:a("layout_editor.table_inplace.move_col_left"),disabled:!ue.ok,onClick:()=>P(j,-1),"data-testid":`g7le-inplace-col-left-${j}`,style:ue.ok?_n:Ei,children:"←"}),i.jsx("button",{type:"button",title:a("layout_editor.table_inplace.add_col"),onClick:()=>L(j),"data-testid":`g7le-inplace-col-add-${j}`,style:_n,children:"+"}),i.jsx("button",{type:"button",title:a("layout_editor.table_inplace.remove_col"),disabled:f.colCount<=1,onClick:()=>I(j),"data-testid":`g7le-inplace-col-remove-${j}`,style:Dh,children:"✕"}),i.jsx("button",{type:"button",title:a("layout_editor.table_inplace.move_col_right"),disabled:!J.ok,onClick:()=>P(j,1),"data-testid":`g7le-inplace-col-right-${j}`,style:J.ok?_n:Ei,children:"→"})]},`colgut-${j}`)})()}),i.jsx("div",{"data-testid":"g7le-inplace-row-rail",style:{position:"absolute",top:n.top,left:be,width:fl,height:n.height,pointerEvents:"none"},children:pe!==null&&Le.has(pe)&&(()=>{const j=pe,oe=Le.get(j),ue=xi(f,j,-1),J=xi(f,j,1),le=oe.top-n.top;return i.jsxs("div",{"data-testid":`g7le-inplace-rowgutter-${j}`,onMouseEnter:()=>{A(),E(j)},onMouseLeave:z,style:{position:"absolute",top:le,left:0,width:fl,height:oe.height,minHeight:48,display:"grid",gridTemplateColumns:"repeat(2, 22px)",gridAutoRows:"22px",gap:3,justifyContent:"center",alignContent:"center",pointerEvents:"auto"},children:[i.jsx("button",{type:"button",title:a("layout_editor.table_inplace.move_row_up"),disabled:!ue.ok,onClick:()=>H(j,-1),"data-testid":`g7le-inplace-row-up-${j}`,style:ue.ok?_n:Ei,children:"↑"}),i.jsx("button",{type:"button",title:a("layout_editor.table_inplace.add_row"),onClick:()=>B(j),"data-testid":`g7le-inplace-row-add-${j}`,style:_n,children:"+"}),i.jsx("button",{type:"button",title:a("layout_editor.table_inplace.remove_row"),disabled:f.rows.length<=1,onClick:()=>T(j),"data-testid":`g7le-inplace-row-remove-${j}`,style:Dh,children:"✕"}),i.jsx("button",{type:"button",title:a("layout_editor.table_inplace.move_row_down"),disabled:!J.ok,onClick:()=>H(j,1),"data-testid":`g7le-inplace-row-down-${j}`,style:J.ok?_n:Ei,children:"↓"})]},`rowgut-${j}`)})()}),i.jsxs("div",{"data-testid":"g7le-inplace-corner-add",style:{position:"absolute",top:n.top+n.height+gl,left:n.left,display:"flex",flexDirection:"column",gap:6,pointerEvents:"auto",minWidth:200,maxWidth:Math.max(240,n.width),background:"#fff",border:"1px solid #e2e8f0",borderRadius:8,padding:8,boxShadow:"0 2px 8px rgba(0,0,0,0.12)"},children:[i.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap"},children:[i.jsxs("button",{type:"button","data-testid":"g7le-inplace-add-row-bottom",onClick:()=>B(f.rows.length-1),style:Nh,children:["+ ",a("layout_editor.table_inplace.add_row")]}),i.jsxs("button",{type:"button","data-testid":"g7le-inplace-add-col-right",onClick:()=>L(f.colCount-1),style:Nh,children:["+ ",a("layout_editor.table_inplace.add_col")]})]}),!b&&i.jsx("div",{"data-testid":"g7le-inplace-select-hint",style:{fontSize:11,color:"#94a3b8",borderTop:"1px solid #f1f5f9",paddingTop:6},children:a("layout_editor.table_inplace.select_cell_hint")}),b&&i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6,borderTop:"1px solid #f1f5f9",paddingTop:6},children:[se&&i.jsx("div",{"data-testid":"g7le-inplace-range-count",style:{fontSize:11,color:"#2563eb"},children:a("layout_editor.table_inplace.range_selected",{count:Z.length})}),i.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap",alignItems:"center"},children:[se?i.jsx("button",{type:"button","data-testid":"g7le-inplace-merge-range",onClick:re,style:or,children:a("layout_editor.table_inplace.merge_range")}):i.jsxs(i.Fragment,{children:[i.jsx("button",{type:"button","data-testid":"g7le-inplace-merge-right",disabled:!G,onClick:()=>F("right"),style:G?or:hl,children:a("layout_editor.table_inplace.merge_right")}),i.jsx("button",{type:"button","data-testid":"g7le-inplace-merge-down",disabled:!V,onClick:()=>F("down"),style:V?or:hl,children:a("layout_editor.table_inplace.merge_down")})]}),i.jsx("button",{type:"button","data-testid":"g7le-inplace-unmerge",disabled:!q,onClick:U,style:q?or:hl,children:a("layout_editor.table_inplace.unmerge")})]}),i.jsxs("div",{"data-testid":"g7le-inplace-cell-color",style:{borderTop:"1px solid #f1f5f9",paddingTop:6,display:"flex",flexDirection:"column",gap:6},children:[i.jsxs("label",{style:{display:"flex",alignItems:"center",gap:6,fontSize:11,color:"#475569",cursor:"pointer"},children:[i.jsx("input",{type:"checkbox","data-testid":"g7le-inplace-border-all-toggle",checked:x,onChange:j=>k(j.target.checked)}),a("layout_editor.table_inplace.border_apply_all")]}),i.jsx(fh,{colorScheme:w,onChange:_,t:a}),ee&&i.jsx("div",{"data-testid":"g7le-inplace-cell-border",children:i.jsx(sh,{className:x?"":M,catalog:ee,t:a,onChange:me,colorScheme:w,onPresetToken:De,colorStyle:x?"":Qe,onColorStyle:Pe})}),i.jsx("div",{"data-testid":"g7le-inplace-cell-fill",children:i.jsx(ch,{colorStyle:x?"":ie,className:x?"":_e,catalog:fe,t:a,colorScheme:w,onPresetToken:ve,onCustomColor:te,onClear:he})})]}),i.jsx("div",{"data-testid":"g7le-inplace-cell-padding",style:{borderTop:"1px solid #f1f5f9",paddingTop:6},children:i.jsx(uh,{paddingStyle:x?"":ge,catalog:K,t:a,onChange:Q})})]})]})]})}const _n={width:22,height:22,lineHeight:"20px",padding:0,fontSize:13,border:"1px solid #cbd5e1",borderRadius:5,background:"#fff",color:"#475569",cursor:"pointer",boxShadow:"0 1px 3px rgba(0,0,0,0.18)"},Dh={..._n,border:"1px solid #fecaca",color:"#dc2626"},Ei={..._n,cursor:"not-allowed",opacity:.4,color:"#94a3b8",borderColor:"#e2e8f0"},or={padding:"4px 10px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",boxShadow:"0 1px 2px rgba(0,0,0,0.12)"},hl={...or,cursor:"not-allowed",opacity:.4},Nh={padding:"3px 8px",fontSize:11,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"};let zh=!1;function Mz(){zh||(Pn("children",Kg),Pn("table",$8),Pn("array",kh),Pn("array-group",uz),Pn("array-cell-tree",vz),Oa("table",zz),zh=!0)}function Lz(){if(typeof window>"u")return;const e=window.G7Core;if(!e)return;const t=e.layoutEditor,n=Array.isArray(t?.__queue)?t.__queue:[],o=Array.isArray(t?.__readyCallbacks)?t.__readyCallbacks:[];e.layoutEditor={registerWidget:Xe,registerNodeEditor:Pn,registerCanvasOverlay:Oa,onReady:r=>{typeof r=="function"&&r()}};for(const r of n){const[s,...a]=r;try{s==="widget"?Xe(a[0],a[1]):s==="nodeEditor"?Pn(a[0],a[1]):s==="canvasOverlay"&&Oa(a[0],a[1])}catch{}}for(const r of o)try{r()}catch{}}const Pz=1280;FN(),Mz(),Lz();async function Oz(e){if(typeof fetch!="function")return[];try{const t=await fetch(en(`/api/admin/templates/${encodeURIComponent(e)}/editor/permission-candidates`,"json"),{credentials:"same-origin",headers:je()});if(!t.ok)return[];const o=(await t.json().catch(()=>null))?.data?.permissions;if(!Array.isArray(o))return[];const r=[];for(const s of o)if(s&&typeof s=="object"){const a=s.key,l=s.name;typeof a=="string"&&a.length>0&&r.push({value:a,label:typeof l=="string"&&l?l:a})}return r}catch{return[]}}function Bz({templateIdentifier:e}){cD({templateIdentifier:e}),uD(e);const{state:t,dispatch:n}=Je(),{t:o}=tt(),r=yo(),s=wp(),a=bD(),l=t.selectedRoute?.layoutName??null,d=xD(e,l),c=t.editMode==="extension",p=u.useMemo(()=>c?vD(a):s,[c,a,s]),[f,y]=u.useState(null),[g,m]=u.useState(null),[h,v]=u.useState([]),[b,x]=u.useState("user"),[k,w]=u.useState(null),[_,S]=u.useState(null),[E,C]=u.useState([]);u.useEffect(()=>{let te=!1;return(async()=>{try{const he=await fetch(en(`/api/templates/${encodeURIComponent(e)}/components`,"json"),{credentials:"same-origin",headers:{Accept:"application/json"}});if(!he.ok)return;const Q=await he.json().catch(()=>null);!te&&Q&&typeof Q=="object"&&y(Q)}catch{}})(),()=>{te=!0}},[e]),u.useEffect(()=>{let te=!1;return(async()=>{const{spec:he,sampleGlobalSources:Q}=await Zy({templateIdentifier:e,coreSeed:wD()});te||(m(he),v(Q),jz(e,he,Q))})(),()=>{te=!0}},[e]),u.useEffect(()=>{let te=!1;return(async()=>{if(typeof fetch=="function")try{const he=await fetch(`/api/admin/templates/${encodeURIComponent(e)}`,{credentials:"same-origin",headers:je()});if(!he.ok)return;const ie=(await he.json().catch(()=>null))?.data,_e=ie?.type;te||((_e==="admin"||_e==="user")&&x(_e),typeof ie?.name=="string"&&ie.name&&w(ie.name),typeof ie?.version=="string"&&ie.version&&S(ie.version))}catch{}})(),()=>{te=!0}},[e]),u.useEffect(()=>{let te=!1;return(async()=>{if(typeof fetch=="function")try{const he=await fetch("/api/admin/templates/?per_page=100&page=1",{credentials:"same-origin",headers:je()});if(!he.ok)return;const ie=(await he.json().catch(()=>null))?.data?.data;if(!te&&Array.isArray(ie)){const _e=[];for(const ge of ie){if(!ge||typeof ge!="object")continue;const Ae=ge.identifier;if(typeof Ae!="string"||!Ae||ge.is_pending===!0)continue;const Le=ge.type==="admin"?"admin":"user",q=ge.name,ae=ge.version;_e.push({identifier:Ae,name:typeof q=="string"?q:Ae,version:typeof ae=="string"?ae:"",type:Le})}C(_e)}}catch{}})(),()=>{te=!0}},[e]);const N=g?.nesting??null,$=t.selectedRoute?.path??null,A=t.editMode,z=t.selectedRoute?.layoutName??(c?a.document?.hostLayoutName??null:null),D=t.routeTree,O=u.useMemo(()=>{if(A!=="extension"||!z)return null;const te=bl(D,z);return te||`__base__/${z}`},[A,z,D]),M=c&&t.returnRoute===null&&!!z;u.useEffect(()=>{if(!M||!z)return;const te=bl(D,z);te&&n({type:"SET_RETURN_ROUTE",route:{path:te,layoutName:z}})},[M,z,D,n]),u.useEffect(()=>{const te=K4(A,$,O),he=V4(g?.states?.groups,te);n({type:"SET_AVAILABLE_STATES",states:he,activeStateId:U4(he)})},[g,A,$,O,n]);const[B,T]=u.useState([]);u.useEffect(()=>{let te=!1;return(async()=>{const he=await Oz(e);te||T(he)})(),()=>{te=!0}},[e]),pD(),fD();const H=u.useCallback(te=>{const he=t.routeTree,Q=te.split("?")[0]?.split("#")[0]??te;return Wz(he,Q)?"route_in_tree":"route_not_in_tree"},[t.routeTree]),L=u.useCallback(te=>{const he=te.split("?")[0]?.split("#")[0]??te,Q=yl(t.routeTree,he);Q&&(p.isDirty&&!(!(typeof window<"u")||window.confirm(o("layout_editor.chrome.dirty_guard.message")))||n({type:"SELECT_ROUTE",route:{path:Q.path,layoutName:Q.layoutName}}))},[t.routeTree,p.isDirty,n]),I=u.useRef([]),P=u.useCallback(te=>{I.current=te},[]),[F,G]=u.useState(null),V=u.useCallback(()=>G(null),[]),Y=u.useRef(null),Z=u.useRef(null);u.useEffect(()=>{const te=Z.current,he=Y.current;if(!te||!he||typeof ResizeObserver>"u")return;const Q=()=>{he.style.setProperty("--g7le-header-h",`${Math.round(te.getBoundingClientRect().height)}px`)};Q();const ie=new ResizeObserver(Q);return ie.observe(te),()=>ie.disconnect()},[]);const se=u.useCallback(()=>{p.reload()},[p]),re=u.useCallback(()=>{p.isDirty&&!(!(typeof window<"u")||window.confirm(o("layout_editor.chrome.dirty_guard.message")))||window.G7Core?.dispatch?.({handler:"openWindow",params:{path:`/admin/templates/${b}`,target:"_self"}})},[p.isDirty,o,b]),U=u.useCallback(te=>{if(!te||te===e||p.isDirty&&!(typeof window<"u"?window.confirm(o("layout_editor.chrome.dirty_guard.message")):!0))return;const he=Zs(te);window.G7Core?.dispatch?.({handler:"openWindow",params:{path:he,target:"_self"}})},[e,p.isDirty,o]),ee=u.useCallback(()=>{const te=TE(e,t.selectedRoute?.path??null);window.G7Core?.dispatch?.({handler:"openWindow",params:{path:te}})},[e,t.selectedRoute]),fe=u.useCallback(()=>{const te=t.selectedRoute?.layoutName??"";if(!te)return;const he=r.open({ariaLabel:o("layout_editor.attachment_manager.title"),width:720,maxHeightRatio:.82,content:u.createElement(Ml,{templateIdentifier:e,layoutName:te,t:o,onClose:()=>r.close(he)})})},[r,e,t.selectedRoute,o]),K=u.useCallback(()=>{const te=t.selectedRoute?.layoutName??"";if(!te)return;const he=By(s.document?.raw??{}),Q=r.open({ariaLabel:o("layout_editor.translation_manager.title"),width:720,maxHeightRatio:.82,content:u.createElement(sm,{templateIdentifier:e,layoutName:te,t:o,referencedKeys:he,onClose:()=>r.close(Q)})})},[r,e,t.selectedRoute,o,s.document]),ne=u.useCallback((te,he)=>{const Q=window.G7Core;if(Q&&typeof Q.t=="function"){const ie=Q.t(te,he);if(ie&&ie!==te&&!ie.startsWith("$t:"))return ie}return o(te,he)},[o]),me=u.useCallback(()=>{if(!t.selectedRoute||t.editMode==="extension"||t.editMode==="iteration_item")return;const te=r.open({ariaLabel:o("layout_editor.page_settings.title",{name:t.selectedRoute.path??""}),width:1080,maxHeightRatio:.88,closeOnEscape:!1,content:u.createElement(l$,{templateIdentifier:e,spec:g,t:o,resolveLabel:ne,permissionCandidates:B,onClose:()=>r.close(te)})})},[r,t.selectedRoute,t.editMode,o,ne,e,g,B]),Ce=u.useCallback(async()=>{const te=await d.createPreview(s.document?.raw??null);if(te.kind!=="success"){const he=te.kind==="network_error"?te.message:o("layout_editor.preview_action.no_document");typeof window<"u"&&window.alert(he)}},[d,s.document,o]),ze=u.useCallback(()=>{const te=t.selectedRoute?.layoutName??"",he=t.selectedRoute?.path??"",Q=t.editMode==="extension"&&he.startsWith("__extension__/")?he.slice(14):null,ie=Q?{kind:"extension",extensionId:Q}:te?{kind:"layout",layoutName:te}:null;if(!ie)return;const _e=r.open({ariaLabel:o("layout_editor.version_history.title"),width:640,maxHeightRatio:.82,content:u.createElement(q$,{templateIdentifier:e,target:ie,t:o,onRestored:async ge=>{typeof ge=="number"&&(ie.kind==="extension"?n({type:"SET_EXTENSION_VERSION",extensionId:ie.extensionId,version:ge}):n({type:"SET_LAYOUT_VERSION",layoutName:ie.layoutName,version:ge})),await p.reload()},onClose:()=>r.close(_e)})})},[r,e,t.selectedRoute,t.editMode,o,p,n]),Se=p.dirtyKeys.size>0||p.isDirty;u.useEffect(()=>{if(!Se)return;const te=he=>{he.preventDefault(),he.returnValue=""};return window.addEventListener("beforeunload",te),()=>window.removeEventListener("beforeunload",te)},[Se]);const qe=u.useCallback(()=>{!p.isDirty||!(!(typeof window<"u")||window.confirm(o("layout_editor.chrome.reset_guard.message")))||p.reload()},[p,o]),De=u.useCallback(async()=>{const te=await p.save({sessionAddedPaths:I.current});G(te),te.kind==="success"&&typeof te.newContentVersion=="number"&&(te.savedExtensionId?n({type:"SET_EXTENSION_VERSION",extensionId:te.savedExtensionId,version:te.newContentVersion}):te.savedLayoutName&&n({type:"SET_LAYOUT_VERSION",layoutName:te.savedLayoutName,version:te.newContentVersion}))},[p,n]),Pe=u.useCallback(()=>{const te=r.open({ariaLabel:o("layout_editor.shortcuts.title"),width:560,maxHeightRatio:.85,content:u.createElement(tE,{t:o,onClose:()=>r.close(te)})})},[r,o]),Qe=u.useMemo(()=>({save:()=>{De()},exit:re,editCode:ee,reset:qe,translations:K,addElement:()=>{t.selectedRoute&&n({type:"TOGGLE_PALETTE"})},help:Pe,preview:()=>{t.selectedRoute?.layoutName&&Ce()}}),[De,re,ee,qe,K,t.selectedRoute,n,Pe,Ce]),[Me,Re]=u.useState(!1);u.useEffect(()=>{const te=window.setInterval(()=>{Re(!!window.__g7LayoutEditorHasSelection)},200);return()=>window.clearInterval(te)},[]),Ru({handlers:Qe,hasSelection:Me});const ve=p;return t.routesError?i.jsx("div",{className:"g7le-chrome g7le-chrome--routes-error","data-testid":"g7le-chrome-routes-error",style:{position:"fixed",inset:0,display:"flex",background:"#f8fafc",color:"#0f172a",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Apple SD Gothic Neo", "Noto Sans KR", sans-serif',fontSize:13,lineHeight:1.5,zIndex:9e3},children:i.jsx(Fa,{error:t.routesError})}):i.jsx("div",{className:"g7le-chrome","data-testid":"g7le-chrome",ref:Y,style:{position:"static",minHeight:"100vh",minWidth:Pz,background:"#f8fafc",color:"#0f172a",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Apple SD Gothic Neo", "Noto Sans KR", sans-serif',fontSize:13,lineHeight:1.5,zIndex:9e3},children:i.jsxs(sy,{value:ve,children:[c&&a.needsHostPicker&&a.document&&i.jsx(_D,{hostLayouts:a.document.hostLayouts,extensionLabel:null,onSelect:a.selectHost}),i.jsxs("div",{className:"g7le-chrome__header","data-testid":"g7le-chrome-header",ref:Z,style:{position:"sticky",top:0,zIndex:20,background:"#f8fafc"},children:[i.jsx(gy,{onSave:()=>{De()},isDirty:p.isDirty,onExit:re,onEditCode:ee,onManageImages:fe,onManageTranslations:K,onPageSettings:me,onReset:qe,onShowShortcuts:Pe,onPreview:Ce,onShowVersions:ze,templateName:k,templateVersion:_,templateList:E,onSwitchTemplate:U}),i.jsx(bE,{result:F,onDismiss:V,onLoadLatest:se}),i.jsxs("div",{className:"g7le-chrome__device-toolbar","data-testid":"g7le-chrome-device-toolbar",style:{display:"flex",justifyContent:"center",padding:"6px 12px",background:"#f1f5f9",borderBottom:"1px solid #e2e8f0"},children:[i.jsx(H4,{}),i.jsx(F4,{})]})]}),i.jsxs("div",{className:"g7le-chrome__body",style:{display:"grid",gridTemplateColumns:"auto 1fr",alignItems:"stretch"},children:[i.jsx(OE,{}),i.jsx(P4,{manifest:f,nesting:N,componentPalette:g?.componentPalette??null,spec:g,permissionCandidates:B,sampleGlobalSources:h,resolveRouteMatch:H,onNavigateToDestination:L,onSessionAddedPathsChange:P})]}),i.jsx(dy,{})]})})}function yl(e,t){for(const n of e){if(n.kind==="route"&&n.path===t)return n;if(n.children&&n.children.length>0){const o=yl(n.children,t);if(o)return o}}return null}function Wz(e,t){return yl(e,t)!==null}function bl(e,t){for(const n of e){if(n.kind==="route"&&n.layoutName===t&&typeof n.path=="string")return n.path;if(n.children&&n.children.length>0){const o=bl(n.children,t);if(o)return o}}return null}function jz(e,t,n){const o=[];Va({sources:n,isGuestOnly:!1,warn:s=>{const a=/extension '([^']+)' override of core key '([^']+)'/.exec(s);a&&o.push(`${a[1]}:${a[2]}`)}});const r=t?.sampleData?.byDataSourceId?Object.keys(t.sampleData.byDataSourceId).length:0;Xh({templateIdentifier:e,mergedSources:[...n.map(s=>({kind:s.kind,id:s.id}))],blockCounts:{controls:t?.controls?Object.keys(t.controls).length:0,componentCapabilities:t?.componentCapabilities?Object.keys(t.componentCapabilities).length:0,actionRecipes:t?.actionRecipes?Object.keys(t.actionRecipes).length:0,conditionRecipes:t?.conditionRecipes?Object.keys(t.conditionRecipes).length:0,paletteGroups:t?.componentPalette?.groups?.length??0,stateGroups:t?.states?.groups?.length??0,sampleDataIds:r},sampleGlobalSourceCount:n.length,sampleGlobalConflicts:o,timestamp:Date.now()})}function Mh({templateIdentifier:e,initialLocale:t}){return u.useEffect(()=>()=>{Hh(),Kh(),Uh(),qh(),Gh(),Yh(),Jh(),Zh(),Qh()},[]),i.jsx(iy,{templateIdentifier:e,initialLocale:t,children:i.jsx(ly,{children:i.jsx(Bz,{templateIdentifier:e})})})}if(typeof window<"u"){const e=window.G7Core||(window.G7Core={});if(e.__LayoutEditorChrome=Mh,typeof e.__onChromeReady=="function")try{e.__onChromeReady()}catch{}}dn.LayoutEditorChrome=Mh,Object.defineProperty(dn,Symbol.toStringTag,{value:"Module"})})(this.G7LayoutEditor=this.G7LayoutEditor||{},ReactJSXRuntime,React,ReactDOM); +//# sourceMappingURL=layout-editor.min.js.map diff --git a/public/build/core/template-engine.min.js b/public/build/core/template-engine.min.js index d1a82997..e5a9507f 100644 --- a/public/build/core/template-engine.min.js +++ b/public/build/core/template-engine.min.js @@ -1,20 +1,20 @@ -var Qx=Object.defineProperty;var Zx=(Ft,Wa,Ya)=>Wa in Ft?Qx(Ft,Wa,{enumerable:!0,configurable:!0,writable:!0,value:Ya}):Ft[Wa]=Ya;var $=(Ft,Wa,Ya)=>Zx(Ft,typeof Wa!="symbol"?Wa+"":Wa,Ya);(function(Ft){"use strict";function Wa(o,e){for(var a=0;ar[i]})}}}return Object.freeze(Object.defineProperty(o,Symbol.toStringTag,{value:"Module"}))}function Ya(o){return o&&o.__esModule&&Object.prototype.hasOwnProperty.call(o,"default")?o.default:o}var Vu={exports:{}},Ke={};var Mg;function OS(){if(Mg)return Ke;Mg=1;var o=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),a=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),l=Symbol.for("react.consumer"),u=Symbol.for("react.context"),d=Symbol.for("react.forward_ref"),f=Symbol.for("react.suspense"),g=Symbol.for("react.memo"),m=Symbol.for("react.lazy"),b=Symbol.for("react.activity"),v=Symbol.iterator;function S(x){return x===null||typeof x!="object"?null:(x=v&&x[v]||x["@@iterator"],typeof x=="function"?x:null)}var E={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},A=Object.assign,T={};function L(x,K,re){this.props=x,this.context=K,this.refs=T,this.updater=re||E}L.prototype.isReactComponent={},L.prototype.setState=function(x,K){if(typeof x!="object"&&typeof x!="function"&&x!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,x,K,"setState")},L.prototype.forceUpdate=function(x){this.updater.enqueueForceUpdate(this,x,"forceUpdate")};function M(){}M.prototype=L.prototype;function R(x,K,re){this.props=x,this.context=K,this.refs=T,this.updater=re||E}var D=R.prototype=new M;D.constructor=R,A(D,L.prototype),D.isPureReactComponent=!0;var U=Array.isArray;function j(){}var P={H:null,A:null,T:null,S:null},X=Object.prototype.hasOwnProperty;function ge(x,K,re){var de=re.ref;return{$$typeof:o,type:x,key:K,ref:de!==void 0?de:null,props:re}}function Ee(x,K){return ge(x.type,K,x.props)}function Ce(x){return typeof x=="object"&&x!==null&&x.$$typeof===o}function $e(x){var K={"=":"=0",":":"=2"};return"$"+x.replace(/[=:]/g,function(re){return K[re]})}var Pe=/\/+/g;function Xe(x,K){return typeof x=="object"&&x!==null&&x.key!=null?$e(""+x.key):K.toString(36)}function ht(x){switch(x.status){case"fulfilled":return x.value;case"rejected":throw x.reason;default:switch(typeof x.status=="string"?x.then(j,j):(x.status="pending",x.then(function(K){x.status==="pending"&&(x.status="fulfilled",x.value=K)},function(K){x.status==="pending"&&(x.status="rejected",x.reason=K)})),x.status){case"fulfilled":return x.value;case"rejected":throw x.reason}}throw x}function Q(x,K,re,de,ie){var me=typeof x;(me==="undefined"||me==="boolean")&&(x=null);var Ne=!1;if(x===null)Ne=!0;else switch(me){case"bigint":case"string":case"number":Ne=!0;break;case"object":switch(x.$$typeof){case o:case e:Ne=!0;break;case m:return Ne=x._init,Q(Ne(x._payload),K,re,de,ie)}}if(Ne)return ie=ie(x),Ne=de===""?"."+Xe(x,0):de,U(ie)?(re="",Ne!=null&&(re=Ne.replace(Pe,"$&/")+"/"),Q(ie,K,re,"",function(Ae){return Ae})):ie!=null&&(Ce(ie)&&(ie=Ee(ie,re+(ie.key==null||x&&x.key===ie.key?"":(""+ie.key).replace(Pe,"$&/")+"/")+Ne)),K.push(ie)),1;Ne=0;var Se=de===""?".":de+":";if(U(x))for(var He=0;He>>1,he=Q[te];if(0>>1;tei(re,ye))dei(ie,re)?(Q[te]=ie,Q[de]=ye,te=de):(Q[te]=re,Q[K]=ye,te=K);else if(dei(ie,ye))Q[te]=ie,Q[de]=ye,te=de;else break e}}return fe}function i(Q,fe){var ye=Q.sortIndex-fe.sortIndex;return ye!==0?ye:Q.id-fe.id}if(o.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var l=performance;o.unstable_now=function(){return l.now()}}else{var u=Date,d=u.now();o.unstable_now=function(){return u.now()-d}}var f=[],g=[],m=1,b=null,v=3,S=!1,E=!1,A=!1,T=!1,L=typeof setTimeout=="function"?setTimeout:null,M=typeof clearTimeout=="function"?clearTimeout:null,R=typeof setImmediate<"u"?setImmediate:null;function D(Q){for(var fe=a(g);fe!==null;){if(fe.callback===null)r(g);else if(fe.startTime<=Q)r(g),fe.sortIndex=fe.expirationTime,e(f,fe);else break;fe=a(g)}}function U(Q){if(A=!1,D(Q),!E)if(a(f)!==null)E=!0,j||(j=!0,$e());else{var fe=a(g);fe!==null&&ht(U,fe.startTime-Q)}}var j=!1,P=-1,X=5,ge=-1;function Ee(){return T?!0:!(o.unstable_now()-geQ&&Ee());){var te=b.callback;if(typeof te=="function"){b.callback=null,v=b.priorityLevel;var he=te(b.expirationTime<=Q);if(Q=o.unstable_now(),typeof he=="function"){b.callback=he,D(Q),fe=!0;break t}b===a(f)&&r(f),D(Q)}else r(f);b=a(f)}if(b!==null)fe=!0;else{var x=a(g);x!==null&&ht(U,x.startTime-Q),fe=!1}}break e}finally{b=null,v=ye,S=!1}fe=void 0}}finally{fe?$e():j=!1}}}var $e;if(typeof R=="function")$e=function(){R(Ce)};else if(typeof MessageChannel<"u"){var Pe=new MessageChannel,Xe=Pe.port2;Pe.port1.onmessage=Ce,$e=function(){Xe.postMessage(null)}}else $e=function(){L(Ce,0)};function ht(Q,fe){P=L(function(){Q(o.unstable_now())},fe)}o.unstable_IdlePriority=5,o.unstable_ImmediatePriority=1,o.unstable_LowPriority=4,o.unstable_NormalPriority=3,o.unstable_Profiling=null,o.unstable_UserBlockingPriority=2,o.unstable_cancelCallback=function(Q){Q.callback=null},o.unstable_forceFrameRate=function(Q){0>Q||125te?(Q.sortIndex=ye,e(g,Q),a(f)===null&&Q===a(g)&&(A?(M(P),P=-1):A=!0,ht(U,ye-te))):(Q.sortIndex=he,e(f,Q),E||S||(E=!0,j||(j=!0,$e()))),Q},o.unstable_shouldYield=Ee,o.unstable_wrapCallback=function(Q){var fe=v;return function(){var ye=v;v=fe;try{return Q.apply(this,arguments)}finally{v=ye}}}})(Yu)),Yu}var Ig;function MS(){return Ig||(Ig=1,Wu.exports=LS()),Wu.exports}var Xu={exports:{}},mn={};var Hg;function $S(){if(Hg)return mn;Hg=1;var o=Fu();function e(f){var g="https://react.dev/errors/"+f;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(o)}catch(e){console.error(e)}}return o(),Xu.exports=$S(),Xu.exports}var Ug;function NS(){if(Ug)return Vs;Ug=1;var o=MS(),e=Fu(),a=jg();function r(t){var n="https://react.dev/errors/"+t;if(1he||(t.current=te[he],te[he]=null,he--)}function re(t,n){he++,te[he]=t.current,t.current=n}var de=x(null),ie=x(null),me=x(null),Ne=x(null);function Se(t,n){switch(re(me,n),re(ie,t),re(de,null),n.nodeType){case 9:case 11:t=(t=n.documentElement)&&(t=t.namespaceURI)?Jv(t):0;break;default:if(t=n.tagName,n=n.namespaceURI)n=Jv(n),t=Qv(n,t);else switch(t){case"svg":t=1;break;case"math":t=2;break;default:t=0}}K(de),re(de,t)}function He(){K(de),K(ie),K(me)}function Ae(t){t.memoizedState!==null&&re(Ne,t);var n=de.current,s=Qv(n,t.type);n!==s&&(re(ie,t),re(de,s))}function Et(t){ie.current===t&&(K(de),K(ie)),Ne.current===t&&(K(Ne),wl._currentValue=ye)}var kt,_t;function ft(t){if(kt===void 0)try{throw Error()}catch(s){var n=s.stack.trim().match(/\n( *(at )?)/);kt=n&&n[1]||"",_t=-1Ya in Xt?gT(Xt,Ya,{enumerable:!0,configurable:!0,writable:!0,value:Xa}):Xt[Ya]=Xa;var $=(Xt,Ya,Xa)=>pT(Xt,typeof Ya!="symbol"?Ya+"":Ya,Xa);(function(Xt){"use strict";function Ya(o,e){for(var n=0;nr[i]})}}}return Object.freeze(Object.defineProperty(o,Symbol.toStringTag,{value:"Module"}))}function Xa(o){return o&&o.__esModule&&Object.prototype.hasOwnProperty.call(o,"default")?o.default:o}var Yu={exports:{}},We={};var Ig;function zS(){if(Ig)return We;Ig=1;var o=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),l=Symbol.for("react.consumer"),u=Symbol.for("react.context"),d=Symbol.for("react.forward_ref"),f=Symbol.for("react.suspense"),g=Symbol.for("react.memo"),m=Symbol.for("react.lazy"),b=Symbol.for("react.activity"),v=Symbol.iterator;function S(A){return A===null||typeof A!="object"?null:(A=v&&A[v]||A["@@iterator"],typeof A=="function"?A:null)}var _={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},x=Object.assign,k={};function O(A,K,ue){this.props=A,this.context=K,this.refs=k,this.updater=ue||_}O.prototype.isReactComponent={},O.prototype.setState=function(A,K){if(typeof A!="object"&&typeof A!="function"&&A!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,A,K,"setState")},O.prototype.forceUpdate=function(A){this.updater.enqueueForceUpdate(this,A,"forceUpdate")};function M(){}M.prototype=O.prototype;function T(A,K,ue){this.props=A,this.context=K,this.refs=k,this.updater=ue||_}var D=T.prototype=new M;D.constructor=T,x(D,O.prototype),D.isPureReactComponent=!0;var j=Array.isArray;function H(){}var P={H:null,A:null,T:null,S:null},X=Object.prototype.hasOwnProperty;function pe(A,K,ue){var he=ue.ref;return{$$typeof:o,type:A,key:K,ref:he!==void 0?he:null,props:ue}}function _e(A,K){return pe(A.type,K,A.props)}function we(A){return typeof A=="object"&&A!==null&&A.$$typeof===o}function Me(A){var K={"=":"=0",":":"=2"};return"$"+A.replace(/[=:]/g,function(ue){return K[ue]})}var qe=/\/+/g;function Je(A,K){return typeof A=="object"&&A!==null&&A.key!=null?Me(""+A.key):K.toString(36)}function gt(A){switch(A.status){case"fulfilled":return A.value;case"rejected":throw A.reason;default:switch(typeof A.status=="string"?A.then(H,H):(A.status="pending",A.then(function(K){A.status==="pending"&&(A.status="fulfilled",A.value=K)},function(K){A.status==="pending"&&(A.status="rejected",A.reason=K)})),A.status){case"fulfilled":return A.value;case"rejected":throw A.reason}}throw A}function Q(A,K,ue,he,le){var de=typeof A;(de==="undefined"||de==="boolean")&&(A=null);var Oe=!1;if(A===null)Oe=!0;else switch(de){case"bigint":case"string":case"number":Oe=!0;break;case"object":switch(A.$$typeof){case o:case e:Oe=!0;break;case m:return Oe=A._init,Q(Oe(A._payload),K,ue,he,le)}}if(Oe)return le=le(A),Oe=he===""?"."+Je(A,0):he,j(le)?(ue="",Oe!=null&&(ue=Oe.replace(qe,"$&/")+"/"),Q(le,K,ue,"",function(ke){return ke})):le!=null&&(we(le)&&(le=_e(le,ue+(le.key==null||A&&A.key===le.key?"":(""+le.key).replace(qe,"$&/")+"/")+Oe)),K.push(le)),1;Oe=0;var He=he===""?".":he+":";if(j(A))for(var Pe=0;Pe>>1,ge=Q[ae];if(0>>1;aei(ue,ve))hei(le,ue)?(Q[ae]=le,Q[he]=ve,ae=he):(Q[ae]=ue,Q[K]=ve,ae=K);else if(hei(le,ve))Q[ae]=le,Q[he]=ve,ae=he;else break e}}return fe}function i(Q,fe){var ve=Q.sortIndex-fe.sortIndex;return ve!==0?ve:Q.id-fe.id}if(o.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var l=performance;o.unstable_now=function(){return l.now()}}else{var u=Date,d=u.now();o.unstable_now=function(){return u.now()-d}}var f=[],g=[],m=1,b=null,v=3,S=!1,_=!1,x=!1,k=!1,O=typeof setTimeout=="function"?setTimeout:null,M=typeof clearTimeout=="function"?clearTimeout:null,T=typeof setImmediate<"u"?setImmediate:null;function D(Q){for(var fe=n(g);fe!==null;){if(fe.callback===null)r(g);else if(fe.startTime<=Q)r(g),fe.sortIndex=fe.expirationTime,e(f,fe);else break;fe=n(g)}}function j(Q){if(x=!1,D(Q),!_)if(n(f)!==null)_=!0,H||(H=!0,Me());else{var fe=n(g);fe!==null&>(j,fe.startTime-Q)}}var H=!1,P=-1,X=5,pe=-1;function _e(){return k?!0:!(o.unstable_now()-peQ&&_e());){var ae=b.callback;if(typeof ae=="function"){b.callback=null,v=b.priorityLevel;var ge=ae(b.expirationTime<=Q);if(Q=o.unstable_now(),typeof ge=="function"){b.callback=ge,D(Q),fe=!0;break t}b===n(f)&&r(f),D(Q)}else r(f);b=n(f)}if(b!==null)fe=!0;else{var A=n(g);A!==null&>(j,A.startTime-Q),fe=!1}}break e}finally{b=null,v=ve,S=!1}fe=void 0}}finally{fe?Me():H=!1}}}var Me;if(typeof T=="function")Me=function(){T(we)};else if(typeof MessageChannel<"u"){var qe=new MessageChannel,Je=qe.port2;qe.port1.onmessage=we,Me=function(){Je.postMessage(null)}}else Me=function(){O(we,0)};function gt(Q,fe){P=O(function(){Q(o.unstable_now())},fe)}o.unstable_IdlePriority=5,o.unstable_ImmediatePriority=1,o.unstable_LowPriority=4,o.unstable_NormalPriority=3,o.unstable_Profiling=null,o.unstable_UserBlockingPriority=2,o.unstable_cancelCallback=function(Q){Q.callback=null},o.unstable_forceFrameRate=function(Q){0>Q||125ae?(Q.sortIndex=ve,e(g,Q),n(f)===null&&Q===n(g)&&(x?(M(P),P=-1):x=!0,gt(j,ve-ae))):(Q.sortIndex=ge,e(f,Q),_||S||(_=!0,H||(H=!0,Me()))),Q},o.unstable_shouldYield=_e,o.unstable_wrapCallback=function(Q){var fe=v;return function(){var ve=v;v=fe;try{return Q.apply(this,arguments)}finally{v=ve}}}})(Zu)),Zu}var jg;function US(){return jg||(jg=1,Qu.exports=jS()),Qu.exports}var ed={exports:{}},wn={};var Ug;function BS(){if(Ug)return wn;Ug=1;var o=Xu();function e(f){var g="https://react.dev/errors/"+f;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(o)}catch(e){console.error(e)}}return o(),ed.exports=BS(),ed.exports}var qg;function PS(){if(qg)return Ys;qg=1;var o=US(),e=Xu(),n=Pg();function r(t){var a="https://react.dev/errors/"+t;if(1ge||(t.current=ae[ge],ae[ge]=null,ge--)}function ue(t,a){ge++,ae[ge]=t.current,t.current=a}var he=A(null),le=A(null),de=A(null),Oe=A(null);function He(t,a){switch(ue(de,a),ue(le,t),ue(he,null),a.nodeType){case 9:case 11:t=(t=a.documentElement)&&(t=t.namespaceURI)?iS(t):0;break;default:if(t=a.tagName,a=a.namespaceURI)a=iS(a),t=sS(a,t);else switch(t){case"svg":t=1;break;case"math":t=2;break;default:t=0}}K(he),ue(he,t)}function Pe(){K(he),K(le),K(de)}function ke(t){t.memoizedState!==null&&ue(Oe,t);var a=he.current,s=sS(a,t.type);a!==s&&(ue(le,t),ue(he,s))}function Ot(t){le.current===t&&(K(he),K(le)),Oe.current===t&&(K(Oe),Al._currentValue=ve)}var ut,Ct;function vt(t){if(ut===void 0)try{throw Error()}catch(s){var a=s.stack.trim().match(/\n( *(at )?)/);ut=a&&a[1]||"",Ct=-1)":-1h||z[c]!==Y[h]){var ae=` -`+z[c].replace(" at new "," at ");return t.displayName&&ae.includes("")&&(ae=ae.replace("",t.displayName)),ae}while(1<=c&&0<=h);break}}}finally{un=!1,Error.prepareStackTrace=s}return(s=t?t.displayName||t.name:"")?ft(s):""}function ja(t,n){switch(t.tag){case 26:case 27:case 5:return ft(t.type);case 16:return ft("Lazy");case 13:return t.child!==n&&n!==null?ft("Suspense Fallback"):ft("Suspense");case 19:return ft("SuspenseList");case 0:case 15:return gt(t.type,!1);case 11:return gt(t.type.render,!1);case 1:return gt(t.type,!0);case 31:return ft("Activity");default:return""}}function kn(t){try{var n="",s=null;do n+=ja(t,s),s=t,t=t.return;while(t);return n}catch(c){return` +`+ut+t+Ct}var kt=!1;function Ee(t,a){if(!t||kt)return"";kt=!0;var s=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var c={DetermineComponentFrameRoot:function(){try{if(a){var ce=function(){throw Error()};if(Object.defineProperty(ce.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(ce,[])}catch(ee){var J=ee}Reflect.construct(t,[],ce)}else{try{ce.call()}catch(ee){J=ee}t.call(ce.prototype)}}else{try{throw Error()}catch(ee){J=ee}(ce=t())&&typeof ce.catch=="function"&&ce.catch(function(){})}}catch(ee){if(ee&&J&&typeof ee.stack=="string")return[ee.stack,J.stack]}return[null,null]}};c.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var h=Object.getOwnPropertyDescriptor(c.DetermineComponentFrameRoot,"name");h&&h.configurable&&Object.defineProperty(c.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var p=c.DetermineComponentFrameRoot(),C=p[0],R=p[1];if(C&&R){var U=C.split(` +`),Y=R.split(` +`);for(h=c=0;ch||U[c]!==Y[h]){var ne=` +`+U[c].replace(" at new "," at ");return t.displayName&&ne.includes("")&&(ne=ne.replace("",t.displayName)),ne}while(1<=c&&0<=h);break}}}finally{kt=!1,Error.prepareStackTrace=s}return(s=t?t.displayName||t.name:"")?vt(s):""}function Nt(t,a){switch(t.tag){case 26:case 27:case 5:return vt(t.type);case 16:return vt("Lazy");case 13:return t.child!==a&&a!==null?vt("Suspense Fallback"):vt("Suspense");case 19:return vt("SuspenseList");case 0:case 15:return Ee(t.type,!1);case 11:return Ee(t.type.render,!1);case 1:return Ee(t.type,!0);case 31:return vt("Activity");default:return""}}function zt(t){try{var a="",s=null;do a+=Nt(t,s),s=t,t=t.return;while(t);return a}catch(c){return` Error generating stack: `+c.message+` -`+c.stack}}var Dn=Object.prototype.hasOwnProperty,jt=o.unstable_scheduleCallback,On=o.unstable_cancelCallback,ea=o.unstable_shouldYield,Ua=o.unstable_requestPaint,Kt=o.unstable_now,Dr=o.unstable_getCurrentPriorityLevel,er=o.unstable_ImmediatePriority,bn=o.unstable_UserBlockingPriority,tn=o.unstable_NormalPriority,et=o.unstable_LowPriority,ta=o.unstable_IdlePriority,En=o.log,tr=o.unstable_setDisableYieldValue,Ea=null,nn=null;function _n(t){if(typeof En=="function"&&tr(t),nn&&typeof nn.setStrictMode=="function")try{nn.setStrictMode(Ea,t)}catch{}}var q=Math.clz32?Math.clz32:Z,ce=Math.log,le=Math.LN2;function Z(t){return t>>>=0,t===0?32:31-(ce(t)/le|0)|0}var be=256,ve=262144,Re=4194304;function xe(t){var n=t&42;if(n!==0)return n;switch(t&-t){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return t&261888;case 262144:case 524288:case 1048576:case 2097152:return t&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return t&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return t}}function je(t,n,s){var c=t.pendingLanes;if(c===0)return 0;var h=0,p=t.suspendedLanes,w=t.pingedLanes;t=t.warmLanes;var k=c&134217727;return k!==0?(c=k&~p,c!==0?h=xe(c):(w&=k,w!==0?h=xe(w):s||(s=k&~t,s!==0&&(h=xe(s))))):(k=c&~p,k!==0?h=xe(k):w!==0?h=xe(w):s||(s=c&~t,s!==0&&(h=xe(s)))),h===0?0:n!==0&&n!==h&&(n&p)===0&&(p=h&-h,s=n&-n,p>=s||p===32&&(s&4194048)!==0)?n:h}function ze(t,n){return(t.pendingLanes&~(t.suspendedLanes&~t.pingedLanes)&n)===0}function Le(t,n){switch(t){case 1:case 2:case 4:case 8:case 64:return n+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return n+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function ke(){var t=Re;return Re<<=1,(Re&62914560)===0&&(Re=4194304),t}function We(t){for(var n=[],s=0;31>s;s++)n.push(t);return n}function Fe(t,n){t.pendingLanes|=n,n!==268435456&&(t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0)}function _e(t,n,s,c,h,p){var w=t.pendingLanes;t.pendingLanes=s,t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0,t.expiredLanes&=s,t.entangledLanes&=s,t.errorRecoveryDisabledLanes&=s,t.shellSuspendCounter=0;var k=t.entanglements,z=t.expirationTimes,Y=t.hiddenUpdates;for(s=w&~s;0"u")return null;try{return t.activeElement||t.body}catch{return t.body}}var vf=/[\n"\\]/g;function $n(t){return t.replace(vf,function(n){return"\\"+n.charCodeAt(0).toString(16)+" "})}function ds(t,n,s,c,h,p,w,k){t.name="",w!=null&&typeof w!="function"&&typeof w!="symbol"&&typeof w!="boolean"?t.type=w:t.removeAttribute("type"),n!=null?w==="number"?(n===0&&t.value===""||t.value!=n)&&(t.value=""+Sn(n)):t.value!==""+Sn(n)&&(t.value=""+Sn(n)):w!=="submit"&&w!=="reset"||t.removeAttribute("value"),n!=null?ar(t,w,Sn(n)):s!=null?ar(t,w,Sn(s)):c!=null&&t.removeAttribute("value"),h==null&&p!=null&&(t.defaultChecked=!!p),h!=null&&(t.checked=h&&typeof h!="function"&&typeof h!="symbol"),k!=null&&typeof k!="function"&&typeof k!="symbol"&&typeof k!="boolean"?t.name=""+Sn(k):t.removeAttribute("name")}function Si(t,n,s,c,h,p,w,k){if(p!=null&&typeof p!="function"&&typeof p!="symbol"&&typeof p!="boolean"&&(t.type=p),n!=null||s!=null){if(!(p!=="submit"&&p!=="reset"||n!=null)){Do(t);return}s=s!=null?""+Sn(s):"",n=n!=null?""+Sn(n):s,k||n===t.value||(t.value=n),t.defaultValue=n}c=c??h,c=typeof c!="function"&&typeof c!="symbol"&&!!c,t.checked=k?t.checked:!!c,t.defaultChecked=!!c,w!=null&&typeof w!="function"&&typeof w!="symbol"&&typeof w!="boolean"&&(t.name=w),Do(t)}function ar(t,n,s){n==="number"&&Nr(t.ownerDocument)===t||t.defaultValue===""+s||(t.defaultValue=""+s)}function Ir(t,n,s,c){if(t=t.options,n){n={};for(var h=0;h"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),No=!1;if(xa)try{var Ci={};Object.defineProperty(Ci,"passive",{get:function(){No=!0}}),window.addEventListener("test",Ci,Ci),window.removeEventListener("test",Ci,Ci)}catch{No=!1}var qa=null,Io=null,hs=null;function Oc(){if(hs)return hs;var t,n=Io,s=n.length,c,h="value"in qa?qa.value:qa.textContent,p=h.length;for(t=0;t=ne),Ve=" ",ot=!1;function pt(t,n){switch(t){case"keyup":return O.indexOf(n.keyCode)!==-1;case"keydown":return n.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Nt(t){return t=t.detail,typeof t=="object"&&"data"in t?t.data:null}var Ra=!1;function Hf(t,n){switch(t){case"compositionend":return Nt(n);case"keypress":return n.which!==32?null:(ot=!0,Ve);case"textInput":return t=n.data,t===Ve&&ot?null:t;default:return null}}function zc(t,n){if(Ra)return t==="compositionend"||!I&&pt(t,n)?(t=Oc(),hs=Io=qa=null,Ra=!1,t):null;switch(t){case"paste":return null;case"keypress":if(!(n.ctrlKey||n.altKey||n.metaKey)||n.ctrlKey&&n.altKey){if(n.char&&1=n)return{node:s,offset:n-t};t=c}e:{for(;s;){if(s.nextSibling){s=s.nextSibling;break e}s=s.parentNode}s=void 0}s=py(s)}}function yy(t,n){return t&&n?t===n?!0:t&&t.nodeType===3?!1:n&&n.nodeType===3?yy(t,n.parentNode):"contains"in t?t.contains(n):t.compareDocumentPosition?!!(t.compareDocumentPosition(n)&16):!1:!1}function by(t){t=t!=null&&t.ownerDocument!=null&&t.ownerDocument.defaultView!=null?t.ownerDocument.defaultView:window;for(var n=Nr(t.document);n instanceof t.HTMLIFrameElement;){try{var s=typeof n.contentWindow.location.href=="string"}catch{s=!1}if(s)t=n.contentWindow;else break;n=Nr(t.document)}return n}function Pf(t){var n=t&&t.nodeName&&t.nodeName.toLowerCase();return n&&(n==="input"&&(t.type==="text"||t.type==="search"||t.type==="tel"||t.type==="url"||t.type==="password")||n==="textarea"||t.contentEditable==="true")}var OA=xa&&"documentMode"in document&&11>=document.documentMode,ys=null,qf=null,Fo=null,Gf=!1;function vy(t,n,s){var c=s.window===s?s.document:s.nodeType===9?s:s.ownerDocument;Gf||ys==null||ys!==Nr(c)||(c=ys,"selectionStart"in c&&Pf(c)?c={start:c.selectionStart,end:c.selectionEnd}:(c=(c.ownerDocument&&c.ownerDocument.defaultView||window).getSelection(),c={anchorNode:c.anchorNode,anchorOffset:c.anchorOffset,focusNode:c.focusNode,focusOffset:c.focusOffset}),Fo&&Vo(Fo,c)||(Fo=c,c=Du(qf,"onSelect"),0>=w,h-=w,Ga=1<<32-q(n)+h|s<Qe?(rt=Ie,Ie=null):rt=Ie.sibling;var yt=J(V,Ie,W[Qe],oe);if(yt===null){Ie===null&&(Ie=rt);break}t&&Ie&&yt.alternate===null&&n(V,Ie),G=p(yt,G,Qe),mt===null?qe=yt:mt.sibling=yt,mt=yt,Ie=rt}if(Qe===W.length)return s(V,Ie),lt&&or(V,Qe),qe;if(Ie===null){for(;QeQe?(rt=Ie,Ie=null):rt=Ie.sibling;var li=J(V,Ie,yt.value,oe);if(li===null){Ie===null&&(Ie=rt);break}t&&Ie&&li.alternate===null&&n(V,Ie),G=p(li,G,Qe),mt===null?qe=li:mt.sibling=li,mt=li,Ie=rt}if(yt.done)return s(V,Ie),lt&&or(V,Qe),qe;if(Ie===null){for(;!yt.done;Qe++,yt=W.next())yt=ue(V,yt.value,oe),yt!==null&&(G=p(yt,G,Qe),mt===null?qe=yt:mt.sibling=yt,mt=yt);return lt&&or(V,Qe),qe}for(Ie=c(Ie);!yt.done;Qe++,yt=W.next())yt=ee(Ie,V,Qe,yt.value,oe),yt!==null&&(t&&yt.alternate!==null&&Ie.delete(yt.key===null?Qe:yt.key),G=p(yt,G,Qe),mt===null?qe=yt:mt.sibling=yt,mt=yt);return t&&Ie.forEach(function(Jx){return n(V,Jx)}),lt&&or(V,Qe),qe}function Rt(V,G,W,oe){if(typeof W=="object"&&W!==null&&W.type===A&&W.key===null&&(W=W.props.children),typeof W=="object"&&W!==null){switch(W.$$typeof){case S:e:{for(var qe=W.key;G!==null;){if(G.key===qe){if(qe=W.type,qe===A){if(G.tag===7){s(V,G.sibling),oe=h(G,W.props.children),oe.return=V,V=oe;break e}}else if(G.elementType===qe||typeof qe=="object"&&qe!==null&&qe.$$typeof===X&&zi(qe)===G.type){s(V,G.sibling),oe=h(G,W.props),Qo(oe,W),oe.return=V,V=oe;break e}s(V,G);break}else n(V,G);G=G.sibling}W.type===A?(oe=Mi(W.props.children,V.mode,oe,W.key),oe.return=V,V=oe):(oe=Kc(W.type,W.key,W.props,null,V.mode,oe),Qo(oe,W),oe.return=V,V=oe)}return w(V);case E:e:{for(qe=W.key;G!==null;){if(G.key===qe)if(G.tag===4&&G.stateNode.containerInfo===W.containerInfo&&G.stateNode.implementation===W.implementation){s(V,G.sibling),oe=h(G,W.children||[]),oe.return=V,V=oe;break e}else{s(V,G);break}else n(V,G);G=G.sibling}oe=Jf(W,V.mode,oe),oe.return=V,V=oe}return w(V);case X:return W=zi(W),Rt(V,G,W,oe)}if(ht(W))return De(V,G,W,oe);if($e(W)){if(qe=$e(W),typeof qe!="function")throw Error(r(150));return W=qe.call(W),Ge(V,G,W,oe)}if(typeof W.then=="function")return Rt(V,G,eu(W),oe);if(W.$$typeof===R)return Rt(V,G,Xc(V,W),oe);tu(V,W)}return typeof W=="string"&&W!==""||typeof W=="number"||typeof W=="bigint"?(W=""+W,G!==null&&G.tag===6?(s(V,G.sibling),oe=h(G,W),oe.return=V,V=oe):(s(V,G),oe=Xf(W,V.mode,oe),oe.return=V,V=oe),w(V)):s(V,G)}return function(V,G,W,oe){try{Jo=0;var qe=Rt(V,G,W,oe);return Rs=null,qe}catch(Ie){if(Ie===Ts||Ie===Qc)throw Ie;var mt=Vn(29,Ie,null,V.mode);return mt.lanes=oe,mt.return=V,mt}}}var Ui=Py(!0),qy=Py(!1),Vr=!1;function ch(t){t.updateQueue={baseState:t.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function uh(t,n){t=t.updateQueue,n.updateQueue===t&&(n.updateQueue={baseState:t.baseState,firstBaseUpdate:t.firstBaseUpdate,lastBaseUpdate:t.lastBaseUpdate,shared:t.shared,callbacks:null})}function Fr(t){return{lane:t,tag:0,payload:null,callback:null,next:null}}function Kr(t,n,s){var c=t.updateQueue;if(c===null)return null;if(c=c.shared,(vt&2)!==0){var h=c.pending;return h===null?n.next=n:(n.next=h.next,h.next=n),c.pending=n,n=Fc(t),xy(t,null,s),n}return Vc(t,c,n,s),Fc(t)}function Zo(t,n,s){if(n=n.updateQueue,n!==null&&(n=n.shared,(s&4194048)!==0)){var c=n.lanes;c&=t.pendingLanes,s|=c,n.lanes=s,Ue(t,s)}}function dh(t,n){var s=t.updateQueue,c=t.alternate;if(c!==null&&(c=c.updateQueue,s===c)){var h=null,p=null;if(s=s.firstBaseUpdate,s!==null){do{var w={lane:s.lane,tag:s.tag,payload:s.payload,callback:null,next:null};p===null?h=p=w:p=p.next=w,s=s.next}while(s!==null);p===null?h=p=n:p=p.next=n}else h=p=n;s={baseState:c.baseState,firstBaseUpdate:h,lastBaseUpdate:p,shared:c.shared,callbacks:c.callbacks},t.updateQueue=s;return}t=s.lastBaseUpdate,t===null?s.firstBaseUpdate=n:t.next=n,s.lastBaseUpdate=n}var fh=!1;function el(){if(fh){var t=xs;if(t!==null)throw t}}function tl(t,n,s,c){fh=!1;var h=t.updateQueue;Vr=!1;var p=h.firstBaseUpdate,w=h.lastBaseUpdate,k=h.shared.pending;if(k!==null){h.shared.pending=null;var z=k,Y=z.next;z.next=null,w===null?p=Y:w.next=Y,w=z;var ae=t.alternate;ae!==null&&(ae=ae.updateQueue,k=ae.lastBaseUpdate,k!==w&&(k===null?ae.firstBaseUpdate=Y:k.next=Y,ae.lastBaseUpdate=z))}if(p!==null){var ue=h.baseState;w=0,ae=Y=z=null,k=p;do{var J=k.lane&-536870913,ee=J!==k.lane;if(ee?(at&J)===J:(c&J)===J){J!==0&&J===As&&(fh=!0),ae!==null&&(ae=ae.next={lane:0,tag:k.tag,payload:k.payload,callback:null,next:null});e:{var De=t,Ge=k;J=n;var Rt=s;switch(Ge.tag){case 1:if(De=Ge.payload,typeof De=="function"){ue=De.call(Rt,ue,J);break e}ue=De;break e;case 3:De.flags=De.flags&-65537|128;case 0:if(De=Ge.payload,J=typeof De=="function"?De.call(Rt,ue,J):De,J==null)break e;ue=b({},ue,J);break e;case 2:Vr=!0}}J=k.callback,J!==null&&(t.flags|=64,ee&&(t.flags|=8192),ee=h.callbacks,ee===null?h.callbacks=[J]:ee.push(J))}else ee={lane:J,tag:k.tag,payload:k.payload,callback:k.callback,next:null},ae===null?(Y=ae=ee,z=ue):ae=ae.next=ee,w|=J;if(k=k.next,k===null){if(k=h.shared.pending,k===null)break;ee=k,k=ee.next,ee.next=null,h.lastBaseUpdate=ee,h.shared.pending=null}}while(!0);ae===null&&(z=ue),h.baseState=z,h.firstBaseUpdate=Y,h.lastBaseUpdate=ae,p===null&&(h.shared.lanes=0),Qr|=w,t.lanes=w,t.memoizedState=ue}}function Gy(t,n){if(typeof t!="function")throw Error(r(191,t));t.call(n)}function Vy(t,n){var s=t.callbacks;if(s!==null)for(t.callbacks=null,t=0;tp?p:8;var w=Q.T,k={};Q.T=k,Oh(t,!1,n,s);try{var z=h(),Y=Q.S;if(Y!==null&&Y(k,z),z!==null&&typeof z=="object"&&typeof z.then=="function"){var ae=UA(z,c);rl(t,n,ae,Xn(t))}else rl(t,n,c,Xn(t))}catch(ue){rl(t,n,{then:function(){},status:"rejected",reason:ue},Xn())}finally{fe.p=p,w!==null&&k.types!==null&&(w.types=k.types),Q.T=w}}function FA(){}function kh(t,n,s,c){if(t.tag!==5)throw Error(r(476));var h=Eb(t).queue;Cb(t,h,n,ye,s===null?FA:function(){return _b(t),s(c)})}function Eb(t){var n=t.memoizedState;if(n!==null)return n;n={memoizedState:ye,baseState:ye,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:dr,lastRenderedState:ye},next:null};var s={};return n.next={memoizedState:s,baseState:s,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:dr,lastRenderedState:s},next:null},t.memoizedState=n,t=t.alternate,t!==null&&(t.memoizedState=n),n}function _b(t){var n=Eb(t);n.next===null&&(n=t.alternate.memoizedState),rl(t,n.next.queue,{},Xn())}function Dh(){return hn(wl)}function Ab(){return Vt().memoizedState}function xb(){return Vt().memoizedState}function KA(t){for(var n=t.return;n!==null;){switch(n.tag){case 24:case 3:var s=Xn();t=Fr(s);var c=Kr(n,t,s);c!==null&&(jn(c,n,s),Zo(c,n,s)),n={cache:ih()},t.payload=n;return}n=n.return}}function WA(t,n,s){var c=Xn();s={lane:c,revertLane:0,gesture:null,action:s,hasEagerState:!1,eagerState:null,next:null},du(t)?Rb(n,s):(s=Wf(t,n,s,c),s!==null&&(jn(s,t,c),kb(s,n,c)))}function Tb(t,n,s){var c=Xn();rl(t,n,s,c)}function rl(t,n,s,c){var h={lane:c,revertLane:0,gesture:null,action:s,hasEagerState:!1,eagerState:null,next:null};if(du(t))Rb(n,h);else{var p=t.alternate;if(t.lanes===0&&(p===null||p.lanes===0)&&(p=n.lastRenderedReducer,p!==null))try{var w=n.lastRenderedState,k=p(w,s);if(h.hasEagerState=!0,h.eagerState=k,Gn(k,w))return Vc(t,n,h,0),Dt===null&&Gc(),!1}catch{}if(s=Wf(t,n,h,c),s!==null)return jn(s,t,c),kb(s,n,c),!0}return!1}function Oh(t,n,s,c){if(c={lane:2,revertLane:cg(),gesture:null,action:c,hasEagerState:!1,eagerState:null,next:null},du(t)){if(n)throw Error(r(479))}else n=Wf(t,s,c,2),n!==null&&jn(n,t,2)}function du(t){var n=t.alternate;return t===Je||n!==null&&n===Je}function Rb(t,n){Ds=ru=!0;var s=t.pending;s===null?n.next=n:(n.next=s.next,s.next=n),t.pending=n}function kb(t,n,s){if((s&4194048)!==0){var c=n.lanes;c&=t.pendingLanes,s|=c,n.lanes=s,Ue(t,s)}}var il={readContext:hn,use:ou,useCallback:Ut,useContext:Ut,useEffect:Ut,useImperativeHandle:Ut,useLayoutEffect:Ut,useInsertionEffect:Ut,useMemo:Ut,useReducer:Ut,useRef:Ut,useState:Ut,useDebugValue:Ut,useDeferredValue:Ut,useTransition:Ut,useSyncExternalStore:Ut,useId:Ut,useHostTransitionStatus:Ut,useFormState:Ut,useActionState:Ut,useOptimistic:Ut,useMemoCache:Ut,useCacheRefresh:Ut};il.useEffectEvent=Ut;var Db={readContext:hn,use:ou,useCallback:function(t,n){return An().memoizedState=[t,n===void 0?null:n],t},useContext:hn,useEffect:hb,useImperativeHandle:function(t,n,s){s=s!=null?s.concat([t]):null,cu(4194308,4,yb.bind(null,n,t),s)},useLayoutEffect:function(t,n){return cu(4194308,4,t,n)},useInsertionEffect:function(t,n){cu(4,2,t,n)},useMemo:function(t,n){var s=An();n=n===void 0?null:n;var c=t();if(Bi){_n(!0);try{t()}finally{_n(!1)}}return s.memoizedState=[c,n],c},useReducer:function(t,n,s){var c=An();if(s!==void 0){var h=s(n);if(Bi){_n(!0);try{s(n)}finally{_n(!1)}}}else h=n;return c.memoizedState=c.baseState=h,t={pending:null,lanes:0,dispatch:null,lastRenderedReducer:t,lastRenderedState:h},c.queue=t,t=t.dispatch=WA.bind(null,Je,t),[c.memoizedState,t]},useRef:function(t){var n=An();return t={current:t},n.memoizedState=t},useState:function(t){t=_h(t);var n=t.queue,s=Tb.bind(null,Je,n);return n.dispatch=s,[t.memoizedState,s]},useDebugValue:Th,useDeferredValue:function(t,n){var s=An();return Rh(s,t,n)},useTransition:function(){var t=_h(!1);return t=Cb.bind(null,Je,t.queue,!0,!1),An().memoizedState=t,[!1,t]},useSyncExternalStore:function(t,n,s){var c=Je,h=An();if(lt){if(s===void 0)throw Error(r(407));s=s()}else{if(s=n(),Dt===null)throw Error(r(349));(at&127)!==0||Jy(c,n,s)}h.memoizedState=s;var p={value:s,getSnapshot:n};return h.queue=p,hb(Zy.bind(null,c,p,t),[t]),c.flags|=2048,Ls(9,{destroy:void 0},Qy.bind(null,c,p,s,n),null),s},useId:function(){var t=An(),n=Dt.identifierPrefix;if(lt){var s=Va,c=Ga;s=(c&~(1<<32-q(c)-1)).toString(32)+s,n="_"+n+"R_"+s,s=iu++,0<\/script>",p=p.removeChild(p.firstChild);break;case"select":p=typeof c.is=="string"?w.createElement("select",{is:c.is}):w.createElement("select"),c.multiple?p.multiple=!0:c.size&&(p.size=c.size);break;default:p=typeof c.is=="string"?w.createElement(h,{is:c.is}):w.createElement(h)}}p[an]=n,p[vn]=c;e:for(w=n.child;w!==null;){if(w.tag===5||w.tag===6)p.appendChild(w.stateNode);else if(w.tag!==4&&w.tag!==27&&w.child!==null){w.child.return=w,w=w.child;continue}if(w===n)break e;for(;w.sibling===null;){if(w.return===null||w.return===n)break e;w=w.return}w.sibling.return=w.return,w=w.sibling}n.stateNode=p;e:switch(pn(p,h,c),h){case"button":case"input":case"select":case"textarea":c=!!c.autoFocus;break e;case"img":c=!0;break e;default:c=!1}c&&hr(n)}}return Lt(n),Vh(n,n.type,t===null?null:t.memoizedProps,n.pendingProps,s),null;case 6:if(t&&n.stateNode!=null)t.memoizedProps!==c&&hr(n);else{if(typeof c!="string"&&n.stateNode===null)throw Error(r(166));if(t=me.current,Es(n)){if(t=n.stateNode,s=n.memoizedProps,c=null,h=fn,h!==null)switch(h.tag){case 27:case 5:c=h.memoizedProps}t[an]=n,t=!!(t.nodeValue===s||c!==null&&c.suppressHydrationWarning===!0||Yv(t.nodeValue,s)),t||qr(n,!0)}else t=Ou(t).createTextNode(c),t[an]=n,n.stateNode=t}return Lt(n),null;case 31:if(s=n.memoizedState,t===null||t.memoizedState!==null){if(c=Es(n),s!==null){if(t===null){if(!c)throw Error(r(318));if(t=n.memoizedState,t=t!==null?t.dehydrated:null,!t)throw Error(r(557));t[an]=n}else $i(),(n.flags&128)===0&&(n.memoizedState=null),n.flags|=4;Lt(n),t=!1}else s=th(),t!==null&&t.memoizedState!==null&&(t.memoizedState.hydrationErrors=s),t=!0;if(!t)return n.flags&256?(Kn(n),n):(Kn(n),null);if((n.flags&128)!==0)throw Error(r(558))}return Lt(n),null;case 13:if(c=n.memoizedState,t===null||t.memoizedState!==null&&t.memoizedState.dehydrated!==null){if(h=Es(n),c!==null&&c.dehydrated!==null){if(t===null){if(!h)throw Error(r(318));if(h=n.memoizedState,h=h!==null?h.dehydrated:null,!h)throw Error(r(317));h[an]=n}else $i(),(n.flags&128)===0&&(n.memoizedState=null),n.flags|=4;Lt(n),h=!1}else h=th(),t!==null&&t.memoizedState!==null&&(t.memoizedState.hydrationErrors=h),h=!0;if(!h)return n.flags&256?(Kn(n),n):(Kn(n),null)}return Kn(n),(n.flags&128)!==0?(n.lanes=s,n):(s=c!==null,t=t!==null&&t.memoizedState!==null,s&&(c=n.child,h=null,c.alternate!==null&&c.alternate.memoizedState!==null&&c.alternate.memoizedState.cachePool!==null&&(h=c.alternate.memoizedState.cachePool.pool),p=null,c.memoizedState!==null&&c.memoizedState.cachePool!==null&&(p=c.memoizedState.cachePool.pool),p!==h&&(c.flags|=2048)),s!==t&&s&&(n.child.flags|=8192),mu(n,n.updateQueue),Lt(n),null);case 4:return He(),t===null&&hg(n.stateNode.containerInfo),Lt(n),null;case 10:return cr(n.type),Lt(n),null;case 19:if(K(Gt),c=n.memoizedState,c===null)return Lt(n),null;if(h=(n.flags&128)!==0,p=c.rendering,p===null)if(h)ol(c,!1);else{if(Bt!==0||t!==null&&(t.flags&128)!==0)for(t=n.child;t!==null;){if(p=au(t),p!==null){for(n.flags|=128,ol(c,!1),t=p.updateQueue,n.updateQueue=t,mu(n,t),n.subtreeFlags=0,t=s,s=n.child;s!==null;)Ty(s,t),s=s.sibling;return re(Gt,Gt.current&1|2),lt&&or(n,c.treeForkCount),n.child}t=t.sibling}c.tail!==null&&Kt()>wu&&(n.flags|=128,h=!0,ol(c,!1),n.lanes=4194304)}else{if(!h)if(t=au(p),t!==null){if(n.flags|=128,h=!0,t=t.updateQueue,n.updateQueue=t,mu(n,t),ol(c,!0),c.tail===null&&c.tailMode==="hidden"&&!p.alternate&&!lt)return Lt(n),null}else 2*Kt()-c.renderingStartTime>wu&&s!==536870912&&(n.flags|=128,h=!0,ol(c,!1),n.lanes=4194304);c.isBackwards?(p.sibling=n.child,n.child=p):(t=c.last,t!==null?t.sibling=p:n.child=p,c.last=p)}return c.tail!==null?(t=c.tail,c.rendering=t,c.tail=t.sibling,c.renderingStartTime=Kt(),t.sibling=null,s=Gt.current,re(Gt,h?s&1|2:s&1),lt&&or(n,c.treeForkCount),t):(Lt(n),null);case 22:case 23:return Kn(n),gh(),c=n.memoizedState!==null,t!==null?t.memoizedState!==null!==c&&(n.flags|=8192):c&&(n.flags|=8192),c?(s&536870912)!==0&&(n.flags&128)===0&&(Lt(n),n.subtreeFlags&6&&(n.flags|=8192)):Lt(n),s=n.updateQueue,s!==null&&mu(n,s.retryQueue),s=null,t!==null&&t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(s=t.memoizedState.cachePool.pool),c=null,n.memoizedState!==null&&n.memoizedState.cachePool!==null&&(c=n.memoizedState.cachePool.pool),c!==s&&(n.flags|=2048),t!==null&&K(Hi),null;case 24:return s=null,t!==null&&(s=t.memoizedState.cache),n.memoizedState.cache!==s&&(n.flags|=2048),cr(Xt),Lt(n),null;case 25:return null;case 30:return null}throw Error(r(156,n.tag))}function ZA(t,n){switch(Zf(n),n.tag){case 1:return t=n.flags,t&65536?(n.flags=t&-65537|128,n):null;case 3:return cr(Xt),He(),t=n.flags,(t&65536)!==0&&(t&128)===0?(n.flags=t&-65537|128,n):null;case 26:case 27:case 5:return Et(n),null;case 31:if(n.memoizedState!==null){if(Kn(n),n.alternate===null)throw Error(r(340));$i()}return t=n.flags,t&65536?(n.flags=t&-65537|128,n):null;case 13:if(Kn(n),t=n.memoizedState,t!==null&&t.dehydrated!==null){if(n.alternate===null)throw Error(r(340));$i()}return t=n.flags,t&65536?(n.flags=t&-65537|128,n):null;case 19:return K(Gt),null;case 4:return He(),null;case 10:return cr(n.type),null;case 22:case 23:return Kn(n),gh(),t!==null&&K(Hi),t=n.flags,t&65536?(n.flags=t&-65537|128,n):null;case 24:return cr(Xt),null;case 25:return null;default:return null}}function ev(t,n){switch(Zf(n),n.tag){case 3:cr(Xt),He();break;case 26:case 27:case 5:Et(n);break;case 4:He();break;case 31:n.memoizedState!==null&&Kn(n);break;case 13:Kn(n);break;case 19:K(Gt);break;case 10:cr(n.type);break;case 22:case 23:Kn(n),gh(),t!==null&&K(Hi);break;case 24:cr(Xt)}}function ll(t,n){try{var s=n.updateQueue,c=s!==null?s.lastEffect:null;if(c!==null){var h=c.next;s=h;do{if((s.tag&t)===t){c=void 0;var p=s.create,w=s.inst;c=p(),w.destroy=c}s=s.next}while(s!==h)}}catch(k){Ct(n,n.return,k)}}function Xr(t,n,s){try{var c=n.updateQueue,h=c!==null?c.lastEffect:null;if(h!==null){var p=h.next;c=p;do{if((c.tag&t)===t){var w=c.inst,k=w.destroy;if(k!==void 0){w.destroy=void 0,h=n;var z=s,Y=k;try{Y()}catch(ae){Ct(h,z,ae)}}}c=c.next}while(c!==p)}}catch(ae){Ct(n,n.return,ae)}}function tv(t){var n=t.updateQueue;if(n!==null){var s=t.stateNode;try{Vy(n,s)}catch(c){Ct(t,t.return,c)}}}function nv(t,n,s){s.props=Pi(t.type,t.memoizedProps),s.state=t.memoizedState;try{s.componentWillUnmount()}catch(c){Ct(t,n,c)}}function cl(t,n){try{var s=t.ref;if(s!==null){switch(t.tag){case 26:case 27:case 5:var c=t.stateNode;break;case 30:c=t.stateNode;break;default:c=t.stateNode}typeof s=="function"?t.refCleanup=s(c):s.current=c}}catch(h){Ct(t,n,h)}}function Fa(t,n){var s=t.ref,c=t.refCleanup;if(s!==null)if(typeof c=="function")try{c()}catch(h){Ct(t,n,h)}finally{t.refCleanup=null,t=t.alternate,t!=null&&(t.refCleanup=null)}else if(typeof s=="function")try{s(null)}catch(h){Ct(t,n,h)}else s.current=null}function av(t){var n=t.type,s=t.memoizedProps,c=t.stateNode;try{e:switch(n){case"button":case"input":case"select":case"textarea":s.autoFocus&&c.focus();break e;case"img":s.src?c.src=s.src:s.srcSet&&(c.srcset=s.srcSet)}}catch(h){Ct(t,t.return,h)}}function Fh(t,n,s){try{var c=t.stateNode;wx(c,t.type,s,n),c[vn]=n}catch(h){Ct(t,t.return,h)}}function rv(t){return t.tag===5||t.tag===3||t.tag===26||t.tag===27&&ai(t.type)||t.tag===4}function Kh(t){e:for(;;){for(;t.sibling===null;){if(t.return===null||rv(t.return))return null;t=t.return}for(t.sibling.return=t.return,t=t.sibling;t.tag!==5&&t.tag!==6&&t.tag!==18;){if(t.tag===27&&ai(t.type)||t.flags&2||t.child===null||t.tag===4)continue e;t.child.return=t,t=t.child}if(!(t.flags&2))return t.stateNode}}function Wh(t,n,s){var c=t.tag;if(c===5||c===6)t=t.stateNode,n?(s.nodeType===9?s.body:s.nodeName==="HTML"?s.ownerDocument.body:s).insertBefore(t,n):(n=s.nodeType===9?s.body:s.nodeName==="HTML"?s.ownerDocument.body:s,n.appendChild(t),s=s._reactRootContainer,s!=null||n.onclick!==null||(n.onclick=Aa));else if(c!==4&&(c===27&&ai(t.type)&&(s=t.stateNode,n=null),t=t.child,t!==null))for(Wh(t,n,s),t=t.sibling;t!==null;)Wh(t,n,s),t=t.sibling}function yu(t,n,s){var c=t.tag;if(c===5||c===6)t=t.stateNode,n?s.insertBefore(t,n):s.appendChild(t);else if(c!==4&&(c===27&&ai(t.type)&&(s=t.stateNode),t=t.child,t!==null))for(yu(t,n,s),t=t.sibling;t!==null;)yu(t,n,s),t=t.sibling}function iv(t){var n=t.stateNode,s=t.memoizedProps;try{for(var c=t.type,h=n.attributes;h.length;)n.removeAttributeNode(h[0]);pn(n,c,s),n[an]=t,n[vn]=s}catch(p){Ct(t,t.return,p)}}var gr=!1,Zt=!1,Yh=!1,sv=typeof WeakSet=="function"?WeakSet:Set,cn=null;function ex(t,n){if(t=t.containerInfo,mg=zu,t=by(t),Pf(t)){if("selectionStart"in t)var s={start:t.selectionStart,end:t.selectionEnd};else e:{s=(s=t.ownerDocument)&&s.defaultView||window;var c=s.getSelection&&s.getSelection();if(c&&c.rangeCount!==0){s=c.anchorNode;var h=c.anchorOffset,p=c.focusNode;c=c.focusOffset;try{s.nodeType,p.nodeType}catch{s=null;break e}var w=0,k=-1,z=-1,Y=0,ae=0,ue=t,J=null;t:for(;;){for(var ee;ue!==s||h!==0&&ue.nodeType!==3||(k=w+h),ue!==p||c!==0&&ue.nodeType!==3||(z=w+c),ue.nodeType===3&&(w+=ue.nodeValue.length),(ee=ue.firstChild)!==null;)J=ue,ue=ee;for(;;){if(ue===t)break t;if(J===s&&++Y===h&&(k=w),J===p&&++ae===c&&(z=w),(ee=ue.nextSibling)!==null)break;ue=J,J=ue.parentNode}ue=ee}s=k===-1||z===-1?null:{start:k,end:z}}else s=null}s=s||{start:0,end:0}}else s=null;for(yg={focusedElem:t,selectionRange:s},zu=!1,cn=n;cn!==null;)if(n=cn,t=n.child,(n.subtreeFlags&1028)!==0&&t!==null)t.return=n,cn=t;else for(;cn!==null;){switch(n=cn,p=n.alternate,t=n.flags,n.tag){case 0:if((t&4)!==0&&(t=n.updateQueue,t=t!==null?t.events:null,t!==null))for(s=0;s title"))),pn(p,c,s),p[an]=t,Yt(p),c=p;break e;case"link":var w=fS("link","href",h).get(c+(s.href||""));if(w){for(var k=0;kRt&&(w=Rt,Rt=Ge,Ge=w);var V=my(k,Ge),G=my(k,Rt);if(V&&G&&(ee.rangeCount!==1||ee.anchorNode!==V.node||ee.anchorOffset!==V.offset||ee.focusNode!==G.node||ee.focusOffset!==G.offset)){var W=ue.createRange();W.setStart(V.node,V.offset),ee.removeAllRanges(),Ge>Rt?(ee.addRange(W),ee.extend(G.node,G.offset)):(W.setEnd(G.node,G.offset),ee.addRange(W))}}}}for(ue=[],ee=k;ee=ee.parentNode;)ee.nodeType===1&&ue.push({element:ee,left:ee.scrollLeft,top:ee.scrollTop});for(typeof k.focus=="function"&&k.focus(),k=0;ks?32:s,Q.T=null,s=ng,ng=null;var p=ei,w=vr;if(sn=0,Hs=ei=null,vr=0,(vt&6)!==0)throw Error(r(331));var k=vt;if(vt|=4,yv(p.current),gv(p,p.current,w,s),vt=k,pl(0,!1),nn&&typeof nn.onPostCommitFiberRoot=="function")try{nn.onPostCommitFiberRoot(Ea,p)}catch{}return!0}finally{fe.p=h,Q.T=c,Nv(t,n)}}function Hv(t,n,s){n=ra(s,n),n=Nh(t.stateNode,n,2),t=Kr(t,n,2),t!==null&&(Fe(t,2),Ka(t))}function Ct(t,n,s){if(t.tag===3)Hv(t,t,s);else for(;n!==null;){if(n.tag===3){Hv(n,t,s);break}else if(n.tag===1){var c=n.stateNode;if(typeof n.type.getDerivedStateFromError=="function"||typeof c.componentDidCatch=="function"&&(Zr===null||!Zr.has(c))){t=ra(s,t),s=zb(2),c=Kr(n,s,2),c!==null&&(jb(s,c,n,t),Fe(c,2),Ka(c));break}}n=n.return}}function sg(t,n,s){var c=t.pingCache;if(c===null){c=t.pingCache=new ax;var h=new Set;c.set(n,h)}else h=c.get(n),h===void 0&&(h=new Set,c.set(n,h));h.has(s)||(Qh=!0,h.add(s),t=lx.bind(null,t,n,s),n.then(t,t))}function lx(t,n,s){var c=t.pingCache;c!==null&&c.delete(n),t.pingedLanes|=t.suspendedLanes&s,t.warmLanes&=~s,Dt===t&&(at&s)===s&&(Bt===4||Bt===3&&(at&62914560)===at&&300>Kt()-Su?(vt&2)===0&&zs(t,0):Zh|=s,Is===at&&(Is=0)),Ka(t)}function zv(t,n){n===0&&(n=ke()),t=Li(t,n),t!==null&&(Fe(t,n),Ka(t))}function cx(t){var n=t.memoizedState,s=0;n!==null&&(s=n.retryLane),zv(t,s)}function ux(t,n){var s=0;switch(t.tag){case 31:case 13:var c=t.stateNode,h=t.memoizedState;h!==null&&(s=h.retryLane);break;case 19:c=t.stateNode;break;case 22:c=t.stateNode._retryCache;break;default:throw Error(r(314))}c!==null&&c.delete(n),zv(t,s)}function dx(t,n){return jt(t,n)}var Tu=null,Us=null,og=!1,Ru=!1,lg=!1,ni=0;function Ka(t){t!==Us&&t.next===null&&(Us===null?Tu=Us=t:Us=Us.next=t),Ru=!0,og||(og=!0,hx())}function pl(t,n){if(!lg&&Ru){lg=!0;do for(var s=!1,c=Tu;c!==null;){if(t!==0){var h=c.pendingLanes;if(h===0)var p=0;else{var w=c.suspendedLanes,k=c.pingedLanes;p=(1<<31-q(42|t)+1)-1,p&=h&~(w&~k),p=p&201326741?p&201326741|1:p?p|2:0}p!==0&&(s=!0,Pv(c,p))}else p=at,p=je(c,c===Dt?p:0,c.cancelPendingCommit!==null||c.timeoutHandle!==-1),(p&3)===0||ze(c,p)||(s=!0,Pv(c,p));c=c.next}while(s);lg=!1}}function fx(){jv()}function jv(){Ru=og=!1;var t=0;ni!==0&&Ex()&&(t=ni);for(var n=Kt(),s=null,c=Tu;c!==null;){var h=c.next,p=Uv(c,n);p===0?(c.next=null,s===null?Tu=h:s.next=h,h===null&&(Us=s)):(s=c,(t!==0||(p&3)!==0)&&(Ru=!0)),c=h}sn!==0&&sn!==5||pl(t),ni!==0&&(ni=0)}function Uv(t,n){for(var s=t.suspendedLanes,c=t.pingedLanes,h=t.expirationTimes,p=t.pendingLanes&-62914561;0k)break;var ae=z.transferSize,ue=z.initiatorType;ae&&Xv(ue)&&(z=z.responseEnd,w+=ae*(z"u"?null:document;function lS(t,n,s){var c=Bs;if(c&&typeof n=="string"&&n){var h=$n(n);h='link[rel="'+t+'"][href="'+h+'"]',typeof s=="string"&&(h+='[crossorigin="'+s+'"]'),oS.has(h)||(oS.add(h),t={rel:t,crossOrigin:s,href:n},c.querySelector(h)===null&&(n=c.createElement("link"),pn(n,"link",t),Yt(n),c.head.appendChild(n)))}}function Lx(t){Sr.D(t),lS("dns-prefetch",t,null)}function Mx(t,n){Sr.C(t,n),lS("preconnect",t,n)}function $x(t,n,s){Sr.L(t,n,s);var c=Bs;if(c&&t&&n){var h='link[rel="preload"][as="'+$n(n)+'"]';n==="image"&&s&&s.imageSrcSet?(h+='[imagesrcset="'+$n(s.imageSrcSet)+'"]',typeof s.imageSizes=="string"&&(h+='[imagesizes="'+$n(s.imageSizes)+'"]')):h+='[href="'+$n(t)+'"]';var p=h;switch(n){case"style":p=Ps(t);break;case"script":p=qs(t)}ua.has(p)||(t=b({rel:"preload",href:n==="image"&&s&&s.imageSrcSet?void 0:t,as:n},s),ua.set(p,t),c.querySelector(h)!==null||n==="style"&&c.querySelector(vl(p))||n==="script"&&c.querySelector(Sl(p))||(n=c.createElement("link"),pn(n,"link",t),Yt(n),c.head.appendChild(n)))}}function Nx(t,n){Sr.m(t,n);var s=Bs;if(s&&t){var c=n&&typeof n.as=="string"?n.as:"script",h='link[rel="modulepreload"][as="'+$n(c)+'"][href="'+$n(t)+'"]',p=h;switch(c){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":p=qs(t)}if(!ua.has(p)&&(t=b({rel:"modulepreload",href:t},n),ua.set(p,t),s.querySelector(h)===null)){switch(c){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(s.querySelector(Sl(p)))return}c=s.createElement("link"),pn(c,"link",t),Yt(c),s.head.appendChild(c)}}}function Ix(t,n,s){Sr.S(t,n,s);var c=Bs;if(c&&t){var h=Mr(c).hoistableStyles,p=Ps(t);n=n||"default";var w=h.get(p);if(!w){var k={loading:0,preload:null};if(w=c.querySelector(vl(p)))k.loading=5;else{t=b({rel:"stylesheet",href:t,"data-precedence":n},s),(s=ua.get(p))&&_g(t,s);var z=w=c.createElement("link");Yt(z),pn(z,"link",t),z._p=new Promise(function(Y,ae){z.onload=Y,z.onerror=ae}),z.addEventListener("load",function(){k.loading|=1}),z.addEventListener("error",function(){k.loading|=2}),k.loading|=4,Mu(w,n,c)}w={type:"stylesheet",instance:w,count:1,state:k},h.set(p,w)}}}function Hx(t,n){Sr.X(t,n);var s=Bs;if(s&&t){var c=Mr(s).hoistableScripts,h=qs(t),p=c.get(h);p||(p=s.querySelector(Sl(h)),p||(t=b({src:t,async:!0},n),(n=ua.get(h))&&Ag(t,n),p=s.createElement("script"),Yt(p),pn(p,"link",t),s.head.appendChild(p)),p={type:"script",instance:p,count:1,state:null},c.set(h,p))}}function zx(t,n){Sr.M(t,n);var s=Bs;if(s&&t){var c=Mr(s).hoistableScripts,h=qs(t),p=c.get(h);p||(p=s.querySelector(Sl(h)),p||(t=b({src:t,async:!0,type:"module"},n),(n=ua.get(h))&&Ag(t,n),p=s.createElement("script"),Yt(p),pn(p,"link",t),s.head.appendChild(p)),p={type:"script",instance:p,count:1,state:null},c.set(h,p))}}function cS(t,n,s,c){var h=(h=me.current)?Lu(h):null;if(!h)throw Error(r(446));switch(t){case"meta":case"title":return null;case"style":return typeof s.precedence=="string"&&typeof s.href=="string"?(n=Ps(s.href),s=Mr(h).hoistableStyles,c=s.get(n),c||(c={type:"style",instance:null,count:0,state:null},s.set(n,c)),c):{type:"void",instance:null,count:0,state:null};case"link":if(s.rel==="stylesheet"&&typeof s.href=="string"&&typeof s.precedence=="string"){t=Ps(s.href);var p=Mr(h).hoistableStyles,w=p.get(t);if(w||(h=h.ownerDocument||h,w={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},p.set(t,w),(p=h.querySelector(vl(t)))&&!p._p&&(w.instance=p,w.state.loading=5),ua.has(t)||(s={rel:"preload",as:"style",href:s.href,crossOrigin:s.crossOrigin,integrity:s.integrity,media:s.media,hrefLang:s.hrefLang,referrerPolicy:s.referrerPolicy},ua.set(t,s),p||jx(h,t,s,w.state))),n&&c===null)throw Error(r(528,""));return w}if(n&&c!==null)throw Error(r(529,""));return null;case"script":return n=s.async,s=s.src,typeof s=="string"&&n&&typeof n!="function"&&typeof n!="symbol"?(n=qs(s),s=Mr(h).hoistableScripts,c=s.get(n),c||(c={type:"script",instance:null,count:0,state:null},s.set(n,c)),c):{type:"void",instance:null,count:0,state:null};default:throw Error(r(444,t))}}function Ps(t){return'href="'+$n(t)+'"'}function vl(t){return'link[rel="stylesheet"]['+t+"]"}function uS(t){return b({},t,{"data-precedence":t.precedence,precedence:null})}function jx(t,n,s,c){t.querySelector('link[rel="preload"][as="style"]['+n+"]")?c.loading=1:(n=t.createElement("link"),c.preload=n,n.addEventListener("load",function(){return c.loading|=1}),n.addEventListener("error",function(){return c.loading|=2}),pn(n,"link",s),Yt(n),t.head.appendChild(n))}function qs(t){return'[src="'+$n(t)+'"]'}function Sl(t){return"script[async]"+t}function dS(t,n,s){if(n.count++,n.instance===null)switch(n.type){case"style":var c=t.querySelector('style[data-href~="'+$n(s.href)+'"]');if(c)return n.instance=c,Yt(c),c;var h=b({},s,{"data-href":s.href,"data-precedence":s.precedence,href:null,precedence:null});return c=(t.ownerDocument||t).createElement("style"),Yt(c),pn(c,"style",h),Mu(c,s.precedence,t),n.instance=c;case"stylesheet":h=Ps(s.href);var p=t.querySelector(vl(h));if(p)return n.state.loading|=4,n.instance=p,Yt(p),p;c=uS(s),(h=ua.get(h))&&_g(c,h),p=(t.ownerDocument||t).createElement("link"),Yt(p);var w=p;return w._p=new Promise(function(k,z){w.onload=k,w.onerror=z}),pn(p,"link",c),n.state.loading|=4,Mu(p,s.precedence,t),n.instance=p;case"script":return p=qs(s.src),(h=t.querySelector(Sl(p)))?(n.instance=h,Yt(h),h):(c=s,(h=ua.get(p))&&(c=b({},s),Ag(c,h)),t=t.ownerDocument||t,h=t.createElement("script"),Yt(h),pn(h,"link",c),t.head.appendChild(h),n.instance=h);case"void":return null;default:throw Error(r(443,n.type))}else n.type==="stylesheet"&&(n.state.loading&4)===0&&(c=n.instance,n.state.loading|=4,Mu(c,s.precedence,t));return n.instance}function Mu(t,n,s){for(var c=s.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),h=c.length?c[c.length-1]:null,p=h,w=0;w title"):null)}function Ux(t,n,s){if(s===1||n.itemProp!=null)return!1;switch(t){case"meta":case"title":return!0;case"style":if(typeof n.precedence!="string"||typeof n.href!="string"||n.href==="")break;return!0;case"link":if(typeof n.rel!="string"||typeof n.href!="string"||n.href===""||n.onLoad||n.onError)break;return n.rel==="stylesheet"?(t=n.disabled,typeof n.precedence=="string"&&t==null):!0;case"script":if(n.async&&typeof n.async!="function"&&typeof n.async!="symbol"&&!n.onLoad&&!n.onError&&n.src&&typeof n.src=="string")return!0}return!1}function gS(t){return!(t.type==="stylesheet"&&(t.state.loading&3)===0)}function Bx(t,n,s,c){if(s.type==="stylesheet"&&(typeof c.media!="string"||matchMedia(c.media).matches!==!1)&&(s.state.loading&4)===0){if(s.instance===null){var h=Ps(c.href),p=n.querySelector(vl(h));if(p){n=p._p,n!==null&&typeof n=="object"&&typeof n.then=="function"&&(t.count++,t=Nu.bind(t),n.then(t,t)),s.state.loading|=4,s.instance=p,Yt(p);return}p=n.ownerDocument||n,c=uS(c),(h=ua.get(h))&&_g(c,h),p=p.createElement("link"),Yt(p);var w=p;w._p=new Promise(function(k,z){w.onload=k,w.onerror=z}),pn(p,"link",c),s.instance=p}t.stylesheets===null&&(t.stylesheets=new Map),t.stylesheets.set(s,n),(n=s.state.preload)&&(s.state.loading&3)===0&&(t.count++,s=Nu.bind(t),n.addEventListener("load",s),n.addEventListener("error",s))}}var xg=0;function Px(t,n){return t.stylesheets&&t.count===0&&Hu(t,t.stylesheets),0xg?50:800)+n);return t.unsuspend=s,function(){t.unsuspend=null,clearTimeout(c),clearTimeout(h)}}:null}function Nu(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Hu(this,this.stylesheets);else if(this.unsuspend){var t=this.unsuspend;this.unsuspend=null,t()}}}var Iu=null;function Hu(t,n){t.stylesheets=null,t.unsuspend!==null&&(t.count++,Iu=new Map,n.forEach(qx,t),Iu=null,Nu.call(t))}function qx(t,n){if(!(n.state.loading&4)){var s=Iu.get(t);if(s)var c=s.get(null);else{s=new Map,Iu.set(t,s);for(var h=t.querySelectorAll("link[data-precedence],style[data-precedence]"),p=0;p"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(o)}catch(e){console.error(e)}}return o(),Ku.exports=NS(),Ku.exports}var Ju=IS();const Qu=Ya(Ju),Fs=[],HS=50;let Zu=!1;function Pg(){try{return window.G7Core?.devTools}catch{return}}function Vi(o,e,a){const r=Pg();if(Zu&&r?.isEnabled?.()){r.trackLog?.(o,e,a);return}Zu||(o==="error"||o==="warn")&&Fs.length{a.isDebugEnabled()&&console.log(e,...r),Vi("log",o,r)},warn:(...r)=>{a.isDebugEnabled()&&console.warn(e,...r),Vi("warn",o,r)},error:(...r)=>{a.isDebugEnabled()&&console.error(e,...r),Vi("error",o,r)}}}Ks.getInstance();const Fi=ct("networkResilience"),qg=2,Gg=300,Vg=2e3,zS=15e3;function Fg(o){return o?.name==="AbortError"}function jS(o){return Fg(o)?!1:o instanceof TypeError}let Al=!1,Kg=!1;function td(){return Al}function US(){typeof window>"u"||Kg||(Kg=!0,window.addEventListener("pagehide",()=>{Al=!0}),window.addEventListener("pageshow",o=>{o.persisted&&(Al=!1)}),window.addEventListener("beforeunload",()=>{Al=!0}))}function Wg(o,e,a){const r=Math.min(e*Math.pow(2,o),a),i=r*.25*(Math.random()*2-1);return Math.max(0,Math.round(r+i))}function Yg(o){return new Promise(e=>setTimeout(e,o))}async function xl(o,e={}){const{retries:a=qg,baseDelayMs:r=Gg,maxDelayMs:i=Vg,timeoutMs:l=zS,label:u=o,init:d}=e,f=a+1;let g;for(let m=0;m0?new AbortController:null;try{const E={...d};if(S){const T=d?.signal;T&&(T.aborted?S.abort():T.addEventListener("abort",()=>S.abort(),{once:!0})),E.signal=S.signal,v=setTimeout(()=>{b=!0,S.abort()},l)}return await fetch(o,E)}catch(E){if(g=E,Fg(E)&&!b||!(b||jS(E)))throw E;if(td())throw Fi.warn(`Document unloading, aborting retries: ${u}`),E;if(m===f-1)throw Fi.warn(`All ${f} attempts failed: ${u}`,E),E;const L=Wg(m,r,i);Fi.warn(`Network failure (attempt ${m+1}/${f}), retrying in ${L}ms: ${u}`),await Yg(L)}finally{v!==void 0&&clearTimeout(v)}}throw g}async function Xg(o,e={},a={}){const{retries:r=qg,baseDelayMs:i=Gg,maxDelayMs:l=Vg,label:u=o}=a,d=r+1;for(let f=0;f{const i=document.createElement("script");i.src=o,i.async=!1;for(const[l,u]of Object.entries(e))l==="id"?i.id=u:i.setAttribute(l,u);i.onload=()=>a(),i.onerror=()=>r(new Error(`Failed to load script: ${o}`)),document.head.appendChild(i)})}const Jg="extension",Ki="extensionless",PS="file";function qS(){const o=globalThis?.G7Config;if(globalThis?.__g7AssetUrlMode===Ki)return Ki;const a=o?.assetUrlMode;return a===Ki||a===Jg?a:o?.settings?.general?.asset_url_mode===Ki?Ki:Jg}function Qg(){return qS()===Ki}function La(o,e,a,r){const i=o.replace(/\/+$/,""),l=e.replace(/^\.+/,""),u=Qg()?i:`${i}.${l}`,d=[];return r&&d.push(r.replace(/^[?&]+/,"")),a!=null&&a!==""&&d.push(`v=${a}`),d.length>0?`${u}?${d.join("&")}`:u}function wr(o){if(!o||!Qg())return o;const e=globalThis?.location?.origin,a=e&&o.startsWith(e)?o.slice(e.length):o;if(!a.startsWith("/api/"))return o;const[r,i]=GS(a),l=r.match(/^\/api\/(modules|plugins)\/bundle\.(js|css)$/);if(l)return Zg(`/api/${l[1]}/bundle/${l[2]}`,i);const u=r.match(/^\/api\/(templates|modules|plugins)\/assets\/([^/]+)\/(.+)$/);if(u){const[,f,g,m]=u,b=`${PS}=${encodeURIComponent(decodeURIComponent(m))}`;return`/api/${f}/assets/${g}?${b}${i?`&${i}`:""}`}const d=r.match(/^(\/api\/.+)\.(json|js|css)$/);return d?Zg(d[1],i):o}function GS(o){const e=o.indexOf("?");return e===-1?[o,""]:[o.slice(0,e),o.slice(e+1)]}function Zg(o,e){return e?`${o}?${e}`:o}const Ma=ct("ComponentRegistry");class on extends Error{constructor(a,r,i){super(a);$(this,"code");$(this,"details");this.code=r,this.details=i,this.name="ComponentRegistryError"}}const Pn=class Pn{constructor(){$(this,"registry",{});$(this,"manifest",null);$(this,"loadingState","idle");$(this,"error",null);$(this,"templateId",null);$(this,"templateType",null)}static getInstance(){return Pn.instance||(Pn.instance=new Pn),Pn.instance}static createIsolatedInstance(){return new Pn}static resetInstance(){Pn.instance=null}async loadComponents(e,a){if(this.loadingState==="loading")throw new on("Components are already being loaded","LOADING_IN_PROGRESS");if(this.loadingState==="loaded"&&this.templateId===e&&this.templateType===a){Ma.log("Components already loaded for template:",e,a);return}this.loadingState="loading",this.templateId=e,this.templateType=a,this.error=null;try{await this.loadManifest(),await this.loadComponentBundle(),this.loadingState="loaded",Ma.log("Successfully loaded components:",Object.keys(this.registry).length)}catch(r){throw this.loadingState="error",this.error=r instanceof Error?r:new Error(String(r)),new on(`Failed to load components: ${this.error.message}`,"LOAD_FAILED",{originalError:this.error})}}async loadManifest(){try{if(!this.templateId)throw new on("Template ID not set","TEMPLATE_ID_NOT_SET");const e=`${this.templateId}:${this.templateType}`;if(Pn.manifestCache.has(e)){this.manifest=Pn.manifestCache.get(e),Ma.log("Manifest loaded from cache:",this.manifest.templateId);return}const a=La(`/api/templates/${this.templateId}/components`,"json"),r=await xl(a,{label:"components.json"});if(!r.ok)throw new on(`Failed to fetch manifest: ${r.status} ${r.statusText}`,"MANIFEST_FETCH_FAILED",{status:r.status,statusText:r.statusText});const i=await r.json();this.validateManifest(i),this.manifest=i,Pn.manifestCache.set(e,i),Ma.log("Manifest loaded and cached:",i.templateId)}catch(e){throw e instanceof on?e:new on("Failed to load component manifest","MANIFEST_LOAD_FAILED",{originalError:e})}}validateManifest(e){if(!e.version)throw new on("Manifest missing required field: version","MANIFEST_INVALID",{field:"version"});if(!e.templateId)throw new on("Manifest missing required field: templateId","MANIFEST_INVALID",{field:"templateId"});if(!e.components||typeof e.components!="object")throw new on("Manifest missing required field: components","MANIFEST_INVALID",{field:"components"});const a=["basic","composite","layout"];for(const r of a){if(!Array.isArray(e.components[r]))throw new on(`Manifest field 'components.${r}' must be an array`,"MANIFEST_INVALID",{field:`components.${r}`,value:e.components[r]});e.components[r].forEach((i,l)=>{if(!i.name||typeof i.name!="string")throw new on(`Invalid component metadata at ${r}[${l}]: missing or invalid 'name'`,"MANIFEST_INVALID",{type:r,index:l,metadata:i});if(!i.type||typeof i.type!="string")throw new on(`Invalid component metadata at ${r}[${l}]: missing or invalid 'type'`,"MANIFEST_INVALID",{type:r,index:l,metadata:i})})}Ma.log("Manifest validation passed")}async loadComponentBundle(){try{if(!this.templateId)throw new on("Template ID not set","TEMPLATE_ID_NOT_SET");const e=this.getGlobalVariableName(),a=window[e];if(!a||typeof a!="object")throw new on(`Component bundle not loaded. Expected global variable: ${e}. Ensure admin.blade.php includes the IIFE bundle script.`,"BUNDLE_NOT_LOADED",{expectedVariable:e});await this.registerComponentsFromManifest(a),Ma.log("Component bundle loaded from global variable:",e)}catch(e){throw e instanceof on?e:new on("Failed to load component bundle","BUNDLE_LOAD_FAILED",{originalError:e})}}getGlobalVariableName(){if(!this.templateId)throw new on("Template ID not set","TEMPLATE_ID_NOT_SET");return this.templateId.split(/[-_]/).map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}async registerComponentsFromManifest(e){if(!this.manifest)throw new on("Manifest not loaded","MANIFEST_NOT_LOADED");const a=["basic","composite","layout"];for(const r of a){const i=this.manifest.components[r]||[];for(const l of i){const u=l.name,d=e[u];if(!d){Ma.warn(`Component '${u}' not found in bundle`);continue}this.registerComponent(u,d,l)}}}registerComponent(e,a,r){this.registry[e]&&Ma.warn(`Component '${e}' already registered, overwriting`);const i=Ye.memo(a);this.registry[e]={component:i,metadata:r},Ma.log(`[ComponentRegistry] Registered component: ${e} (${r.type})`)}getComponent(e){const a=this.registry[e];return a?a.component:null}getMetadata(e){const a=this.registry[e];return a?a.metadata:null}hasComponent(e){return e in this.registry}getComponentsByType(e){return Object.entries(this.registry).filter(([a,r])=>r.metadata.type===e).map(([a,r])=>a)}getAllComponents(){return Object.keys(this.registry)}getComponentMap(){const e={};for(const[a,r]of Object.entries(this.registry))e[a]=r.component;return e}getLoadingState(){return this.loadingState}getError(){return this.error}getTemplateId(){return this.templateId}getManifest(){return this.manifest}clear(){this.registry={},this.manifest=null,this.loadingState="idle",this.error=null,this.templateId=null,this.templateType=null,Ma.log("Registry cleared")}};$(Pn,"instance",null),$(Pn,"manifestCache",new Map);let da=Pn;const ep=ct("TranslationEngine");class nd extends Error{constructor(a,r,i){super(a);$(this,"key");$(this,"locale");this.key=r,this.locale=i,this.name="TranslationError"}}const Rn=class Rn{constructor(e={}){$(this,"cache",new Map);$(this,"translations",new Map);$(this,"options");$(this,"cacheVersion",0);this.options={defaultLocale:e.defaultLocale||"ko",fallbackLocale:e.fallbackLocale||"en",cacheTTL:e.cacheTTL||3e5}}static getInstance(e={}){return Rn.instance||(Rn.instance=new Rn(e)),Rn.instance}static resetInstance(){Rn.instance=null}setCacheVersion(e){this.cacheVersion!==e&&(ep.log("Cache version updated:",this.cacheVersion,"->",e),this.cacheVersion=e,this.cache.clear())}getCacheVersion(){return this.cacheVersion}async loadTranslations(e,a,r="/api",i=!1){const l=`${e}:${a}`;if(!i){const u=this.getFromCache(l);if(u)return this.translations.set(l,u),u}try{const u=[];i&&u.push(`_=${Date.now()}`);const d=La(`${r}/templates/${e}/lang/${a}`,"json",this.cacheVersion>0?this.cacheVersion:null,u.length>0?u.join("&"):void 0),f=await fetch(d);if(!f.ok)throw new nd(`Failed to load translations: ${f.statusText}`,void 0,a);const m=await f.json();return this.saveToCache(l,m),this.translations.set(l,m),m}catch(u){throw new nd(`Failed to fetch translations for ${a}: ${u instanceof Error?u.message:String(u)}`,void 0,a)}}resolveTranslations(e,a,r){let i=e;const l=5;let u=0;for(;u"="+this.translate(m,a,void 0,r)),i===d)break;u++}return i.replace(Rn.TRANSLATION_PATTERN,(d,f,g)=>{const{cleanedParams:m,trailing:b}=this.separateTrailingText(g);return this.translate(f,a,m,r)+b})}translate(e,a,r,i){const l=this.getTranslation(e,a),u=r&&this.cleanParamsStr(r);if(u){const d=this.parseParams(u,i);return this.replaceParams(l,d)}return l}getTranslation(e,a){const{templateId:r,locale:i}=a,l=`${r}:${i}`,u=this.translations.get(l);if(u){const d=this.getNestedValue(u,e);if(d!==null)return d}if(i!==this.options.fallbackLocale){const d=`${r}:${this.options.fallbackLocale}`,f=this.translations.get(d);if(f){const g=this.getNestedValue(f,e);if(g!==null)return g}}return e}getNestedValue(e,a){const r=a.split(".");let i=e;for(const l of r){if(i==null||typeof i!="object")return null;i=i[l]}return typeof i=="string"?i:null}setTranslationValue(e,a,r,i){const l=`${e}:${a}`,u=this.translations.get(l)??{},d=r.split(".");let f=u;for(let g=0;g(l.push(f),`__PLACEHOLDER_${l.length-1}__`)).matchAll(Rn.PARAM_PATTERN);for(const f of d){const[,g,m]=f,b=m.replace(/__PLACEHOLDER_(\d+)__/g,(v,S)=>l[parseInt(S,10)]);r[g.trim()]=this.resolveParamValue(b.trim(),a)}return r}resolveParamValue(e,a){if(e.startsWith("{{")&&e.endsWith("}}")){const r=e.slice(2,-2).trim();if(/[|&()[\]!?:+\-*/%<>=\s]/.test(r)&&a)try{const u=new Function(...Object.keys(a),`return ${r}`)(...Object.values(a));return String(u??"")}catch(l){return ep.error("Expression evaluation failed:",r,l),""}else{const l=this.getNestedDataValue(a,r);return String(l??"")}}return e}separateTrailingText(e){if(!e)return{cleanedParams:void 0,trailing:""};if(e.trimEnd().endsWith("}}"))return{cleanedParams:e,trailing:""};if(!(e.startsWith("|")?e.slice(1):e).includes("="))return{cleanedParams:void 0,trailing:e};const r=e.match(/(\s+[^\p{L}\w=|&\s][^\p{L}\w=]*\s*)$/u);return r?{cleanedParams:e.slice(0,-r[1].length),trailing:r[1]}:{cleanedParams:e,trailing:""}}cleanParamsStr(e){return this.separateTrailingText(e).cleanedParams||""}getNestedDataValue(e,a){if(!e)return;const r=a.split(".");let i=e;for(const l of r){if(i==null)return;i=i[l]}return i}replaceParams(e,a){let r=e;for(const[i,l]of Object.entries(a)){const u=new RegExp(`\\{\\{${i}\\}\\}`,"g");r=r.replace(u,String(l));const d=new RegExp(`\\{${i}\\}`,"g");r=r.replace(d,String(l))}return r}getFromCache(e){const a=this.cache.get(e);return a?Date.now()-a.timestamp>this.options.cacheTTL?(this.cache.delete(e),null):a.data:null}saveToCache(e,a){this.cache.set(e,{data:a,timestamp:Date.now()})}clearCache(){this.cache.clear(),this.translations.clear()}pruneCache(){const e=Date.now(),a=[];for(const[r,i]of this.cache.entries())e-i.timestamp>this.options.cacheTTL&&a.push(r);for(const r of a)this.cache.delete(r)}getCacheStats(){const e=Date.now();let a=0;for(const r of this.cache.values())e-r.timestamp>this.options.cacheTTL&&a++;return{size:this.cache.size,expired:a}}};$(Rn,"instance",null),$(Rn,"TRANSLATION_PATTERN",/\$t:(?:defer:)?([a-zA-Z0-9._-]+)(\|(?:(?!\$t:).)+)?/g),$(Rn,"NESTED_TRANSLATION_PARAM_PATTERN",/=(\$t:([a-zA-Z0-9._-]+))(?=[|&\s]|$)/g),$(Rn,"PARAM_PATTERN",/([^=|&]+)=([^|&]+)/g);let Cr=Rn,ad=null;function VS(o){return ad||(ad=new Cr(o)),ad}const tp=Object.freeze(Object.defineProperty({__proto__:null,TranslationEngine:Cr,TranslationError:nd,getTranslationEngine:VS},Symbol.toStringTag,{value:"Module"})),Wi=ct("PipeRegistry");function np(o,e){const a=o.getFullYear(),r=String(o.getMonth()+1).padStart(2,"0"),i=String(o.getDate()).padStart(2,"0"),l=String(o.getHours()).padStart(2,"0"),u=String(o.getMinutes()).padStart(2,"0"),d=String(o.getSeconds()).padStart(2,"0");return e.replace("YYYY",String(a)).replace("YY",String(a).slice(-2)).replace("MM",r).replace("M",String(o.getMonth()+1)).replace("DD",i).replace("D",String(o.getDate())).replace("HH",l).replace("H",String(o.getHours())).replace("mm",u).replace("m",String(o.getMinutes())).replace("ss",d).replace("s",String(o.getSeconds()))}function FS(o,e="ko"){const r=new Date().getTime()-o.getTime(),i=Math.floor(r/1e3),l=Math.floor(i/60),u=Math.floor(l/60),d=Math.floor(u/24),f=Math.floor(d/7),g=Math.floor(d/30),m=Math.floor(d/365);return e==="ko"?i<60?"방금 전":l<60?`${l}분 전`:u<24?`${u}시간 전`:d<7?`${d}일 전`:f<4?`${f}주 전`:g<12?`${g}개월 전`:`${m}년 전`:i<60?"just now":l<60?`${l} minute${l===1?"":"s"} ago`:u<24?`${u} hour${u===1?"":"s"} ago`:d<7?`${d} day${d===1?"":"s"} ago`:f<4?`${f} week${f===1?"":"s"} ago`:g<12?`${g} month${g===1?"":"s"} ago`:`${m} year${m===1?"":"s"} ago`}function rd(o){if(o==null)return null;if(o instanceof Date)return o;if(typeof o=="number")return new Date(o);if(typeof o=="string"){const e=new Date(o);return isNaN(e.getTime())?null:e}return null}const Ws={date:{fn:(o,e="YYYY-MM-DD")=>{const a=rd(o);return a?np(a,e):""},description:"날짜 포맷 (기본: YYYY-MM-DD)"},datetime:{fn:(o,e="YYYY-MM-DD HH:mm")=>{const a=rd(o);return a?np(a,e):""},description:"날짜+시간 포맷 (기본: YYYY-MM-DD HH:mm)"},relativeTime:{fn:(o,e="ko")=>{const a=rd(o);return a?FS(a,e):""},description:'상대 시간 표시 (예: "3분 전")'},number:{fn:(o,e)=>{const a=Number(o);if(isNaN(a))return String(o??"");const r={};return e!==void 0&&(r.minimumFractionDigits=e,r.maximumFractionDigits=e),a.toLocaleString(void 0,r)},description:"숫자 포맷 (천단위 구분, 선택적 소수점)"},truncate:{fn:(o,e=100,a="...")=>typeof o!="string"?String(o??""):o.length<=e?o:o.slice(0,e)+a,description:'문자열 자르기 (기본: 100자, 접미사: "...")'},uppercase:{fn:o=>typeof o!="string"?String(o??""):o.toUpperCase(),description:"대문자 변환"},lowercase:{fn:o=>typeof o!="string"?String(o??""):o.toLowerCase(),description:"소문자 변환"},stripHtml:{fn:o=>typeof o!="string"?String(o??""):o.replace(/<[^>]*>/g,""),description:"HTML 태그 제거"},default:{fn:(o,e="")=>o==null||o===""?e:o,description:"기본값 설정 (null, undefined, 빈문자열 시)"},fallback:{fn:(o,e)=>o??e,description:"폴백 값 설정 (null, undefined 시만)"},first:{fn:o=>{if(Array.isArray(o))return o[0]},description:"배열의 첫 번째 요소"},last:{fn:o=>{if(Array.isArray(o))return o[o.length-1]},description:"배열의 마지막 요소"},join:{fn:(o,e=", ")=>Array.isArray(o)?o.join(e):"",description:'배열을 문자열로 결합 (기본 구분자: ", ")'},length:{fn:o=>Array.isArray(o)||typeof o=="string"?o.length:0,description:"배열/문자열 길이"},filterBy:{fn:(o,e,a)=>Array.isArray(o)?Array.isArray(e)?o.filter(r=>{const i=a?r?.[a]:r;return e.includes(i)}):o:[],description:"배열 필터링 (allowList에 포함된 항목만 반환)"},keys:{fn:o=>o==null||typeof o!="object"?[]:Object.keys(o),description:"객체의 키 배열"},values:{fn:o=>o==null||typeof o!="object"?[]:Object.values(o),description:"객체의 값 배열"},json:{fn:(o,e)=>{try{return JSON.stringify(o,null,e)}catch{return""}},description:"JSON 문자열로 변환"},localized:{fn:(o,e)=>o==null?"":typeof o=="string"?o:typeof o!="object"?String(o):o[e||"ko"]||o.ko||o.en||Object.values(o)[0]||"",description:"다국어 객체에서 로케일에 맞는 값 추출"}},Yi=new Map,mi=class mi{static getInstance(){return mi.instance||(mi.instance=new mi),mi.instance}register(e,a,r){if(Ws[e]){Wi.warn(`[PipeRegistry] 내장 파이프를 덮어쓸 수 없습니다: ${e}`);return}Yi.set(e,{fn:a,description:r}),Wi.log(`[PipeRegistry] 커스텀 파이프 등록됨: ${e}`)}unregister(e){if(Ws[e])return Wi.warn(`[PipeRegistry] 내장 파이프는 해제할 수 없습니다: ${e}`),!1;const a=Yi.delete(e);return a&&Wi.log(`[PipeRegistry] 커스텀 파이프 해제됨: ${e}`),a}get(e){const a=Ws[e];return a?a.fn:Yi.get(e)?.fn}has(e){return!!Ws[e]||Yi.has(e)}execute(e,a,r=[]){const i=this.get(e);if(!i)return Wi.warn(`[PipeRegistry] 알 수 없는 파이프: ${e}`),a;try{return i(a,...r)}catch(l){return Wi.error(`[PipeRegistry] 파이프 실행 오류 (${e}):`,l),a}}list(){const e=[];for(const[a,r]of Object.entries(Ws))e.push({name:a,description:r.description,type:"built-in"});for(const[a,r]of Yi.entries())e.push({name:a,description:r.description,type:"custom"});return e.sort((a,r)=>a.name.localeCompare(r.name))}clearCustomPipes(){Yi.clear()}};$(mi,"instance",null);let Tl=mi;Tl.getInstance();function KS(o){const e=o.trim(),a=e.indexOf("(");if(a===-1)return{name:e,args:[]};const r=e.slice(0,a).trim(),i=e.slice(a+1,-1);if(!i.trim())return{name:r,args:[]};const l=[];let u="",d=null,f=0;for(let g=0;g0?i[g-1]:"")==="\\"){u+=m;continue}if((m==='"'||m==="'")&&!d){d=m;continue}if(m===d){d=null;continue}if(d){u+=m;continue}if(m==="("||m==="["||m==="{"){f++,u+=m;continue}if(m===")"||m==="]"||m==="}"){f--,u+=m;continue}if(m===","&&f===0){l.push(ap(u.trim())),u="";continue}u+=m}return u.trim()&&l.push(ap(u.trim())),{name:r,args:l}}function ap(o){if(o==="null")return null;if(o==="undefined")return;if(o==="true")return!0;if(o==="false")return!1;const e=Number(o);return!isNaN(e)&&o!==""?e:o}function WS(o){const e=[];let a="",r=null,i=0;for(let l=0;l0?o[l-1]:"",f=l0?o[r-1]:"",u=r=2&&o.charCodeAt(0)===64976&&o.charCodeAt(o.length-1)===64977}function ip(o){return o.includes(Rl)}function sp(o){return o.slice(1,-1)}function Js(o){if(typeof o=="string")return Xs(o);if(Array.isArray(o))return o.map(Js);if(o&&typeof o=="object"){const e={};for(const[a,r]of Object.entries(o))e[a]=Js(r);return e}return o}const Qs=ct("DataBindingEngine");function kl(){try{return window.G7Core?.devTools}catch{return}}class id extends Error{constructor(a,r,i){super(a);$(this,"path");$(this,"context");this.path=r,this.context=i,this.name="DataBindingError"}}const Sa=class Sa{constructor(e){$(this,"cache",new Map);$(this,"expressionFnCache",new Map);$(this,"renderCycleCache",new Map);$(this,"currentRenderCycleId",0);$(this,"defaultOptions",{defaultValue:void 0,nullSafe:!0,detectCircular:!0,maxDepth:10});e&&(this.defaultOptions={...this.defaultOptions,...e})}startRenderCycle(){this.currentRenderCycleId++,this.renderCycleCache.clear()}isRenderCycleCacheActive(){return this.currentRenderCycleId>0}getFromRenderCycleCache(e){if(this.isRenderCycleCacheActive())return this.renderCycleCache.get(e)}saveToRenderCycleCache(e,a){this.isRenderCycleCacheActive()&&this.renderCycleCache.set(e,a)}resolveBindings(e,a,r,i){const l={...this.defaultOptions,...r},u=kl(),d=a._computed&&!a.$computed?{...a,$computed:a._computed}:a;return e.replace(Sa.BINDING_PATTERN,(f,g)=>{const m=g.trim();let b=!1,v=m;if(m.startsWith(Er)&&(b=!0,v=m.slice(Er.length)),ci(v)){const R=u?.isEnabled()?performance.now():0;try{const[D,U]=WS(v);let j,P=!1;const X=/[?:|&!+\-*/<>=()]/.test(D)||/\[['"]/.test(D),ge=D.startsWith("_global")||D.startsWith("_local")||D.startsWith("_isolated")||D.startsWith("$parent");if(l.skipCache)X?j=this.evaluateExpression(D,d):j=this.resolvePath(D,d,l);else if(X){const $e=this.getFromRenderCycleCache(`expr:${D}`);$e!==void 0?(j=$e,P=!0):(j=this.evaluateExpression(D,d),this.saveToRenderCycleCache(`expr:${D}`,j))}else if(ge){const $e=this.getFromRenderCycleCache(D);$e!==void 0?(j=$e,P=!0):(j=this.resolvePath(D,d,l),this.saveToRenderCycleCache(D,j))}else{const $e=this.getFromCache(D);$e!==void 0?(j=$e,P=!0):(j=this.resolvePath(D,d,l),this.saveToCache(D,j))}const Ee=YS(j,U);if(u?.isEnabled()){const $e=performance.now()-R;u.trackExpressionEval({expression:`{{${m}}}`,result:this.sanitizeResultForTracking(Ee),resultType:this.getResultType(Ee),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:P,duration:$e,method:"resolveBindings",skipCache:l.skipCache})}const Ce=this.formatValue(Ee);return b?Xs(Ce):Ce}catch(D){return Qs.error("Pipe expression evaluation failed:",v,D),f}}if(/[?:&!+\-*/<>=()]/.test(v)||/\|\|/.test(v)||/\[['"]/.test(v)){const R=u?.isEnabled()?performance.now():0;try{let D,U=!1;if(l.skipCache)D=this.evaluateExpression(v,d);else{const P=`expr:${v}`,X=this.getFromRenderCycleCache(P);X!==void 0?(D=X,U=!0):(D=this.evaluateExpression(v,d),this.saveToRenderCycleCache(P,D))}if(u?.isEnabled()){const P=performance.now()-R;u.trackExpressionEval({expression:`{{${m}}}`,result:this.sanitizeResultForTracking(D),resultType:this.getResultType(D),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:U,duration:P,method:"resolveBindings",skipCache:l.skipCache})}const j=this.formatValue(D);return b?Xs(j):j}catch(D){return Qs.error("Expression evaluation failed:",v,D),f}}if(l.skipCache){const R=u?.isEnabled()?performance.now():0,D=this.resolvePath(v,d,l);if(u?.isEnabled()){const j=performance.now()-R;u.trackExpressionEval({expression:`{{${m}}}`,result:this.sanitizeResultForTracking(D),resultType:this.getResultType(D),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:!1,duration:j,method:"resolveBindings",skipCache:!0})}const U=this.formatValue(D);return b?Xs(U):U}const E=v.startsWith("_global")||v.startsWith("_local")||v.startsWith("_isolated")||v.startsWith("$parent"),A=u?.isEnabled()?performance.now():0;let T,L=!1;if(E){const R=this.getFromRenderCycleCache(v);R!==void 0?(T=R,L=!0):(T=this.resolvePath(v,d,l),this.saveToRenderCycleCache(v,T))}else{const R=this.getFromCache(v);R!==void 0?(T=R,L=!0):(T=this.resolvePath(v,d,l),this.saveToCache(v,T))}if(u?.isEnabled()){const R=performance.now()-A;u.trackExpressionEval({expression:`{{${m}}}`,result:this.sanitizeResultForTracking(T),resultType:this.getResultType(T),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:L,duration:R,method:"resolveBindings",skipCache:l.skipCache})}const M=this.formatValue(T);return b?Xs(M):M})}resolve(e,a,r,i){const l={...this.defaultOptions,...r},u=kl(),d=u?.isEnabled()?performance.now():0;if(l.skipCache){const b=this.resolvePath(e,a,l);return u?.isEnabled()&&u.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(b),resultType:this.getResultType(b),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:!1,duration:performance.now()-d,method:"resolve",skipCache:!0}),b}const f=e.startsWith("_global")||e.startsWith("_local")||e.startsWith("_isolated")||e.startsWith("$parent");let g=!1;if(f){const b=this.getFromRenderCycleCache(e);if(b!==void 0)return g=!0,u?.isEnabled()&&u.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(b),resultType:this.getResultType(b),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:!0,duration:performance.now()-d,method:"resolve",skipCache:l.skipCache}),b}else{const b=this.getFromCache(e);if(b!==void 0)return g=!0,u?.isEnabled()&&u.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(b),resultType:this.getResultType(b),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:!0,duration:performance.now()-d,method:"resolve",skipCache:l.skipCache}),b}const m=this.resolvePath(e,a,l);return f?this.saveToRenderCycleCache(e,m):this.saveToCache(e,m),u?.isEnabled()&&u.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(m),resultType:this.getResultType(m),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:g,duration:performance.now()-d,method:"resolve",skipCache:l.skipCache}),m}resolvePath(e,a,r,i=0,l=new WeakSet){if(r.maxDepth&&i>r.maxDepth){if(r.detectCircular)throw new id(`Maximum depth exceeded (${r.maxDepth}). Possible circular reference.`,e,a);return r.defaultValue}const u=this.parsePath(e);let d=a;for(let f=0;fSa.CACHE_EXPIRY){this.cache.delete(e),r?.isEnabled()&&r.recordCacheMiss();return}return r?.isEnabled()&&r.recordCacheHit(),a.value}saveToCache(e,a){this.cache.set(e,{value:a,timestamp:Date.now()})}isActionDefinition(e){return typeof e.handler!="string"?!1:e.params!==void 0||Array.isArray(e.actions)||typeof e.target=="string"||e.onSuccess!==void 0||e.onError!==void 0}extractSingleBinding(e){if(!e.startsWith("{{")||!e.endsWith("}}")||e.length<5)return null;const a=e.slice(2,-2);let r=0;for(let i=0;i0)r--;else if(a[i+1]==="}")return null}}return a}resolveObject(e,a,r){if(this.isSwitchExpression(e)){const d=e;return this.resolveSwitch(d,a,r)}if(this.isActionDefinition(e))return{...e};if("iteration"in e)return{...e};const i={},u=[...["cellChildren","expandChildren","expandContext","render"],...r?.skipBindingKeys||[]];for(const[d,f]of Object.entries(e)){if(u.includes(d)){i[d]=f;continue}if(typeof f=="string"){const g=this.extractSingleBinding(f);if(g!==null){const m=g.trim();let b=!1,v=m;m.startsWith(Er)&&(b=!0,v=m.slice(Er.length));const S=/[?:|&!+\-*/<>=()]/.test(v)||/\[['"]/.test(v),E=ci(v)?this.resolveBindings(`{{${v}}}`,a,r):S?this.evaluateExpression(v,a,r):this.resolve(v,a,r);i[d]=b&&E!=null?Js(E):E}else i[d]=this.resolveBindings(f,a,r)}else Array.isArray(f)?i[d]=f.map(g=>typeof g=="string"?this.resolveBindings(g,a,r):typeof g=="object"&&g!==null?this.resolveObject(g,a,r):g):f&&typeof f=="object"?i[d]=this.resolveObject(f,a,r):i[d]=f}return i}clearCache(){this.cache.clear(),this.expressionFnCache.clear()}invalidateCacheByKeys(e){for(const a of this.cache.keys())for(const r of e)if(a===r||a.startsWith(`${r}.`)||a.startsWith(`${r}[`)){this.cache.delete(a);break}}pruneCache(){const e=Date.now();for(const[a,r]of this.cache.entries())e-r.timestamp>Sa.CACHE_EXPIRY&&this.cache.delete(a)}getCacheStats(){const e=Date.now();let a=0;for(const r of this.cache.values())e-r.timestamp>Sa.CACHE_EXPIRY&&a++;return{size:this.cache.size,expired:a}}evaluateExpression(e,a,r){const i=kl(),l=i?.isEnabled()?performance.now():0;i?.isEnabled()&&i.trackBindingEval();try{let u=this.preprocessOptionalChaining(e);u=this.preprocessTranslationTokens(u);const d=this.extractVariablesFromExpression(u),f={...a};for(const D of d)D in f||(f[D]=void 0);a._computed&&!f.$computed&&(f.$computed=a._computed);let g=a.$templateId,m=a.$locale;if(typeof window<"u"&&(!g||!m)){const D=window.__templateApp?.getConfig?.();g??(g=D?.templateId),m??(m=D?.locale)}const b=m||"ko";f.$localized=(D,U)=>{if(D==null&&!U)return"";if(typeof D=="string")return D;if(D&&typeof D=="object"&&D[b])return D[b];if(U&&typeof U=="string"){const j=f.$t?f.$t(U):U;if(j&&j!==U)return j}return D&&typeof D=="object"?D.ko||D.en||Object.values(D)[0]||"":D==null?"":String(D)};const v=typeof window<"u"?window.G7Core:void 0;f.$uuid=()=>v?.uuid?v.uuid():typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,D=>{const U=Math.random()*16|0;return(D==="x"?U:U&3|8).toString(16)});const S={templateId:g||"",locale:b};f.$t=D=>{if(!D||typeof D!="string")return"";try{return Cr.getInstance().translate(D,S)}catch(U){return Qs.warn("$t() translation failed for key:",D,U),D}},f.$get=(D,U,j=void 0)=>{if(D==null)return j;const P=Array.isArray(U)?U:[U];if(P.length===0)return D;let X=D;for(const ge of P){if(X==null||ge==null)return j;X=X[ge]}return X??j};const E=Object.keys(f),A=Object.values(f),T=`${u}|${E.join(",")}`;let L=this.expressionFnCache.get(T);const M=!!L;L||(L=new Function(...E,`return (${u});`),this.expressionFnCache.set(T,L));const R=L(...A);if(i?.isEnabled()){const D=performance.now()-l;i.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(R),resultType:this.getResultType(R),componentId:r?.componentId,componentName:r?.componentName,propName:r?.propName,fromCache:M,duration:D,method:"evaluateExpression",skipCache:r?.skipCache})}return R}catch(u){throw new Error(`Failed to evaluate expression "${e}": ${u instanceof Error?u.message:String(u)}`)}}getResultType(e){return e===null?"null":e===void 0?"undefined":Array.isArray(e)?"array":typeof e}sanitizeResultForTracking(e){if(e==null||typeof e!="object")return e;try{if(Array.isArray(e))return e.length>10?`[Array(${e.length})]`:e.slice(0,10);const a=Object.keys(e);return a.length>20?`{Object(${a.length} keys)}`:(JSON.stringify(e),e)}catch{return"[Complex Object]"}}preprocessTranslationTokens(e){return e=e.replace(/(['"])(\$t:([a-zA-Z_][a-zA-Z0-9_.\-]*))\1/g,(a,r,i,l)=>`$t('${l}')`),e.replace(/(?(a.push(l),`__STRING_LITERAL_${a.length-1}__`));const i=[];return r=r.replace(/\$t:[a-zA-Z_][a-zA-Z0-9_.\-]*(?:\|[^'"\s,)]+)?/g,l=>(i.push(l),`__TRANSLATION_TOKEN_${i.length-1}__`)),r=r.replace(/([a-zA-Z_$][a-zA-Z0-9_$]*)\.(?!\?)/g,"$1?."),r=r.replace(/__TRANSLATION_TOKEN_(\d+)__/g,(l,u)=>i[parseInt(u,10)]),r=r.replace(/__STRING_LITERAL_(\d+)__/g,(l,u)=>a[parseInt(u,10)]),r}extractVariablesFromExpression(e){const a=new Set(["true","false","null","undefined","NaN","Infinity","if","else","for","while","do","switch","case","break","continue","return","function","class","const","let","var","new","delete","typeof","instanceof","this","super","import","export","default","try","catch","finally","throw","Math","Date","JSON","Array","Object","String","Number","Boolean","RegExp","Set","Map","WeakSet","WeakMap","Symbol","Promise","BigInt","Error","parseInt","parseFloat","isNaN","isFinite","encodeURI","decodeURI","encodeURIComponent","decodeURIComponent"]),r=/(?{a!==null&&clearTimeout(a),a=setTimeout(()=>{o(...r)},e)})}class QS{constructor(){$(this,"subscribers",new Set);$(this,"currentWidth",1024);$(this,"debouncedHandler",null);$(this,"isInitialized",!1);this.initialize()}initialize(){typeof window>"u"||(this.currentWidth=window.innerWidth,this.isInitialized=!0,this.debouncedHandler=JS(()=>{this.currentWidth=window.innerWidth,this.notifySubscribers()},150),window.addEventListener("resize",this.debouncedHandler))}notifySubscribers(){this.subscribers.forEach(e=>{e(this.currentWidth)})}subscribe(e){return this.subscribers.add(e),e(this.currentWidth),()=>{this.subscribers.delete(e)}}getWidth(){return this.currentWidth}parseRange(e){if(Ol.has(e))return Ol.get(e)??null;let a=null;if(Dl[e])a={...Dl[e]};else{const r=e.match(/^(-?\d*)-(-?\d*)$/);if(r){const[,i,l]=r,u=i===""?0:parseInt(i,10),d=l===""?1/0:parseInt(l,10);!isNaN(u)&&!isNaN(d)&&u<=d&&(a={min:u,max:d})}}return Ol.set(e,a),a}getMatchingKey(e,a){const r=[];for(const i of Object.keys(e)){const l=this.parseRange(i);l&&a>=l.min&&a<=l.max&&r.push({key:i,range:l,isPreset:!!Dl[i]})}return r.length===0?null:(r.sort((i,l)=>{if(i.isPreset!==l.isPreset)return i.isPreset?1:-1;const u=i.range.max-i.range.min,d=l.range.max-l.range.min;return u-d}),r[0].key)}matches(e){const a=this.parseRange(e);return a?this.currentWidth>=a.min&&this.currentWidth<=a.max:!1}clearSubscribers(){this.subscribers.clear()}destroy(){this.debouncedHandler&&typeof window<"u"&&window.removeEventListener("resize",this.debouncedHandler),this.clearSubscribers(),Ol.clear()}_setWidthForTesting(e){this.currentWidth=e,this.notifySubscribers()}}const ui=new QS,Ll=ct("ConditionEvaluator");function ZS(o){switch(o){case"true":return{value:!0};case"false":return{value:!1};case"null":return{value:null};case"undefined":return{value:void 0};default:return}}function ew(o){return/[?:|&!+\-*/<>=()]/.test(o)}function tw(o){if(!o.startsWith("{{")||!o.endsWith("}}"))return null;const e=o.slice(2,-2);let a=null,r=0;for(let i=0;i0?e[i-1]:"")!=="\\"&&((l==='"'||l==="'")&&!a?a=l:l===a&&(a=null),!a&&(l==="{"&&r++,l==="}"&&r--,r<0)))return null}return r===0?e.trim():null}function nw(o,e,a){if(!o)return!0;try{const r=tw(o);let i;if(r!==null){const l=ZS(r);l!==void 0?i=l.value:ci(r)?i=a.resolveBindings(`{{${r}}}`,e,{skipCache:!0}):ew(r)?i=a.evaluateExpression(r,e):i=a.resolve(r,e,{skipCache:!0})}else i=a.resolveBindings(o,e,{skipCache:!0});if(typeof i=="string"){const l=i.toLowerCase().trim();if(l==="false"||l==="0"||l===""||l==="null"||l==="undefined")return!1}return!!i}catch(r){return Ll.warn(`evaluateStringCondition: 조건 평가 실패: ${o}`,r),!1}}function Ml(o,e,a){if(typeof o=="string")return nw(o,e,a);if("and"in o){if(!Array.isArray(o.and)||o.and.length===0)return Ll.warn("evaluateConditionExpression: AND 그룹이 비어있습니다"),!0;for(const r of o.and)if(!Ml(r,e,a))return!1;return!0}if("or"in o){if(!Array.isArray(o.or)||o.or.length===0)return Ll.warn("evaluateConditionExpression: OR 그룹이 비어있습니다"),!1;for(const r of o.or)if(Ml(r,e,a))return!0;return!1}return Ll.warn("evaluateConditionExpression: 알 수 없는 조건 형식",o),!1}function op(o,e,a){if(!Array.isArray(o)||o.length===0)return{matched:!1,branchIndex:-1};for(let r=0;r=()[\]{}]/.test(o)}function up(o){if(!o.startsWith("{{")||!o.endsWith("}}"))return null;const e=o.slice(2,-2);let a=null,r=0;for(let i=0;i0?e[i-1]:"")!=="\\"&&((l==='"'||l==="'")&&!a?a=l:l===a&&(a=null),!a&&(l==="{"&&r++,l==="}"&&r--,r<0)))return null}return r===0?e.trim():null}function od(o,e,a){let r=o;if(o.startsWith("{{")&&o.endsWith("}}")&&(r=o.slice(2,-2).trim()),sd(r))try{return a.evaluateExpression(r,e)}catch(i){Xa.warn(`resolveIterationSource: 표현식 평가 실패: ${o}`,i);return}return a.resolve(r,e,{skipCache:!0})}function sw(o,e){const a={...o};if(e?.parentDataContext)for(const[r,i]of Object.entries(e.parentDataContext))r in a||(a[r]=i);if(e?.state){const r=a._local||{};a._local={...r,...e.state}}return e?.isolatedContext?.state&&(a._isolated=e.isolatedContext.state),a}function ld(o,e,a,r){if(!e||!Array.isArray(e)||e.length===0)return o;const i=r?.actionDispatcher??Zp(),l={...o,actions:e},u=i.bindActionsToProps(l,a,r?.componentContext);return delete u.actions,u}function dp(o,e,a,r){if(typeof o=="boolean")return o;if(!o)return!0;try{const i=up(o);let l;if(i!==null){const u=iw.get(i);u!==void 0?l=u:ci(i)?l=a.resolveBindings(`{{${i}}}`,e,{skipCache:!0}):sd(i)?l=a.evaluateExpression(i,e):l=a.resolve(i,e,{skipCache:!0})}else l=a.resolveBindings(o,e,{skipCache:!0});if(typeof l=="string"){const u=l.toLowerCase().trim();if(u==="false"||u==="0"||u===""||u==="null"||u==="undefined")return!1}return!!l}catch(i){return Xa.warn(`evaluateIfCondition: 조건 평가 실패 (컴포넌트: ${r||"unknown"}):`,i),!1}}function Xi(o,e,a,r){if(o.if!==void 0)return dp(o.if,e,a,r);if(o.condition!==void 0)return dp(o.condition,e,a,r);if(o.conditions===void 0)return!0;const i=o.conditions;try{return aw(i)?Ml(i,e,a):rw(i)?op(i,e,a).matched:(Xa.warn(`evaluateRenderCondition: 알 수 없는 conditions 형식 (컴포넌트: ${r||"unknown"})`),!0)}catch(l){return Xa.warn(`evaluateRenderCondition: conditions 평가 실패 (컴포넌트: ${r||"unknown"}):`,l),!1}}function fp(o){if(!o.responsive)return o;const e=ui.getWidth(),a=ui.getMatchingKey(o.responsive,e);if(!a)return o;const r=o.responsive[a];return{...o,props:{...o.props,...r.props},children:r.children??o.children,text:r.text??o.text,if:r.if??o.if,iteration:r.iteration??o.iteration}}function Zs(o,e,a,r,i){if(!o||o.length===0)return[];const l=i?.bindingEngine??new wn,u=i?.translationEngine??Cr.getInstance(),d=i?.translationContext??{templateId:"",locale:"ko"},f=sw(e,i?.componentContext),g=(v,S)=>{if(typeof v=="string"){if(rp(v))return sp(v);if(ip(v)){const A=[],T=v.replace(new RegExp(`${Rl}([^${Ys}]*)${Ys}`,"g"),(M,R)=>(A.push(R),`${_r}${A.length-1}${_r}`));let L=T;return/\$t:[a-zA-Z0-9._-]+/.test(T)&&(L=u.resolveTranslations(T,d,S)),L.replace(new RegExp(`${_r}(\\d+)${_r}`,"g"),(M,R)=>A[parseInt(R)])}if(v.startsWith("$t:defer:")){const A="$t:"+v.slice(9);return u.resolveTranslations(A,d,S)}if(v.startsWith("$t:"))return u.resolveTranslations(v,d,S);const E=up(v);if(E!==null){let A=!1,T=E;E.startsWith(Er)&&(A=!0,T=E.slice(Er.length));let L;if(ci(T))L=l.resolveBindings(`{{${T}}}`,S,{skipCache:!0});else if(sd(T))try{L=l.evaluateExpression(T,S)}catch(M){Xa.warn("renderItemChildren: 표현식 평가 실패:",M);return}else L=l.resolve(T,S,{skipCache:!0});return!A&&typeof L=="string"&&/\$t:[a-zA-Z0-9._-]+/.test(L)&&(L=u.resolveTranslations(L,d,S)),A&&L!=null?Js(L):L}if(v.includes("{{")){const A=l.resolveBindings(v,S,{skipCache:!0});return typeof A=="string"&&/\$t:[a-zA-Z0-9._-]+/.test(A)?u.resolveTranslations(A,d,S):A}return v}if(Array.isArray(v))return v.map(E=>g(E,S));if(v&&typeof v=="object"){const E={};for(const[A,T]of Object.entries(v))E[A]=g(T,S);return E}return v},m=(v,S)=>{if(!v)return{};const E={};for(const[A,T]of Object.entries(v))E[A]=g(T,S);return E},b=(v,S,E)=>{const A=fp(v),T=A.iteration;if(!T)return[];const L=od(T.source,E,l);if(!Array.isArray(L))return Xa.warn(`renderItemChildren: iteration.source가 배열이 아닙니다: ${T.source}`),[];const M=lp();if(M?.isEnabled()){const D=`${S}-iteration`;M.trackIteration(D,T.source,T.item_var,T.index_var,L.length)}const R=a[A.name];return R?L.flatMap((D,U)=>{const j={...E,[T.item_var]:D,[`${T.item_var}_index`]:U,...T.index_var?{[T.index_var]:U}:{}},P=Xi({if:A.if,condition:A.condition,conditions:A.conditions},j,l,A.id);if(A.if&&M?.isEnabled()){const Xe=`${S}-iter-${U}-if`;M.trackIfCondition(Xe,A.if,P,A.name)}if(!P)return[];const X=A.id?String(g(A.id,j)):void 0,ge=`${S}-iter-${U}`,Ee=i?.getRemountKey?i.getRemountKey(X,ge):ge,Ce=m(A.props,j),$e=ld(Ce,A.actions,j,{actionDispatcher:i?.actionDispatcher,componentContext:i?.componentContext});let Pe=null;return A.text!==void 0?Pe=g(A.text,j):A.children&&A.children.length>0&&(Pe=Zs(A.children,j,a,Ee,i)),M?.isEnabled()&&M.trackRender(A.name),[Ye.createElement(R,{key:Ee,...$e},Pe)]}):(Xa.warn(`renderItemChildren: 컴포넌트를 찾을 수 없습니다: ${A.name}`),[])};return o.flatMap((v,S)=>{const E=fp(v),A=E.id?String(g(E.id,f)):void 0,T=r?`${r}-${A||S}`:A||`child-${S}`,L=i?.getRemountKey?i.getRemountKey(A,T):T;if(E.iteration)return b(E,L,f);const M=Xi({if:E.if,condition:E.condition,conditions:E.conditions},f,l,E.id),R=lp();if(E.if&&R?.isEnabled()){const X=`${L}-if`;R.trackIfCondition(X,E.if,M,E.name)}if(!M)return[];const D=a[E.name];if(!D)return Xa.warn(`renderItemChildren: 컴포넌트를 찾을 수 없습니다: ${E.name}`),[];const U=m(E.props,f),j=ld(U,E.actions,f,{actionDispatcher:i?.actionDispatcher,componentContext:i?.componentContext});let P=null;return E.text!==void 0?P=g(E.text,f):E.children&&E.children.length>0&&(P=Zs(E.children,f,a,L,i)),R?.isEnabled()&&R.trackRender(E.name),[Ye.createElement(D,{key:L,...j},P)]})}function Ji(o,e,a,r){let i,l;return a instanceof wn?(i=a,l=r):(i=cp,l=a),i.resolveBindings(o,e,l)}function ow(o,e,a,r){const i=a??cp,l={skipCache:!0,...r};let u;try{u=i.resolveBindings(o.key,e,{skipCache:l.skipCache})?.toString()?.trim()??""}catch(g){Xa.warn("resolveClassMap: key 평가 실패:",o.key,g),u=""}let d="";u&&o.variants&&u in o.variants?d=o.variants[u]:o.default&&(d=o.default);const f=[];return o.base?.trim()&&f.push(o.base.trim()),d?.trim()&&f.push(d.trim()),f.join(" ")}function hp(o,e){return function(){return o.apply(e,arguments)}}const{toString:lw}=Object.prototype,{getPrototypeOf:$l}=Object,{iterator:Nl,toStringTag:gp}=Symbol,Il=(o=>e=>{const a=lw.call(e);return o[a]||(o[a]=a.slice(8,-1).toLowerCase())})(Object.create(null)),fa=o=>(o=o.toLowerCase(),e=>Il(e)===o),Hl=o=>e=>typeof e===o,{isArray:Qi}=Array,Zi=Hl("undefined");function eo(o){return o!==null&&!Zi(o)&&o.constructor!==null&&!Zi(o.constructor)&&xn(o.constructor.isBuffer)&&o.constructor.isBuffer(o)}const pp=fa("ArrayBuffer");function cw(o){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(o):e=o&&o.buffer&&pp(o.buffer),e}const uw=Hl("string"),xn=Hl("function"),mp=Hl("number"),to=o=>o!==null&&typeof o=="object",dw=o=>o===!0||o===!1,zl=o=>{if(Il(o)!=="object")return!1;const e=$l(o);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(gp in o)&&!(Nl in o)},fw=o=>{if(!to(o)||eo(o))return!1;try{return Object.keys(o).length===0&&Object.getPrototypeOf(o)===Object.prototype}catch{return!1}},hw=fa("Date"),gw=fa("File"),pw=o=>!!(o&&typeof o.uri<"u"),mw=o=>o&&typeof o.getParts<"u",yw=fa("Blob"),bw=fa("FileList"),vw=o=>to(o)&&xn(o.pipe);function Sw(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}}const yp=Sw(),bp=typeof yp.FormData<"u"?yp.FormData:void 0,ww=o=>{if(!o)return!1;if(bp&&o instanceof bp)return!0;const e=$l(o);if(!e||e===Object.prototype||!xn(o.append))return!1;const a=Il(o);return a==="formdata"||a==="object"&&xn(o.toString)&&o.toString()==="[object FormData]"},Cw=fa("URLSearchParams"),[Ew,_w,Aw,xw]=["ReadableStream","Request","Response","Headers"].map(fa),Tw=o=>o.trim?o.trim():o.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function no(o,e,{allOwnKeys:a=!1}={}){if(o===null||typeof o>"u")return;let r,i;if(typeof o!="object"&&(o=[o]),Qi(o))for(r=0,i=o.length;r0;)if(i=a[r],e===i.toLowerCase())return i;return null}const di=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Sp=o=>!Zi(o)&&o!==di;function cd(...o){const{caseless:e,skipUndefined:a}=Sp(this)&&this||{},r={},i=(l,u)=>{if(u==="__proto__"||u==="constructor"||u==="prototype")return;const d=e&&vp(r,u)||u,f=ud(r,d)?r[d]:void 0;zl(f)&&zl(l)?r[d]=cd(f,l):zl(l)?r[d]=cd({},l):Qi(l)?r[d]=l.slice():(!a||!Zi(l))&&(r[d]=l)};for(let l=0,u=o.length;l(no(e,(i,l)=>{a&&xn(i)?Object.defineProperty(o,l,{__proto__:null,value:hp(i,a),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(o,l,{__proto__:null,value:i,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:r}),o),kw=o=>(o.charCodeAt(0)===65279&&(o=o.slice(1)),o),Dw=(o,e,a,r)=>{o.prototype=Object.create(e.prototype,r),Object.defineProperty(o.prototype,"constructor",{__proto__:null,value:o,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(o,"super",{__proto__:null,value:e.prototype}),a&&Object.assign(o.prototype,a)},Ow=(o,e,a,r)=>{let i,l,u;const d={};if(e=e||{},o==null)return e;do{for(i=Object.getOwnPropertyNames(o),l=i.length;l-- >0;)u=i[l],(!r||r(u,o,e))&&!d[u]&&(e[u]=o[u],d[u]=!0);o=a!==!1&&$l(o)}while(o&&(!a||a(o,e))&&o!==Object.prototype);return e},Lw=(o,e,a)=>{o=String(o),(a===void 0||a>o.length)&&(a=o.length),a-=e.length;const r=o.indexOf(e,a);return r!==-1&&r===a},Mw=o=>{if(!o)return null;if(Qi(o))return o;let e=o.length;if(!mp(e))return null;const a=new Array(e);for(;e-- >0;)a[e]=o[e];return a},$w=(o=>e=>o&&e instanceof o)(typeof Uint8Array<"u"&&$l(Uint8Array)),Nw=(o,e)=>{const r=(o&&o[Nl]).call(o);let i;for(;(i=r.next())&&!i.done;){const l=i.value;e.call(o,l[0],l[1])}},Iw=(o,e)=>{let a;const r=[];for(;(a=o.exec(e))!==null;)r.push(a);return r},Hw=fa("HTMLFormElement"),zw=o=>o.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(a,r,i){return r.toUpperCase()+i}),ud=(({hasOwnProperty:o})=>(e,a)=>o.call(e,a))(Object.prototype),jw=fa("RegExp"),wp=(o,e)=>{const a=Object.getOwnPropertyDescriptors(o),r={};no(a,(i,l)=>{let u;(u=e(i,l,o))!==!1&&(r[l]=u||i)}),Object.defineProperties(o,r)},Uw=o=>{wp(o,(e,a)=>{if(xn(o)&&["arguments","caller","callee"].includes(a))return!1;const r=o[a];if(xn(r)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+a+"'")})}})},Bw=(o,e)=>{const a={},r=i=>{i.forEach(l=>{a[l]=!0})};return Qi(o)?r(o):r(String(o).split(e)),a},Pw=()=>{},qw=(o,e)=>o!=null&&Number.isFinite(o=+o)?o:e;function Gw(o){return!!(o&&xn(o.append)&&o[gp]==="FormData"&&o[Nl])}const Vw=o=>{const e=new WeakSet,a=r=>{if(to(r)){if(e.has(r))return;if(eo(r))return r;if(!("toJSON"in r)){e.add(r);const i=Qi(r)?[]:{};return no(r,(l,u)=>{const d=a(l);!Zi(d)&&(i[u]=d)}),e.delete(r),i}}return r};return a(o)},Fw=fa("AsyncFunction"),Kw=o=>o&&(to(o)||xn(o))&&xn(o.then)&&xn(o.catch),Cp=((o,e)=>o?setImmediate:e?((a,r)=>(di.addEventListener("message",({source:i,data:l})=>{i===di&&l===a&&r.length&&r.shift()()},!1),i=>{r.push(i),di.postMessage(a,"*")}))(`axios@${Math.random()}`,[]):a=>setTimeout(a))(typeof setImmediate=="function",xn(di.postMessage)),Ww=typeof queueMicrotask<"u"?queueMicrotask.bind(di):typeof process<"u"&&process.nextTick||Cp,F={isArray:Qi,isArrayBuffer:pp,isBuffer:eo,isFormData:ww,isArrayBufferView:cw,isString:uw,isNumber:mp,isBoolean:dw,isObject:to,isPlainObject:zl,isEmptyObject:fw,isReadableStream:Ew,isRequest:_w,isResponse:Aw,isHeaders:xw,isUndefined:Zi,isDate:hw,isFile:gw,isReactNativeBlob:pw,isReactNative:mw,isBlob:yw,isRegExp:jw,isFunction:xn,isStream:vw,isURLSearchParams:Cw,isTypedArray:$w,isFileList:bw,forEach:no,merge:cd,extend:Rw,trim:Tw,stripBOM:kw,inherits:Dw,toFlatObject:Ow,kindOf:Il,kindOfTest:fa,endsWith:Lw,toArray:Mw,forEachEntry:Nw,matchAll:Iw,isHTMLForm:Hw,hasOwnProperty:ud,hasOwnProp:ud,reduceDescriptors:wp,freezeMethods:Uw,toObjectSet:Bw,toCamelCase:zw,noop:Pw,toFiniteNumber:qw,findKey:vp,global:di,isContextDefined:Sp,isSpecCompliantForm:Gw,toJSONObject:Vw,isAsyncFn:Fw,isThenable:Kw,setImmediate:Cp,asap:Ww,isIterable:o=>o!=null&&xn(o[Nl])},Yw=F.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),Xw=o=>{const e={};let a,r,i;return o&&o.split(` -`).forEach(function(u){i=u.indexOf(":"),a=u.substring(0,i).trim().toLowerCase(),r=u.substring(i+1).trim(),!(!a||e[a]&&Yw[a])&&(a==="set-cookie"?e[a]?e[a].push(r):e[a]=[r]:e[a]=e[a]?e[a]+", "+r:r)}),e};function Jw(o){let e=0,a=o.length;for(;ee;){const r=o.charCodeAt(a-1);if(r!==9&&r!==32)break;a-=1}return e===0&&a===o.length?o:o.slice(e,a)}const Qw=new RegExp("[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+","g"),Zw=new RegExp("[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+","g");function dd(o,e){return F.isArray(o)?o.map(a=>dd(a,e)):Jw(String(o).replace(e,""))}const e0=o=>dd(o,Qw),t0=o=>dd(o,Zw);function Ep(o){const e=Object.create(null);return F.forEach(o.toJSON(),(a,r)=>{e[r]=t0(a)}),e}const _p=Symbol("internals");function ao(o){return o&&String(o).trim().toLowerCase()}function jl(o){return o===!1||o==null?o:F.isArray(o)?o.map(jl):e0(String(o))}function n0(o){const e=Object.create(null),a=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=a.exec(o);)e[r[1]]=r[2];return e}const a0=o=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(o.trim());function fd(o,e,a,r,i){if(F.isFunction(r))return r.call(this,e,a);if(i&&(e=a),!!F.isString(e)){if(F.isString(r))return e.indexOf(r)!==-1;if(F.isRegExp(r))return r.test(e)}}function r0(o){return o.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,a,r)=>a.toUpperCase()+r)}function i0(o,e){const a=F.toCamelCase(" "+e);["get","set","has"].forEach(r=>{Object.defineProperty(o,r+a,{__proto__:null,value:function(i,l,u){return this[r].call(this,e,i,l,u)},configurable:!0})})}let Cn=class{constructor(e){e&&this.set(e)}set(e,a,r){const i=this;function l(d,f,g){const m=ao(f);if(!m)throw new Error("header name must be a non-empty string");const b=F.findKey(i,m);(!b||i[b]===void 0||g===!0||g===void 0&&i[b]!==!1)&&(i[b||f]=jl(d))}const u=(d,f)=>F.forEach(d,(g,m)=>l(g,m,f));if(F.isPlainObject(e)||e instanceof this.constructor)u(e,a);else if(F.isString(e)&&(e=e.trim())&&!a0(e))u(Xw(e),a);else if(F.isObject(e)&&F.isIterable(e)){let d={},f,g;for(const m of e){if(!F.isArray(m))throw TypeError("Object iterator must return a key-value pair");d[g=m[0]]=(f=d[g])?F.isArray(f)?[...f,m[1]]:[f,m[1]]:m[1]}u(d,a)}else e!=null&&l(a,e,r);return this}get(e,a){if(e=ao(e),e){const r=F.findKey(this,e);if(r){const i=this[r];if(!a)return i;if(a===!0)return n0(i);if(F.isFunction(a))return a.call(this,i,r);if(F.isRegExp(a))return a.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,a){if(e=ao(e),e){const r=F.findKey(this,e);return!!(r&&this[r]!==void 0&&(!a||fd(this,this[r],r,a)))}return!1}delete(e,a){const r=this;let i=!1;function l(u){if(u=ao(u),u){const d=F.findKey(r,u);d&&(!a||fd(r,r[d],d,a))&&(delete r[d],i=!0)}}return F.isArray(e)?e.forEach(l):l(e),i}clear(e){const a=Object.keys(this);let r=a.length,i=!1;for(;r--;){const l=a[r];(!e||fd(this,this[l],l,e,!0))&&(delete this[l],i=!0)}return i}normalize(e){const a=this,r={};return F.forEach(this,(i,l)=>{const u=F.findKey(r,l);if(u){a[u]=jl(i),delete a[l];return}const d=e?r0(l):String(l).trim();d!==l&&delete a[l],a[d]=jl(i),r[d]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const a=Object.create(null);return F.forEach(this,(r,i)=>{r!=null&&r!==!1&&(a[i]=e&&F.isArray(r)?r.join(", "):r)}),a}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,a])=>e+": "+a).join(` -`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...a){const r=new this(e);return a.forEach(i=>r.set(i)),r}static accessor(e){const r=(this[_p]=this[_p]={accessors:{}}).accessors,i=this.prototype;function l(u){const d=ao(u);r[d]||(i0(i,u),r[d]=!0)}return F.isArray(e)?e.forEach(l):l(e),this}};Cn.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),F.reduceDescriptors(Cn.prototype,({value:o},e)=>{let a=e[0].toUpperCase()+e.slice(1);return{get:()=>o,set(r){this[a]=r}}}),F.freezeMethods(Cn);const s0="[REDACTED ****]";function o0(o){if(F.hasOwnProp(o,"toJSON"))return!0;let e=Object.getPrototypeOf(o);for(;e&&e!==Object.prototype;){if(F.hasOwnProp(e,"toJSON"))return!0;e=Object.getPrototypeOf(e)}return!1}function l0(o,e){const a=new Set(e.map(l=>String(l).toLowerCase())),r=[],i=l=>{if(l===null||typeof l!="object"||F.isBuffer(l))return l;if(r.indexOf(l)!==-1)return;l instanceof Cn&&(l=l.toJSON()),r.push(l);let u;if(F.isArray(l))u=[],l.forEach((d,f)=>{const g=i(d);F.isUndefined(g)||(u[f]=g)});else{if(!F.isPlainObject(l)&&o0(l))return r.pop(),l;u=Object.create(null);for(const[d,f]of Object.entries(l)){const g=a.has(d.toLowerCase())?s0:i(f);F.isUndefined(g)||(u[d]=g)}}return r.pop(),u};return i(o)}let Oe=class RS extends Error{static from(e,a,r,i,l,u){const d=new RS(e.message,a||e.code,r,i,l);return d.cause=e,d.name=e.name,e.status!=null&&d.status==null&&(d.status=e.status),u&&Object.assign(d,u),d}constructor(e,a,r,i,l){super(e),Object.defineProperty(this,"message",{__proto__:null,value:e,enumerable:!0,writable:!0,configurable:!0}),this.name="AxiosError",this.isAxiosError=!0,a&&(this.code=a),r&&(this.config=r),i&&(this.request=i),l&&(this.response=l,this.status=l.status)}toJSON(){const e=this.config,a=e&&F.hasOwnProp(e,"redact")?e.redact:void 0,r=F.isArray(a)&&a.length>0?l0(e,a):F.toJSONObject(e);return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:r,code:this.code,status:this.status}}};Oe.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE",Oe.ERR_BAD_OPTION="ERR_BAD_OPTION",Oe.ECONNABORTED="ECONNABORTED",Oe.ETIMEDOUT="ETIMEDOUT",Oe.ECONNREFUSED="ECONNREFUSED",Oe.ERR_NETWORK="ERR_NETWORK",Oe.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS",Oe.ERR_DEPRECATED="ERR_DEPRECATED",Oe.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE",Oe.ERR_BAD_REQUEST="ERR_BAD_REQUEST",Oe.ERR_CANCELED="ERR_CANCELED",Oe.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT",Oe.ERR_INVALID_URL="ERR_INVALID_URL",Oe.ERR_FORM_DATA_DEPTH_EXCEEDED="ERR_FORM_DATA_DEPTH_EXCEEDED";const c0=null;function hd(o){return F.isPlainObject(o)||F.isArray(o)}function Ap(o){return F.endsWith(o,"[]")?o.slice(0,-2):o}function gd(o,e,a){return o?o.concat(e).map(function(i,l){return i=Ap(i),!a&&l?"["+i+"]":i}).join(a?".":""):e}function u0(o){return F.isArray(o)&&!o.some(hd)}const d0=F.toFlatObject(F,{},null,function(e){return/^is[A-Z]/.test(e)});function Ul(o,e,a){if(!F.isObject(o))throw new TypeError("target must be an object");e=e||new FormData,a=F.toFlatObject(a,{metaTokens:!0,dots:!1,indexes:!1},!1,function(T,L){return!F.isUndefined(L[T])});const r=a.metaTokens,i=a.visitor||b,l=a.dots,u=a.indexes,d=a.Blob||typeof Blob<"u"&&Blob,f=a.maxDepth===void 0?100:a.maxDepth,g=d&&F.isSpecCompliantForm(e);if(!F.isFunction(i))throw new TypeError("visitor must be a function");function m(A){if(A===null)return"";if(F.isDate(A))return A.toISOString();if(F.isBoolean(A))return A.toString();if(!g&&F.isBlob(A))throw new Oe("Blob is not supported. Use a Buffer instead.");return F.isArrayBuffer(A)||F.isTypedArray(A)?g&&typeof Blob=="function"?new Blob([A]):Buffer.from(A):A}function b(A,T,L){let M=A;if(F.isReactNative(e)&&F.isReactNativeBlob(A))return e.append(gd(L,T,l),m(A)),!1;if(A&&!L&&typeof A=="object"){if(F.endsWith(T,"{}"))T=r?T:T.slice(0,-2),A=JSON.stringify(A);else if(F.isArray(A)&&u0(A)||(F.isFileList(A)||F.endsWith(T,"[]"))&&(M=F.toArray(A)))return T=Ap(T),M.forEach(function(D,U){!(F.isUndefined(D)||D===null)&&e.append(u===!0?gd([T],U,l):u===null?T:T+"[]",m(D))}),!1}return hd(A)?!0:(e.append(gd(L,T,l),m(A)),!1)}const v=[],S=Object.assign(d0,{defaultVisitor:b,convertValue:m,isVisitable:hd});function E(A,T,L=0){if(!F.isUndefined(A)){if(L>f)throw new Oe("Object is too deeply nested ("+L+" levels). Max depth: "+f,Oe.ERR_FORM_DATA_DEPTH_EXCEEDED);if(v.indexOf(A)!==-1)throw Error("Circular reference detected in "+T.join("."));v.push(A),F.forEach(A,function(R,D){(!(F.isUndefined(R)||R===null)&&i.call(e,R,F.isString(D)?D.trim():D,T,S))===!0&&E(R,T?T.concat(D):[D],L+1)}),v.pop()}}if(!F.isObject(o))throw new TypeError("data must be an object");return E(o),e}function xp(o){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"};return encodeURIComponent(o).replace(/[!'()~]|%20/g,function(r){return e[r]})}function pd(o,e){this._pairs=[],o&&Ul(o,this,e)}const Tp=pd.prototype;Tp.append=function(e,a){this._pairs.push([e,a])},Tp.toString=function(e){const a=e?function(r){return e.call(this,r,xp)}:xp;return this._pairs.map(function(i){return a(i[0])+"="+a(i[1])},"").join("&")};function f0(o){return encodeURIComponent(o).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Rp(o,e,a){if(!e)return o;const r=a&&a.encode||f0,i=F.isFunction(a)?{serialize:a}:a,l=i&&i.serialize;let u;if(l?u=l(e,i):u=F.isURLSearchParams(e)?e.toString():new pd(e,i).toString(r),u){const d=o.indexOf("#");d!==-1&&(o=o.slice(0,d)),o+=(o.indexOf("?")===-1?"?":"&")+u}return o}class kp{constructor(){this.handlers=[]}use(e,a,r){return this.handlers.push({fulfilled:e,rejected:a,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){F.forEach(this.handlers,function(r){r!==null&&e(r)})}}const md={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0},h0={isBrowser:!0,classes:{URLSearchParams:typeof URLSearchParams<"u"?URLSearchParams:pd,FormData:typeof FormData<"u"?FormData:null,Blob:typeof Blob<"u"?Blob:null},protocols:["http","https","file","blob","url","data"]},yd=typeof window<"u"&&typeof document<"u",bd=typeof navigator=="object"&&navigator||void 0,g0=yd&&(!bd||["ReactNative","NativeScript","NS"].indexOf(bd.product)<0),p0=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",m0=yd&&window.location.href||"http://localhost",yn={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:yd,hasStandardBrowserEnv:g0,hasStandardBrowserWebWorkerEnv:p0,navigator:bd,origin:m0},Symbol.toStringTag,{value:"Module"})),...h0};function y0(o,e){return Ul(o,new yn.classes.URLSearchParams,{visitor:function(a,r,i,l){return yn.isNode&&F.isBuffer(a)?(this.append(r,a.toString("base64")),!1):l.defaultVisitor.apply(this,arguments)},...e})}function b0(o){return F.matchAll(/\w+|\[(\w*)]/g,o).map(e=>e[0]==="[]"?"":e[1]||e[0])}function v0(o){const e={},a=Object.keys(o);let r;const i=a.length;let l;for(r=0;r=a.length;return u=!u&&F.isArray(i)?i.length:u,f?(F.hasOwnProp(i,u)?i[u]=F.isArray(i[u])?i[u].concat(r):[i[u],r]:i[u]=r,!d):((!F.hasOwnProp(i,u)||!F.isObject(i[u]))&&(i[u]=[]),e(a,r,i[u],l)&&F.isArray(i[u])&&(i[u]=v0(i[u])),!d)}if(F.isFormData(o)&&F.isFunction(o.entries)){const a={};return F.forEachEntry(o,(r,i)=>{e(b0(r),i,a,0)}),a}return null}const es=(o,e)=>o!=null&&F.hasOwnProp(o,e)?o[e]:void 0;function S0(o,e,a){if(F.isString(o))try{return(e||JSON.parse)(o),F.trim(o)}catch(r){if(r.name!=="SyntaxError")throw r}return(a||JSON.stringify)(o)}const ro={transitional:md,adapter:["xhr","http","fetch"],transformRequest:[function(e,a){const r=a.getContentType()||"",i=r.indexOf("application/json")>-1,l=F.isObject(e);if(l&&F.isHTMLForm(e)&&(e=new FormData(e)),F.isFormData(e))return i?JSON.stringify(Dp(e)):e;if(F.isArrayBuffer(e)||F.isBuffer(e)||F.isStream(e)||F.isFile(e)||F.isBlob(e)||F.isReadableStream(e))return e;if(F.isArrayBufferView(e))return e.buffer;if(F.isURLSearchParams(e))return a.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let d;if(l){const f=es(this,"formSerializer");if(r.indexOf("application/x-www-form-urlencoded")>-1)return y0(e,f).toString();if((d=F.isFileList(e))||r.indexOf("multipart/form-data")>-1){const g=es(this,"env"),m=g&&g.FormData;return Ul(d?{"files[]":e}:e,m&&new m,f)}}return l||i?(a.setContentType("application/json",!1),S0(e)):e}],transformResponse:[function(e){const a=es(this,"transitional")||ro.transitional,r=a&&a.forcedJSONParsing,i=es(this,"responseType"),l=i==="json";if(F.isResponse(e)||F.isReadableStream(e))return e;if(e&&F.isString(e)&&(r&&!i||l)){const d=!(a&&a.silentJSONParsing)&&l;try{return JSON.parse(e,es(this,"parseReviver"))}catch(f){if(d)throw f.name==="SyntaxError"?Oe.from(f,Oe.ERR_BAD_RESPONSE,this,null,es(this,"response")):f}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:yn.classes.FormData,Blob:yn.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};F.forEach(["delete","get","head","post","put","patch","query"],o=>{ro.headers[o]={}});function vd(o,e){const a=this||ro,r=e||a,i=Cn.from(r.headers);let l=r.data;return F.forEach(o,function(d){l=d.call(a,l,i.normalize(),e?e.status:void 0)}),i.normalize(),l}function Op(o){return!!(o&&o.__CANCEL__)}let io=class extends Oe{constructor(e,a,r){super(e??"canceled",Oe.ERR_CANCELED,a,r),this.name="CanceledError",this.__CANCEL__=!0}};function Lp(o,e,a){const r=a.config.validateStatus;!a.status||!r||r(a.status)?o(a):e(new Oe("Request failed with status code "+a.status,a.status>=400&&a.status<500?Oe.ERR_BAD_REQUEST:Oe.ERR_BAD_RESPONSE,a.config,a.request,a))}function w0(o){const e=/^([-+\w]{1,25}):(?:\/\/)?/.exec(o);return e&&e[1]||""}function C0(o,e){o=o||10;const a=new Array(o),r=new Array(o);let i=0,l=0,u;return e=e!==void 0?e:1e3,function(f){const g=Date.now(),m=r[l];u||(u=g),a[i]=f,r[i]=g;let b=l,v=0;for(;b!==i;)v+=a[b++],b=b%o;if(i=(i+1)%o,i===l&&(l=(l+1)%o),g-u{a=m,i=null,l&&(clearTimeout(l),l=null),o(...g)};return[(...g)=>{const m=Date.now(),b=m-a;b>=r?u(g,m):(i=g,l||(l=setTimeout(()=>{l=null,u(i)},r-b)))},()=>i&&u(i)]}const Bl=(o,e,a=3)=>{let r=0;const i=C0(50,250);return E0(l=>{if(!l||typeof l.loaded!="number")return;const u=l.loaded,d=l.lengthComputable?l.total:void 0,f=d!=null?Math.min(u,d):u,g=Math.max(0,f-r),m=i(g);r=Math.max(r,f);const b={loaded:f,total:d,progress:d?f/d:void 0,bytes:g,rate:m||void 0,estimated:m&&d?(d-f)/m:void 0,event:l,lengthComputable:d!=null,[e?"download":"upload"]:!0};o(b)},a)},Mp=(o,e)=>{const a=o!=null;return[r=>e[0]({lengthComputable:a,total:o,loaded:r}),e[1]]},$p=o=>(...e)=>F.asap(()=>o(...e)),_0=yn.hasStandardBrowserEnv?((o,e)=>a=>(a=new URL(a,yn.origin),o.protocol===a.protocol&&o.host===a.host&&(e||o.port===a.port)))(new URL(yn.origin),yn.navigator&&/(msie|trident)/i.test(yn.navigator.userAgent)):()=>!0,A0=yn.hasStandardBrowserEnv?{write(o,e,a,r,i,l,u){if(typeof document>"u")return;const d=[`${o}=${encodeURIComponent(e)}`];F.isNumber(a)&&d.push(`expires=${new Date(a).toUTCString()}`),F.isString(r)&&d.push(`path=${r}`),F.isString(i)&&d.push(`domain=${i}`),l===!0&&d.push("secure"),F.isString(u)&&d.push(`SameSite=${u}`),document.cookie=d.join("; ")},read(o){if(typeof document>"u")return null;const e=document.cookie.split(";");for(let a=0;ao instanceof Cn?{...o}:o;function fi(o,e){e=e||{};const a=Object.create(null);Object.defineProperty(a,"hasOwnProperty",{__proto__:null,value:Object.prototype.hasOwnProperty,enumerable:!1,writable:!0,configurable:!0});function r(g,m,b,v){return F.isPlainObject(g)&&F.isPlainObject(m)?F.merge.call({caseless:v},g,m):F.isPlainObject(m)?F.merge({},m):F.isArray(m)?m.slice():m}function i(g,m,b,v){if(F.isUndefined(m)){if(!F.isUndefined(g))return r(void 0,g,b,v)}else return r(g,m,b,v)}function l(g,m){if(!F.isUndefined(m))return r(void 0,m)}function u(g,m){if(F.isUndefined(m)){if(!F.isUndefined(g))return r(void 0,g)}else return r(void 0,m)}function d(g,m,b){if(F.hasOwnProp(e,b))return r(g,m);if(F.hasOwnProp(o,b))return r(void 0,g)}const f={url:l,method:l,data:l,baseURL:u,transformRequest:u,transformResponse:u,paramsSerializer:u,timeout:u,timeoutMessage:u,withCredentials:u,withXSRFToken:u,adapter:u,responseType:u,xsrfCookieName:u,xsrfHeaderName:u,onUploadProgress:u,onDownloadProgress:u,decompress:u,maxContentLength:u,maxBodyLength:u,beforeRedirect:u,transport:u,httpAgent:u,httpsAgent:u,cancelToken:u,socketPath:u,allowedSocketPaths:u,responseEncoding:u,validateStatus:d,headers:(g,m,b)=>i(Ip(g),Ip(m),b,!0)};return F.forEach(Object.keys({...o,...e}),function(m){if(m==="__proto__"||m==="constructor"||m==="prototype")return;const b=F.hasOwnProp(f,m)?f[m]:i,v=F.hasOwnProp(o,m)?o[m]:void 0,S=F.hasOwnProp(e,m)?e[m]:void 0,E=b(v,S,m);F.isUndefined(E)&&b!==d||(a[m]=E)}),a}const R0=["content-type","content-length"];function k0(o,e,a){if(a!=="content-only"){o.set(e);return}Object.entries(e).forEach(([r,i])=>{R0.includes(r.toLowerCase())&&o.set(r,i)})}const D0=o=>encodeURIComponent(o).replace(/%([0-9A-F]{2})/gi,(e,a)=>String.fromCharCode(parseInt(a,16))),Hp=o=>{const e=fi({},o),a=v=>F.hasOwnProp(e,v)?e[v]:void 0,r=a("data");let i=a("withXSRFToken");const l=a("xsrfHeaderName"),u=a("xsrfCookieName");let d=a("headers");const f=a("auth"),g=a("baseURL"),m=a("allowAbsoluteUrls"),b=a("url");if(e.headers=d=Cn.from(d),e.url=Rp(Np(g,b,m),o.params,o.paramsSerializer),f&&d.set("Authorization","Basic "+btoa((f.username||"")+":"+(f.password?D0(f.password):""))),F.isFormData(r)&&(yn.hasStandardBrowserEnv||yn.hasStandardBrowserWebWorkerEnv?d.setContentType(void 0):F.isFunction(r.getHeaders)&&k0(d,r.getHeaders(),a("formDataHeaderPolicy"))),yn.hasStandardBrowserEnv&&(F.isFunction(i)&&(i=i(e)),i===!0||i==null&&_0(e.url))){const S=l&&u&&A0.read(u);S&&d.set(l,S)}return e},O0=typeof XMLHttpRequest<"u"&&function(o){return new Promise(function(a,r){const i=Hp(o);let l=i.data;const u=Cn.from(i.headers).normalize();let{responseType:d,onUploadProgress:f,onDownloadProgress:g}=i,m,b,v,S,E;function A(){S&&S(),E&&E(),i.cancelToken&&i.cancelToken.unsubscribe(m),i.signal&&i.signal.removeEventListener("abort",m)}let T=new XMLHttpRequest;T.open(i.method.toUpperCase(),i.url,!0),T.timeout=i.timeout;function L(){if(!T)return;const R=Cn.from("getAllResponseHeaders"in T&&T.getAllResponseHeaders()),U={data:!d||d==="text"||d==="json"?T.responseText:T.response,status:T.status,statusText:T.statusText,headers:R,config:o,request:T};Lp(function(P){a(P),A()},function(P){r(P),A()},U),T=null}"onloadend"in T?T.onloadend=L:T.onreadystatechange=function(){!T||T.readyState!==4||T.status===0&&!(T.responseURL&&T.responseURL.startsWith("file:"))||setTimeout(L)},T.onabort=function(){T&&(r(new Oe("Request aborted",Oe.ECONNABORTED,o,T)),A(),T=null)},T.onerror=function(D){const U=D&&D.message?D.message:"Network Error",j=new Oe(U,Oe.ERR_NETWORK,o,T);j.event=D||null,r(j),A(),T=null},T.ontimeout=function(){let D=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const U=i.transitional||md;i.timeoutErrorMessage&&(D=i.timeoutErrorMessage),r(new Oe(D,U.clarifyTimeoutError?Oe.ETIMEDOUT:Oe.ECONNABORTED,o,T)),A(),T=null},l===void 0&&u.setContentType(null),"setRequestHeader"in T&&F.forEach(Ep(u),function(D,U){T.setRequestHeader(U,D)}),F.isUndefined(i.withCredentials)||(T.withCredentials=!!i.withCredentials),d&&d!=="json"&&(T.responseType=i.responseType),g&&([v,E]=Bl(g,!0),T.addEventListener("progress",v)),f&&T.upload&&([b,S]=Bl(f),T.upload.addEventListener("progress",b),T.upload.addEventListener("loadend",S)),(i.cancelToken||i.signal)&&(m=R=>{T&&(r(!R||R.type?new io(null,o,T):R),T.abort(),A(),T=null)},i.cancelToken&&i.cancelToken.subscribe(m),i.signal&&(i.signal.aborted?m():i.signal.addEventListener("abort",m)));const M=w0(i.url);if(M&&!yn.protocols.includes(M)){r(new Oe("Unsupported protocol "+M+":",Oe.ERR_BAD_REQUEST,o));return}T.send(l||null)})},L0=(o,e)=>{if(o=o?o.filter(Boolean):[],!e&&!o.length)return;const a=new AbortController;let r=!1;const i=function(f){if(!r){r=!0,u();const g=f instanceof Error?f:this.reason;a.abort(g instanceof Oe?g:new io(g instanceof Error?g.message:g))}};let l=e&&setTimeout(()=>{l=null,i(new Oe(`timeout of ${e}ms exceeded`,Oe.ETIMEDOUT))},e);const u=()=>{o&&(l&&clearTimeout(l),l=null,o.forEach(f=>{f.unsubscribe?f.unsubscribe(i):f.removeEventListener("abort",i)}),o=null)};o.forEach(f=>f.addEventListener("abort",i));const{signal:d}=a;return d.unsubscribe=()=>F.asap(u),d},M0=function*(o,e){let a=o.byteLength;if(a{const i=$0(o,e);let l=0,u,d=f=>{u||(u=!0,r&&r(f))};return new ReadableStream({async pull(f){try{const{done:g,value:m}=await i.next();if(g){d(),f.close();return}let b=m.byteLength;if(a){let v=l+=b;a(v)}f.enqueue(new Uint8Array(m))}catch(g){throw d(g),g}},cancel(f){return d(f),i.return()}},{highWaterMark:2})};function I0(o){if(!o||typeof o!="string"||!o.startsWith("data:"))return 0;const e=o.indexOf(",");if(e<0)return 0;const a=o.slice(5,e),r=o.slice(e+1);if(/;base64/i.test(a)){let u=r.length;const d=r.length;for(let S=0;S=48&&E<=57||E>=65&&E<=70||E>=97&&E<=102)&&(A>=48&&A<=57||A>=65&&A<=70||A>=97&&A<=102)&&(u-=2,S+=2)}let f=0,g=d-1;const m=S=>S>=2&&r.charCodeAt(S-2)===37&&r.charCodeAt(S-1)===51&&(r.charCodeAt(S)===68||r.charCodeAt(S)===100);g>=0&&(r.charCodeAt(g)===61?(f++,g--):m(g)&&(f++,g-=3)),f===1&&g>=0&&(r.charCodeAt(g)===61||m(g))&&f++;const v=Math.floor(u/4)*3-(f||0);return v>0?v:0}if(typeof Buffer<"u"&&typeof Buffer.byteLength=="function")return Buffer.byteLength(r,"utf8");let l=0;for(let u=0,d=r.length;u=55296&&f<=56319&&u+1=56320&&g<=57343?(l+=4,u++):l+=3}else l+=3}return l}const Sd="1.16.1",jp=64*1024,{isFunction:Pl}=F,Up=(o,...e)=>{try{return!!o(...e)}catch{return!1}},H0=o=>{const e=F.global!==void 0&&F.global!==null?F.global:globalThis,{ReadableStream:a,TextEncoder:r}=e;o=F.merge.call({skipUndefined:!0},{Request:e.Request,Response:e.Response},o);const{fetch:i,Request:l,Response:u}=o,d=i?Pl(i):typeof fetch=="function",f=Pl(l),g=Pl(u);if(!d)return!1;const m=d&&Pl(a),b=d&&(typeof r=="function"?(L=>M=>L.encode(M))(new r):async L=>new Uint8Array(await new l(L).arrayBuffer())),v=f&&m&&Up(()=>{let L=!1;const M=new l(yn.origin,{body:new a,method:"POST",get duplex(){return L=!0,"half"}}),R=M.headers.has("Content-Type");return M.body!=null&&M.body.cancel(),L&&!R}),S=g&&m&&Up(()=>F.isReadableStream(new u("").body)),E={stream:S&&(L=>L.body)};d&&["text","arrayBuffer","blob","formData","stream"].forEach(L=>{!E[L]&&(E[L]=(M,R)=>{let D=M&&M[L];if(D)return D.call(M);throw new Oe(`Response type '${L}' is not supported`,Oe.ERR_NOT_SUPPORT,R)})});const A=async L=>{if(L==null)return 0;if(F.isBlob(L))return L.size;if(F.isSpecCompliantForm(L))return(await new l(yn.origin,{method:"POST",body:L}).arrayBuffer()).byteLength;if(F.isArrayBufferView(L)||F.isArrayBuffer(L))return L.byteLength;if(F.isURLSearchParams(L)&&(L=L+""),F.isString(L))return(await b(L)).byteLength},T=async(L,M)=>{const R=F.toFiniteNumber(L.getContentLength());return R??A(M)};return async L=>{let{url:M,method:R,data:D,signal:U,cancelToken:j,timeout:P,onDownloadProgress:X,onUploadProgress:ge,responseType:Ee,headers:Ce,withCredentials:$e="same-origin",fetchOptions:Pe,maxContentLength:Xe,maxBodyLength:ht}=Hp(L);const Q=F.isNumber(Xe)&&Xe>-1,fe=F.isNumber(ht)&&ht>-1;let ye=i||fetch;Ee=Ee?(Ee+"").toLowerCase():"text";let te=L0([U,j&&j.toAbortSignal()],P),he=null;const x=te&&te.unsubscribe&&(()=>{te.unsubscribe()});let K;try{if(Q&&typeof M=="string"&&M.startsWith("data:")&&I0(M)>Xe)throw new Oe("maxContentLength size of "+Xe+" exceeded",Oe.ERR_BAD_RESPONSE,L,he);if(fe&&R!=="get"&&R!=="head"){const Se=await T(Ce,D);if(typeof Se=="number"&&isFinite(Se)&&Se>ht)throw new Oe("Request body larger than maxBodyLength limit",Oe.ERR_BAD_REQUEST,L,he)}if(ge&&v&&R!=="get"&&R!=="head"&&(K=await T(Ce,D))!==0){let Se=new l(M,{method:"POST",body:D,duplex:"half"}),He;if(F.isFormData(D)&&(He=Se.headers.get("content-type"))&&Ce.setContentType(He),Se.body){const[Ae,Et]=Mp(K,Bl($p(ge)));D=zp(Se.body,jp,Ae,Et)}}F.isString($e)||($e=$e?"include":"omit");const re=f&&"credentials"in l.prototype;if(F.isFormData(D)){const Se=Ce.getContentType();Se&&/^multipart\/form-data/i.test(Se)&&!/boundary=/i.test(Se)&&Ce.delete("content-type")}Ce.set("User-Agent","axios/"+Sd,!1);const de={...Pe,signal:te,method:R.toUpperCase(),headers:Ep(Ce.normalize()),body:D,duplex:"half",credentials:re?$e:void 0};he=f&&new l(M,de);let ie=await(f?ye(he,Pe):ye(M,de));if(Q){const Se=F.toFiniteNumber(ie.headers.get("content-length"));if(Se!=null&&Se>Xe)throw new Oe("maxContentLength size of "+Xe+" exceeded",Oe.ERR_BAD_RESPONSE,L,he)}const me=S&&(Ee==="stream"||Ee==="response");if(S&&ie.body&&(X||Q||me&&x)){const Se={};["status","statusText","headers"].forEach(ft=>{Se[ft]=ie[ft]});const He=F.toFiniteNumber(ie.headers.get("content-length")),[Ae,Et]=X&&Mp(He,Bl($p(X),!0))||[];let kt=0;const _t=ft=>{if(Q&&(kt=ft,kt>Xe))throw new Oe("maxContentLength size of "+Xe+" exceeded",Oe.ERR_BAD_RESPONSE,L,he);Ae&&Ae(ft)};ie=new u(zp(ie.body,jp,_t,()=>{Et&&Et(),x&&x()}),Se)}Ee=Ee||"text";let Ne=await E[F.findKey(E,Ee)||"text"](ie,L);if(Q&&!S&&!me){let Se;if(Ne!=null&&(typeof Ne.byteLength=="number"?Se=Ne.byteLength:typeof Ne.size=="number"?Se=Ne.size:typeof Ne=="string"&&(Se=typeof r=="function"?new r().encode(Ne).byteLength:Ne.length)),typeof Se=="number"&&Se>Xe)throw new Oe("maxContentLength size of "+Xe+" exceeded",Oe.ERR_BAD_RESPONSE,L,he)}return!me&&x&&x(),await new Promise((Se,He)=>{Lp(Se,He,{data:Ne,headers:Cn.from(ie.headers),status:ie.status,statusText:ie.statusText,config:L,request:he})})}catch(re){if(x&&x(),te&&te.aborted&&te.reason instanceof Oe){const de=te.reason;throw de.config=L,he&&(de.request=he),re!==de&&(de.cause=re),de}throw re&&re.name==="TypeError"&&/Load failed|fetch/i.test(re.message)?Object.assign(new Oe("Network Error",Oe.ERR_NETWORK,L,he,re&&re.response),{cause:re.cause||re}):Oe.from(re,re&&re.code,L,he,re&&re.response)}}},z0=new Map,Bp=o=>{let e=o&&o.env||{};const{fetch:a,Request:r,Response:i}=e,l=[r,i,a];let u=l.length,d=u,f,g,m=z0;for(;d--;)f=l[d],g=m.get(f),g===void 0&&m.set(f,g=d?new Map:H0(e)),m=g;return g};Bp();const wd={http:c0,xhr:O0,fetch:{get:Bp}};F.forEach(wd,(o,e)=>{if(o){try{Object.defineProperty(o,"name",{__proto__:null,value:e})}catch{}Object.defineProperty(o,"adapterName",{__proto__:null,value:e})}});const Pp=o=>`- ${o}`,j0=o=>F.isFunction(o)||o===null||o===!1;function U0(o,e){o=F.isArray(o)?o:[o];const{length:a}=o;let r,i;const l={};for(let u=0;u`adapter ${f} `+(g===!1?"is not supported by the environment":"is not available in the build"));let d=a?u.length>1?`since : -`+u.map(Pp).join(` -`):" "+Pp(u[0]):"as no adapter specified";throw new Oe("There is no suitable adapter to dispatch the request "+d,"ERR_NOT_SUPPORT")}return i}const qp={getAdapter:U0,adapters:wd};function Cd(o){if(o.cancelToken&&o.cancelToken.throwIfRequested(),o.signal&&o.signal.aborted)throw new io(null,o)}function Gp(o){return Cd(o),o.headers=Cn.from(o.headers),o.data=vd.call(o,o.transformRequest),["post","put","patch"].indexOf(o.method)!==-1&&o.headers.setContentType("application/x-www-form-urlencoded",!1),qp.getAdapter(o.adapter||ro.adapter,o)(o).then(function(r){Cd(o),o.response=r;try{r.data=vd.call(o,o.transformResponse,r)}finally{delete o.response}return r.headers=Cn.from(r.headers),r},function(r){if(!Op(r)&&(Cd(o),r&&r.response)){o.response=r.response;try{r.response.data=vd.call(o,o.transformResponse,r.response)}finally{delete o.response}r.response.headers=Cn.from(r.response.headers)}return Promise.reject(r)})}const ql={};["object","boolean","number","function","string","symbol"].forEach((o,e)=>{ql[o]=function(r){return typeof r===o||"a"+(e<1?"n ":" ")+o}});const Vp={};ql.transitional=function(e,a,r){function i(l,u){return"[Axios v"+Sd+"] Transitional option '"+l+"'"+u+(r?". "+r:"")}return(l,u,d)=>{if(e===!1)throw new Oe(i(u," has been removed"+(a?" in "+a:"")),Oe.ERR_DEPRECATED);return a&&!Vp[u]&&(Vp[u]=!0,console.warn(i(u," has been deprecated since v"+a+" and will be removed in the near future"))),e?e(l,u,d):!0}},ql.spelling=function(e){return(a,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};function B0(o,e,a){if(typeof o!="object")throw new Oe("options must be an object",Oe.ERR_BAD_OPTION_VALUE);const r=Object.keys(o);let i=r.length;for(;i-- >0;){const l=r[i],u=Object.prototype.hasOwnProperty.call(e,l)?e[l]:void 0;if(u){const d=o[l],f=d===void 0||u(d,l,o);if(f!==!0)throw new Oe("option "+l+" must be "+f,Oe.ERR_BAD_OPTION_VALUE);continue}if(a!==!0)throw new Oe("Unknown option "+l,Oe.ERR_BAD_OPTION)}}const Gl={assertOptions:B0,validators:ql},Jn=Gl.validators;let hi=class{constructor(e){this.defaults=e||{},this.interceptors={request:new kp,response:new kp}}async request(e,a){try{return await this._request(e,a)}catch(r){if(r instanceof Error){let i={};Error.captureStackTrace?Error.captureStackTrace(i):i=new Error;const l=(()=>{if(!i.stack)return"";const u=i.stack.indexOf(` +`+c.stack}}var qt=Object.prototype.hasOwnProperty,Lt=o.unstable_scheduleCallback,_n=o.unstable_cancelCallback,hn=o.unstable_shouldYield,Ba=o.unstable_requestPaint,Jt=o.unstable_now,Dr=o.unstable_getCurrentPriorityLevel,tr=o.unstable_ImmediatePriority,An=o.unstable_UserBlockingPriority,sn=o.unstable_NormalPriority,tt=o.unstable_LowPriority,na=o.unstable_IdlePriority,kn=o.log,nr=o.unstable_setDisableYieldValue,_a=null,on=null;function Dn(t){if(typeof kn=="function"&&nr(t),on&&typeof on.setStrictMode=="function")try{on.setStrictMode(_a,t)}catch{}}var q=Math.clz32?Math.clz32:Z,ie=Math.log,oe=Math.LN2;function Z(t){return t>>>=0,t===0?32:31-(ie(t)/oe|0)|0}var be=256,me=262144,Te=4194304;function xe(t){var a=t&42;if(a!==0)return a;switch(t&-t){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return t&261888;case 262144:case 524288:case 1048576:case 2097152:return t&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return t&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return t}}function je(t,a,s){var c=t.pendingLanes;if(c===0)return 0;var h=0,p=t.suspendedLanes,C=t.pingedLanes;t=t.warmLanes;var R=c&134217727;return R!==0?(c=R&~p,c!==0?h=xe(c):(C&=R,C!==0?h=xe(C):s||(s=R&~t,s!==0&&(h=xe(s))))):(R=c&~p,R!==0?h=xe(R):C!==0?h=xe(C):s||(s=c&~t,s!==0&&(h=xe(s)))),h===0?0:a!==0&&a!==h&&(a&p)===0&&(p=h&-h,s=a&-a,p>=s||p===32&&(s&4194048)!==0)?a:h}function ze(t,a){return(t.pendingLanes&~(t.suspendedLanes&~t.pingedLanes)&a)===0}function $e(t,a){switch(t){case 1:case 2:case 4:case 8:case 64:return a+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function De(){var t=Te;return Te<<=1,(Te&62914560)===0&&(Te=4194304),t}function Ye(t){for(var a=[],s=0;31>s;s++)a.push(t);return a}function Ke(t,a){t.pendingLanes|=a,a!==268435456&&(t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0)}function Ae(t,a,s,c,h,p){var C=t.pendingLanes;t.pendingLanes=s,t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0,t.expiredLanes&=s,t.entangledLanes&=s,t.errorRecoveryDisabledLanes&=s,t.shellSuspendCounter=0;var R=t.entanglements,U=t.expirationTimes,Y=t.hiddenUpdates;for(s=C&~s;0"u")return null;try{return t.activeElement||t.body}catch{return t.body}}var Cf=/[\n"\\]/g;function Hn(t){return t.replace(Cf,function(a){return"\\"+a.charCodeAt(0).toString(16)+" "})}function ps(t,a,s,c,h,p,C,R){t.name="",C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"?t.type=C:t.removeAttribute("type"),a!=null?C==="number"?(a===0&&t.value===""||t.value!=a)&&(t.value=""+Tn(a)):t.value!==""+Tn(a)&&(t.value=""+Tn(a)):C!=="submit"&&C!=="reset"||t.removeAttribute("value"),a!=null?rr(t,C,Tn(a)):s!=null?rr(t,C,Tn(s)):c!=null&&t.removeAttribute("value"),h==null&&p!=null&&(t.defaultChecked=!!p),h!=null&&(t.checked=h&&typeof h!="function"&&typeof h!="symbol"),R!=null&&typeof R!="function"&&typeof R!="symbol"&&typeof R!="boolean"?t.name=""+Tn(R):t.removeAttribute("name")}function wi(t,a,s,c,h,p,C,R){if(p!=null&&typeof p!="function"&&typeof p!="symbol"&&typeof p!="boolean"&&(t.type=p),a!=null||s!=null){if(!(p!=="submit"&&p!=="reset"||a!=null)){$o(t);return}s=s!=null?""+Tn(s):"",a=a!=null?""+Tn(a):s,R||a===t.value||(t.value=a),t.defaultValue=a}c=c??h,c=typeof c!="function"&&typeof c!="symbol"&&!!c,t.checked=R?t.checked:!!c,t.defaultChecked=!!c,C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"&&(t.name=C),$o(t)}function rr(t,a,s){a==="number"&&Nr(t.ownerDocument)===t||t.defaultValue===""+s||(t.defaultValue=""+s)}function Ir(t,a,s,c){if(t=t.options,a){a={};for(var h=0;h"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),jo=!1;if(Ta)try{var Ei={};Object.defineProperty(Ei,"passive",{get:function(){jo=!0}}),window.addEventListener("test",Ei,Ei),window.removeEventListener("test",Ei,Ei)}catch{jo=!1}var Ga=null,Uo=null,ys=null;function Nc(){if(ys)return ys;var t,a=Uo,s=a.length,c,h="value"in Ga?Ga.value:Ga.textContent,p=h.length;for(t=0;t=te),Fe=" ",lt=!1;function pt(t,a){switch(t){case"keyup":return L.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function jt(t){return t=t.detail,typeof t=="object"&&"data"in t?t.data:null}var ka=!1;function Uf(t,a){switch(t){case"compositionend":return jt(a);case"keypress":return a.which!==32?null:(lt=!0,Fe);case"textInput":return t=a.data,t===Fe&<?null:t;default:return null}}function Pc(t,a){if(ka)return t==="compositionend"||!N&&pt(t,a)?(t=Nc(),ys=Uo=Ga=null,ka=!1,t):null;switch(t){case"paste":return null;case"keypress":if(!(a.ctrlKey||a.altKey||a.metaKey)||a.ctrlKey&&a.altKey){if(a.char&&1=a)return{node:s,offset:a-t};t=c}e:{for(;s;){if(s.nextSibling){s=s.nextSibling;break e}s=s.parentNode}s=void 0}s=Ey(s)}}function Ay(t,a){return t&&a?t===a?!0:t&&t.nodeType===3?!1:a&&a.nodeType===3?Ay(t,a.parentNode):"contains"in t?t.contains(a):t.compareDocumentPosition?!!(t.compareDocumentPosition(a)&16):!1:!1}function xy(t){t=t!=null&&t.ownerDocument!=null&&t.ownerDocument.defaultView!=null?t.ownerDocument.defaultView:window;for(var a=Nr(t.document);a instanceof t.HTMLIFrameElement;){try{var s=typeof a.contentWindow.location.href=="string"}catch{s=!1}if(s)t=a.contentWindow;else break;a=Nr(t.document)}return a}function Vf(t){var a=t&&t.nodeName&&t.nodeName.toLowerCase();return a&&(a==="input"&&(t.type==="text"||t.type==="search"||t.type==="tel"||t.type==="url"||t.type==="password")||a==="textarea"||t.contentEditable==="true")}var KA=Ta&&"documentMode"in document&&11>=document.documentMode,ws=null,Ff=null,Xo=null,Kf=!1;function Ty(t,a,s){var c=s.window===s?s.document:s.nodeType===9?s:s.ownerDocument;Kf||ws==null||ws!==Nr(c)||(c=ws,"selectionStart"in c&&Vf(c)?c={start:c.selectionStart,end:c.selectionEnd}:(c=(c.ownerDocument&&c.ownerDocument.defaultView||window).getSelection(),c={anchorNode:c.anchorNode,anchorOffset:c.anchorOffset,focusNode:c.focusNode,focusOffset:c.focusOffset}),Xo&&Yo(Xo,c)||(Xo=c,c=$u(Ff,"onSelect"),0>=C,h-=C,Va=1<<32-q(a)+h|s<Ze?(it=Ie,Ie=null):it=Ie.sibling;var yt=J(F,Ie,W[Ze],se);if(yt===null){Ie===null&&(Ie=it);break}t&&Ie&&yt.alternate===null&&a(F,Ie),G=p(yt,G,Ze),mt===null?Ge=yt:mt.sibling=yt,mt=yt,Ie=it}if(Ze===W.length)return s(F,Ie),ct&&lr(F,Ze),Ge;if(Ie===null){for(;ZeZe?(it=Ie,Ie=null):it=Ie.sibling;var li=J(F,Ie,yt.value,se);if(li===null){Ie===null&&(Ie=it);break}t&&Ie&&li.alternate===null&&a(F,Ie),G=p(li,G,Ze),mt===null?Ge=li:mt.sibling=li,mt=li,Ie=it}if(yt.done)return s(F,Ie),ct&&lr(F,Ze),Ge;if(Ie===null){for(;!yt.done;Ze++,yt=W.next())yt=ce(F,yt.value,se),yt!==null&&(G=p(yt,G,Ze),mt===null?Ge=yt:mt.sibling=yt,mt=yt);return ct&&lr(F,Ze),Ge}for(Ie=c(Ie);!yt.done;Ze++,yt=W.next())yt=ee(Ie,F,Ze,yt.value,se),yt!==null&&(t&&yt.alternate!==null&&Ie.delete(yt.key===null?Ze:yt.key),G=p(yt,G,Ze),mt===null?Ge=yt:mt.sibling=yt,mt=yt);return t&&Ie.forEach(function(hT){return a(F,hT)}),ct&&lr(F,Ze),Ge}function Rt(F,G,W,se){if(typeof W=="object"&&W!==null&&W.type===x&&W.key===null&&(W=W.props.children),typeof W=="object"&&W!==null){switch(W.$$typeof){case S:e:{for(var Ge=W.key;G!==null;){if(G.key===Ge){if(Ge=W.type,Ge===x){if(G.tag===7){s(F,G.sibling),se=h(G,W.props.children),se.return=F,F=se;break e}}else if(G.elementType===Ge||typeof Ge=="object"&&Ge!==null&&Ge.$$typeof===X&&ji(Ge)===G.type){s(F,G.sibling),se=h(G,W.props),nl(se,W),se.return=F,F=se;break e}s(F,G);break}else a(F,G);G=G.sibling}W.type===x?(se=$i(W.props.children,F.mode,se,W.key),se.return=F,F=se):(se=Jc(W.type,W.key,W.props,null,F.mode,se),nl(se,W),se.return=F,F=se)}return C(F);case _:e:{for(Ge=W.key;G!==null;){if(G.key===Ge)if(G.tag===4&&G.stateNode.containerInfo===W.containerInfo&&G.stateNode.implementation===W.implementation){s(F,G.sibling),se=h(G,W.children||[]),se.return=F,F=se;break e}else{s(F,G);break}else a(F,G);G=G.sibling}se=eh(W,F.mode,se),se.return=F,F=se}return C(F);case X:return W=ji(W),Rt(F,G,W,se)}if(gt(W))return Le(F,G,W,se);if(Me(W)){if(Ge=Me(W),typeof Ge!="function")throw Error(r(150));return W=Ge.call(W),Ve(F,G,W,se)}if(typeof W.then=="function")return Rt(F,G,ru(W),se);if(W.$$typeof===T)return Rt(F,G,eu(F,W),se);iu(F,W)}return typeof W=="string"&&W!==""||typeof W=="number"||typeof W=="bigint"?(W=""+W,G!==null&&G.tag===6?(s(F,G.sibling),se=h(G,W),se.return=F,F=se):(s(F,G),se=Zf(W,F.mode,se),se.return=F,F=se),C(F)):s(F,G)}return function(F,G,W,se){try{tl=0;var Ge=Rt(F,G,W,se);return Ls=null,Ge}catch(Ie){if(Ie===Os||Ie===nu)throw Ie;var mt=Wn(29,Ie,null,F.mode);return mt.lanes=se,mt.return=F,mt}}}var Bi=Xy(!0),Jy=Xy(!1),Vr=!1;function fh(t){t.updateQueue={baseState:t.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function hh(t,a){t=t.updateQueue,a.updateQueue===t&&(a.updateQueue={baseState:t.baseState,firstBaseUpdate:t.firstBaseUpdate,lastBaseUpdate:t.lastBaseUpdate,shared:t.shared,callbacks:null})}function Fr(t){return{lane:t,tag:0,payload:null,callback:null,next:null}}function Kr(t,a,s){var c=t.updateQueue;if(c===null)return null;if(c=c.shared,(St&2)!==0){var h=c.pending;return h===null?a.next=a:(a.next=h.next,h.next=a),c.pending=a,a=Xc(t),$y(t,null,s),a}return Yc(t,c,a,s),Xc(t)}function al(t,a,s){if(a=a.updateQueue,a!==null&&(a=a.shared,(s&4194048)!==0)){var c=a.lanes;c&=t.pendingLanes,s|=c,a.lanes=s,Ue(t,s)}}function gh(t,a){var s=t.updateQueue,c=t.alternate;if(c!==null&&(c=c.updateQueue,s===c)){var h=null,p=null;if(s=s.firstBaseUpdate,s!==null){do{var C={lane:s.lane,tag:s.tag,payload:s.payload,callback:null,next:null};p===null?h=p=C:p=p.next=C,s=s.next}while(s!==null);p===null?h=p=a:p=p.next=a}else h=p=a;s={baseState:c.baseState,firstBaseUpdate:h,lastBaseUpdate:p,shared:c.shared,callbacks:c.callbacks},t.updateQueue=s;return}t=s.lastBaseUpdate,t===null?s.firstBaseUpdate=a:t.next=a,s.lastBaseUpdate=a}var ph=!1;function rl(){if(ph){var t=Ds;if(t!==null)throw t}}function il(t,a,s,c){ph=!1;var h=t.updateQueue;Vr=!1;var p=h.firstBaseUpdate,C=h.lastBaseUpdate,R=h.shared.pending;if(R!==null){h.shared.pending=null;var U=R,Y=U.next;U.next=null,C===null?p=Y:C.next=Y,C=U;var ne=t.alternate;ne!==null&&(ne=ne.updateQueue,R=ne.lastBaseUpdate,R!==C&&(R===null?ne.firstBaseUpdate=Y:R.next=Y,ne.lastBaseUpdate=U))}if(p!==null){var ce=h.baseState;C=0,ne=Y=U=null,R=p;do{var J=R.lane&-536870913,ee=J!==R.lane;if(ee?(rt&J)===J:(c&J)===J){J!==0&&J===ks&&(ph=!0),ne!==null&&(ne=ne.next={lane:0,tag:R.tag,payload:R.payload,callback:null,next:null});e:{var Le=t,Ve=R;J=a;var Rt=s;switch(Ve.tag){case 1:if(Le=Ve.payload,typeof Le=="function"){ce=Le.call(Rt,ce,J);break e}ce=Le;break e;case 3:Le.flags=Le.flags&-65537|128;case 0:if(Le=Ve.payload,J=typeof Le=="function"?Le.call(Rt,ce,J):Le,J==null)break e;ce=b({},ce,J);break e;case 2:Vr=!0}}J=R.callback,J!==null&&(t.flags|=64,ee&&(t.flags|=8192),ee=h.callbacks,ee===null?h.callbacks=[J]:ee.push(J))}else ee={lane:J,tag:R.tag,payload:R.payload,callback:R.callback,next:null},ne===null?(Y=ne=ee,U=ce):ne=ne.next=ee,C|=J;if(R=R.next,R===null){if(R=h.shared.pending,R===null)break;ee=R,R=ee.next,ee.next=null,h.lastBaseUpdate=ee,h.shared.pending=null}}while(!0);ne===null&&(U=ce),h.baseState=U,h.firstBaseUpdate=Y,h.lastBaseUpdate=ne,p===null&&(h.shared.lanes=0),Qr|=C,t.lanes=C,t.memoizedState=ce}}function Qy(t,a){if(typeof t!="function")throw Error(r(191,t));t.call(a)}function Zy(t,a){var s=t.callbacks;if(s!==null)for(t.callbacks=null,t=0;tp?p:8;var C=Q.T,R={};Q.T=R,$h(t,!1,a,s);try{var U=h(),Y=Q.S;if(Y!==null&&Y(R,U),U!==null&&typeof U=="object"&&typeof U.then=="function"){var ne=nx(U,c);ll(t,a,ne,Zn(t))}else ll(t,a,c,Zn(t))}catch(ce){ll(t,a,{then:function(){},status:"rejected",reason:ce},Zn())}finally{fe.p=p,C!==null&&R.types!==null&&(C.types=R.types),Q.T=C}}function lx(){}function Lh(t,a,s,c){if(t.tag!==5)throw Error(r(476));var h=Ob(t).queue;Db(t,h,a,ve,s===null?lx:function(){return Lb(t),s(c)})}function Ob(t){var a=t.memoizedState;if(a!==null)return a;a={memoizedState:ve,baseState:ve,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:fr,lastRenderedState:ve},next:null};var s={};return a.next={memoizedState:s,baseState:s,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:fr,lastRenderedState:s},next:null},t.memoizedState=a,t=t.alternate,t!==null&&(t.memoizedState=a),a}function Lb(t){var a=Ob(t);a.next===null&&(a=t.alternate.memoizedState),ll(t,a.next.queue,{},Zn())}function Mh(){return bn(Al)}function Mb(){return Yt().memoizedState}function $b(){return Yt().memoizedState}function cx(t){for(var a=t.return;a!==null;){switch(a.tag){case 24:case 3:var s=Zn();t=Fr(s);var c=Kr(a,t,s);c!==null&&(Pn(c,a,s),al(c,a,s)),a={cache:lh()},t.payload=a;return}a=a.return}}function ux(t,a,s){var c=Zn();s={lane:c,revertLane:0,gesture:null,action:s,hasEagerState:!1,eagerState:null,next:null},pu(t)?Ib(a,s):(s=Jf(t,a,s,c),s!==null&&(Pn(s,t,c),Hb(s,a,c)))}function Nb(t,a,s){var c=Zn();ll(t,a,s,c)}function ll(t,a,s,c){var h={lane:c,revertLane:0,gesture:null,action:s,hasEagerState:!1,eagerState:null,next:null};if(pu(t))Ib(a,h);else{var p=t.alternate;if(t.lanes===0&&(p===null||p.lanes===0)&&(p=a.lastRenderedReducer,p!==null))try{var C=a.lastRenderedState,R=p(C,s);if(h.hasEagerState=!0,h.eagerState=R,Kn(R,C))return Yc(t,a,h,0),Dt===null&&Wc(),!1}catch{}if(s=Jf(t,a,h,c),s!==null)return Pn(s,t,c),Hb(s,a,c),!0}return!1}function $h(t,a,s,c){if(c={lane:2,revertLane:fg(),gesture:null,action:c,hasEagerState:!1,eagerState:null,next:null},pu(t)){if(a)throw Error(r(479))}else a=Jf(t,s,c,2),a!==null&&Pn(a,t,2)}function pu(t){var a=t.alternate;return t===Qe||a!==null&&a===Qe}function Ib(t,a){$s=lu=!0;var s=t.pending;s===null?a.next=a:(a.next=s.next,s.next=a),t.pending=a}function Hb(t,a,s){if((s&4194048)!==0){var c=a.lanes;c&=t.pendingLanes,s|=c,a.lanes=s,Ue(t,s)}}var cl={readContext:bn,use:du,useCallback:Gt,useContext:Gt,useEffect:Gt,useImperativeHandle:Gt,useLayoutEffect:Gt,useInsertionEffect:Gt,useMemo:Gt,useReducer:Gt,useRef:Gt,useState:Gt,useDebugValue:Gt,useDeferredValue:Gt,useTransition:Gt,useSyncExternalStore:Gt,useId:Gt,useHostTransitionStatus:Gt,useFormState:Gt,useActionState:Gt,useOptimistic:Gt,useMemoCache:Gt,useCacheRefresh:Gt};cl.useEffectEvent=Gt;var zb={readContext:bn,use:du,useCallback:function(t,a){return On().memoizedState=[t,a===void 0?null:a],t},useContext:bn,useEffect:wb,useImperativeHandle:function(t,a,s){s=s!=null?s.concat([t]):null,hu(4194308,4,Ab.bind(null,a,t),s)},useLayoutEffect:function(t,a){return hu(4194308,4,t,a)},useInsertionEffect:function(t,a){hu(4,2,t,a)},useMemo:function(t,a){var s=On();a=a===void 0?null:a;var c=t();if(Pi){Dn(!0);try{t()}finally{Dn(!1)}}return s.memoizedState=[c,a],c},useReducer:function(t,a,s){var c=On();if(s!==void 0){var h=s(a);if(Pi){Dn(!0);try{s(a)}finally{Dn(!1)}}}else h=a;return c.memoizedState=c.baseState=h,t={pending:null,lanes:0,dispatch:null,lastRenderedReducer:t,lastRenderedState:h},c.queue=t,t=t.dispatch=ux.bind(null,Qe,t),[c.memoizedState,t]},useRef:function(t){var a=On();return t={current:t},a.memoizedState=t},useState:function(t){t=Th(t);var a=t.queue,s=Nb.bind(null,Qe,a);return a.dispatch=s,[t.memoizedState,s]},useDebugValue:Dh,useDeferredValue:function(t,a){var s=On();return Oh(s,t,a)},useTransition:function(){var t=Th(!1);return t=Db.bind(null,Qe,t.queue,!0,!1),On().memoizedState=t,[!1,t]},useSyncExternalStore:function(t,a,s){var c=Qe,h=On();if(ct){if(s===void 0)throw Error(r(407));s=s()}else{if(s=a(),Dt===null)throw Error(r(349));(rt&127)!==0||ib(c,a,s)}h.memoizedState=s;var p={value:s,getSnapshot:a};return h.queue=p,wb(ob.bind(null,c,p,t),[t]),c.flags|=2048,Is(9,{destroy:void 0},sb.bind(null,c,p,s,a),null),s},useId:function(){var t=On(),a=Dt.identifierPrefix;if(ct){var s=Fa,c=Va;s=(c&~(1<<32-q(c)-1)).toString(32)+s,a="_"+a+"R_"+s,s=cu++,0<\/script>",p=p.removeChild(p.firstChild);break;case"select":p=typeof c.is=="string"?C.createElement("select",{is:c.is}):C.createElement("select"),c.multiple?p.multiple=!0:c.size&&(p.size=c.size);break;default:p=typeof c.is=="string"?C.createElement(h,{is:c.is}):C.createElement(h)}}p[ln]=a,p[xn]=c;e:for(C=a.child;C!==null;){if(C.tag===5||C.tag===6)p.appendChild(C.stateNode);else if(C.tag!==4&&C.tag!==27&&C.child!==null){C.child.return=C,C=C.child;continue}if(C===a)break e;for(;C.sibling===null;){if(C.return===null||C.return===a)break e;C=C.return}C.sibling.return=C.return,C=C.sibling}a.stateNode=p;e:switch(Sn(p,h,c),h){case"button":case"input":case"select":case"textarea":c=!!c.autoFocus;break e;case"img":c=!0;break e;default:c=!1}c&&gr(a)}}return $t(a),Wh(a,a.type,t===null?null:t.memoizedProps,a.pendingProps,s),null;case 6:if(t&&a.stateNode!=null)t.memoizedProps!==c&&gr(a);else{if(typeof c!="string"&&a.stateNode===null)throw Error(r(166));if(t=de.current,Ts(a)){if(t=a.stateNode,s=a.memoizedProps,c=null,h=yn,h!==null)switch(h.tag){case 27:case 5:c=h.memoizedProps}t[ln]=a,t=!!(t.nodeValue===s||c!==null&&c.suppressHydrationWarning===!0||aS(t.nodeValue,s)),t||qr(a,!0)}else t=Nu(t).createTextNode(c),t[ln]=a,a.stateNode=t}return $t(a),null;case 31:if(s=a.memoizedState,t===null||t.memoizedState!==null){if(c=Ts(a),s!==null){if(t===null){if(!c)throw Error(r(318));if(t=a.memoizedState,t=t!==null?t.dehydrated:null,!t)throw Error(r(557));t[ln]=a}else Ni(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;$t(a),t=!1}else s=rh(),t!==null&&t.memoizedState!==null&&(t.memoizedState.hydrationErrors=s),t=!0;if(!t)return a.flags&256?(Xn(a),a):(Xn(a),null);if((a.flags&128)!==0)throw Error(r(558))}return $t(a),null;case 13:if(c=a.memoizedState,t===null||t.memoizedState!==null&&t.memoizedState.dehydrated!==null){if(h=Ts(a),c!==null&&c.dehydrated!==null){if(t===null){if(!h)throw Error(r(318));if(h=a.memoizedState,h=h!==null?h.dehydrated:null,!h)throw Error(r(317));h[ln]=a}else Ni(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;$t(a),h=!1}else h=rh(),t!==null&&t.memoizedState!==null&&(t.memoizedState.hydrationErrors=h),h=!0;if(!h)return a.flags&256?(Xn(a),a):(Xn(a),null)}return Xn(a),(a.flags&128)!==0?(a.lanes=s,a):(s=c!==null,t=t!==null&&t.memoizedState!==null,s&&(c=a.child,h=null,c.alternate!==null&&c.alternate.memoizedState!==null&&c.alternate.memoizedState.cachePool!==null&&(h=c.alternate.memoizedState.cachePool.pool),p=null,c.memoizedState!==null&&c.memoizedState.cachePool!==null&&(p=c.memoizedState.cachePool.pool),p!==h&&(c.flags|=2048)),s!==t&&s&&(a.child.flags|=8192),Su(a,a.updateQueue),$t(a),null);case 4:return Pe(),t===null&&mg(a.stateNode.containerInfo),$t(a),null;case 10:return ur(a.type),$t(a),null;case 19:if(K(Wt),c=a.memoizedState,c===null)return $t(a),null;if(h=(a.flags&128)!==0,p=c.rendering,p===null)if(h)dl(c,!1);else{if(Vt!==0||t!==null&&(t.flags&128)!==0)for(t=a.child;t!==null;){if(p=ou(t),p!==null){for(a.flags|=128,dl(c,!1),t=p.updateQueue,a.updateQueue=t,Su(a,t),a.subtreeFlags=0,t=s,s=a.child;s!==null;)Ny(s,t),s=s.sibling;return ue(Wt,Wt.current&1|2),ct&&lr(a,c.treeForkCount),a.child}t=t.sibling}c.tail!==null&&Jt()>Au&&(a.flags|=128,h=!0,dl(c,!1),a.lanes=4194304)}else{if(!h)if(t=ou(p),t!==null){if(a.flags|=128,h=!0,t=t.updateQueue,a.updateQueue=t,Su(a,t),dl(c,!0),c.tail===null&&c.tailMode==="hidden"&&!p.alternate&&!ct)return $t(a),null}else 2*Jt()-c.renderingStartTime>Au&&s!==536870912&&(a.flags|=128,h=!0,dl(c,!1),a.lanes=4194304);c.isBackwards?(p.sibling=a.child,a.child=p):(t=c.last,t!==null?t.sibling=p:a.child=p,c.last=p)}return c.tail!==null?(t=c.tail,c.rendering=t,c.tail=t.sibling,c.renderingStartTime=Jt(),t.sibling=null,s=Wt.current,ue(Wt,h?s&1|2:s&1),ct&&lr(a,c.treeForkCount),t):($t(a),null);case 22:case 23:return Xn(a),yh(),c=a.memoizedState!==null,t!==null?t.memoizedState!==null!==c&&(a.flags|=8192):c&&(a.flags|=8192),c?(s&536870912)!==0&&(a.flags&128)===0&&($t(a),a.subtreeFlags&6&&(a.flags|=8192)):$t(a),s=a.updateQueue,s!==null&&Su(a,s.retryQueue),s=null,t!==null&&t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(s=t.memoizedState.cachePool.pool),c=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(c=a.memoizedState.cachePool.pool),c!==s&&(a.flags|=2048),t!==null&&K(zi),null;case 24:return s=null,t!==null&&(s=t.memoizedState.cache),a.memoizedState.cache!==s&&(a.flags|=2048),ur(en),$t(a),null;case 25:return null;case 30:return null}throw Error(r(156,a.tag))}function px(t,a){switch(nh(a),a.tag){case 1:return t=a.flags,t&65536?(a.flags=t&-65537|128,a):null;case 3:return ur(en),Pe(),t=a.flags,(t&65536)!==0&&(t&128)===0?(a.flags=t&-65537|128,a):null;case 26:case 27:case 5:return Ot(a),null;case 31:if(a.memoizedState!==null){if(Xn(a),a.alternate===null)throw Error(r(340));Ni()}return t=a.flags,t&65536?(a.flags=t&-65537|128,a):null;case 13:if(Xn(a),t=a.memoizedState,t!==null&&t.dehydrated!==null){if(a.alternate===null)throw Error(r(340));Ni()}return t=a.flags,t&65536?(a.flags=t&-65537|128,a):null;case 19:return K(Wt),null;case 4:return Pe(),null;case 10:return ur(a.type),null;case 22:case 23:return Xn(a),yh(),t!==null&&K(zi),t=a.flags,t&65536?(a.flags=t&-65537|128,a):null;case 24:return ur(en),null;case 25:return null;default:return null}}function lv(t,a){switch(nh(a),a.tag){case 3:ur(en),Pe();break;case 26:case 27:case 5:Ot(a);break;case 4:Pe();break;case 31:a.memoizedState!==null&&Xn(a);break;case 13:Xn(a);break;case 19:K(Wt);break;case 10:ur(a.type);break;case 22:case 23:Xn(a),yh(),t!==null&&K(zi);break;case 24:ur(en)}}function fl(t,a){try{var s=a.updateQueue,c=s!==null?s.lastEffect:null;if(c!==null){var h=c.next;s=h;do{if((s.tag&t)===t){c=void 0;var p=s.create,C=s.inst;c=p(),C.destroy=c}s=s.next}while(s!==h)}}catch(R){_t(a,a.return,R)}}function Xr(t,a,s){try{var c=a.updateQueue,h=c!==null?c.lastEffect:null;if(h!==null){var p=h.next;c=p;do{if((c.tag&t)===t){var C=c.inst,R=C.destroy;if(R!==void 0){C.destroy=void 0,h=a;var U=s,Y=R;try{Y()}catch(ne){_t(h,U,ne)}}}c=c.next}while(c!==p)}}catch(ne){_t(a,a.return,ne)}}function cv(t){var a=t.updateQueue;if(a!==null){var s=t.stateNode;try{Zy(a,s)}catch(c){_t(t,t.return,c)}}}function uv(t,a,s){s.props=qi(t.type,t.memoizedProps),s.state=t.memoizedState;try{s.componentWillUnmount()}catch(c){_t(t,a,c)}}function hl(t,a){try{var s=t.ref;if(s!==null){switch(t.tag){case 26:case 27:case 5:var c=t.stateNode;break;case 30:c=t.stateNode;break;default:c=t.stateNode}typeof s=="function"?t.refCleanup=s(c):s.current=c}}catch(h){_t(t,a,h)}}function Ka(t,a){var s=t.ref,c=t.refCleanup;if(s!==null)if(typeof c=="function")try{c()}catch(h){_t(t,a,h)}finally{t.refCleanup=null,t=t.alternate,t!=null&&(t.refCleanup=null)}else if(typeof s=="function")try{s(null)}catch(h){_t(t,a,h)}else s.current=null}function dv(t){var a=t.type,s=t.memoizedProps,c=t.stateNode;try{e:switch(a){case"button":case"input":case"select":case"textarea":s.autoFocus&&c.focus();break e;case"img":s.src?c.src=s.src:s.srcSet&&(c.srcset=s.srcSet)}}catch(h){_t(t,t.return,h)}}function Yh(t,a,s){try{var c=t.stateNode;Hx(c,t.type,s,a),c[xn]=a}catch(h){_t(t,t.return,h)}}function fv(t){return t.tag===5||t.tag===3||t.tag===26||t.tag===27&&ai(t.type)||t.tag===4}function Xh(t){e:for(;;){for(;t.sibling===null;){if(t.return===null||fv(t.return))return null;t=t.return}for(t.sibling.return=t.return,t=t.sibling;t.tag!==5&&t.tag!==6&&t.tag!==18;){if(t.tag===27&&ai(t.type)||t.flags&2||t.child===null||t.tag===4)continue e;t.child.return=t,t=t.child}if(!(t.flags&2))return t.stateNode}}function Jh(t,a,s){var c=t.tag;if(c===5||c===6)t=t.stateNode,a?(s.nodeType===9?s.body:s.nodeName==="HTML"?s.ownerDocument.body:s).insertBefore(t,a):(a=s.nodeType===9?s.body:s.nodeName==="HTML"?s.ownerDocument.body:s,a.appendChild(t),s=s._reactRootContainer,s!=null||a.onclick!==null||(a.onclick=xa));else if(c!==4&&(c===27&&ai(t.type)&&(s=t.stateNode,a=null),t=t.child,t!==null))for(Jh(t,a,s),t=t.sibling;t!==null;)Jh(t,a,s),t=t.sibling}function wu(t,a,s){var c=t.tag;if(c===5||c===6)t=t.stateNode,a?s.insertBefore(t,a):s.appendChild(t);else if(c!==4&&(c===27&&ai(t.type)&&(s=t.stateNode),t=t.child,t!==null))for(wu(t,a,s),t=t.sibling;t!==null;)wu(t,a,s),t=t.sibling}function hv(t){var a=t.stateNode,s=t.memoizedProps;try{for(var c=t.type,h=a.attributes;h.length;)a.removeAttributeNode(h[0]);Sn(a,c,s),a[ln]=t,a[xn]=s}catch(p){_t(t,t.return,p)}}var pr=!1,an=!1,Qh=!1,gv=typeof WeakSet=="function"?WeakSet:Set,gn=null;function mx(t,a){if(t=t.containerInfo,vg=Pu,t=xy(t),Vf(t)){if("selectionStart"in t)var s={start:t.selectionStart,end:t.selectionEnd};else e:{s=(s=t.ownerDocument)&&s.defaultView||window;var c=s.getSelection&&s.getSelection();if(c&&c.rangeCount!==0){s=c.anchorNode;var h=c.anchorOffset,p=c.focusNode;c=c.focusOffset;try{s.nodeType,p.nodeType}catch{s=null;break e}var C=0,R=-1,U=-1,Y=0,ne=0,ce=t,J=null;t:for(;;){for(var ee;ce!==s||h!==0&&ce.nodeType!==3||(R=C+h),ce!==p||c!==0&&ce.nodeType!==3||(U=C+c),ce.nodeType===3&&(C+=ce.nodeValue.length),(ee=ce.firstChild)!==null;)J=ce,ce=ee;for(;;){if(ce===t)break t;if(J===s&&++Y===h&&(R=C),J===p&&++ne===c&&(U=C),(ee=ce.nextSibling)!==null)break;ce=J,J=ce.parentNode}ce=ee}s=R===-1||U===-1?null:{start:R,end:U}}else s=null}s=s||{start:0,end:0}}else s=null;for(Sg={focusedElem:t,selectionRange:s},Pu=!1,gn=a;gn!==null;)if(a=gn,t=a.child,(a.subtreeFlags&1028)!==0&&t!==null)t.return=a,gn=t;else for(;gn!==null;){switch(a=gn,p=a.alternate,t=a.flags,a.tag){case 0:if((t&4)!==0&&(t=a.updateQueue,t=t!==null?t.events:null,t!==null))for(s=0;s title"))),Sn(p,c,s),p[ln]=t,Zt(p),c=p;break e;case"link":var C=SS("link","href",h).get(c+(s.href||""));if(C){for(var R=0;RRt&&(C=Rt,Rt=Ve,Ve=C);var F=_y(R,Ve),G=_y(R,Rt);if(F&&G&&(ee.rangeCount!==1||ee.anchorNode!==F.node||ee.anchorOffset!==F.offset||ee.focusNode!==G.node||ee.focusOffset!==G.offset)){var W=ce.createRange();W.setStart(F.node,F.offset),ee.removeAllRanges(),Ve>Rt?(ee.addRange(W),ee.extend(G.node,G.offset)):(W.setEnd(G.node,G.offset),ee.addRange(W))}}}}for(ce=[],ee=R;ee=ee.parentNode;)ee.nodeType===1&&ce.push({element:ee,left:ee.scrollLeft,top:ee.scrollTop});for(typeof R.focus=="function"&&R.focus(),R=0;Rs?32:s,Q.T=null,s=ig,ig=null;var p=ei,C=Sr;if(un=0,Bs=ei=null,Sr=0,(St&6)!==0)throw Error(r(331));var R=St;if(St|=4,Av(p.current),Cv(p,p.current,C,s),St=R,vl(0,!1),on&&typeof on.onPostCommitFiberRoot=="function")try{on.onPostCommitFiberRoot(_a,p)}catch{}return!0}finally{fe.p=h,Q.T=c,qv(t,a)}}function Vv(t,a,s){a=ia(s,a),a=zh(t.stateNode,a,2),t=Kr(t,a,2),t!==null&&(Ke(t,2),Wa(t))}function _t(t,a,s){if(t.tag===3)Vv(t,t,s);else for(;a!==null;){if(a.tag===3){Vv(a,t,s);break}else if(a.tag===1){var c=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof c.componentDidCatch=="function"&&(Zr===null||!Zr.has(c))){t=ia(s,t),s=Fb(2),c=Kr(a,s,2),c!==null&&(Kb(s,c,a,t),Ke(c,2),Wa(c));break}}a=a.return}}function cg(t,a,s){var c=t.pingCache;if(c===null){c=t.pingCache=new vx;var h=new Set;c.set(a,h)}else h=c.get(a),h===void 0&&(h=new Set,c.set(a,h));h.has(s)||(tg=!0,h.add(s),t=_x.bind(null,t,a,s),a.then(t,t))}function _x(t,a,s){var c=t.pingCache;c!==null&&c.delete(a),t.pingedLanes|=t.suspendedLanes&s,t.warmLanes&=~s,Dt===t&&(rt&s)===s&&(Vt===4||Vt===3&&(rt&62914560)===rt&&300>Jt()-_u?(St&2)===0&&Ps(t,0):ng|=s,Us===rt&&(Us=0)),Wa(t)}function Fv(t,a){a===0&&(a=De()),t=Mi(t,a),t!==null&&(Ke(t,a),Wa(t))}function Ax(t){var a=t.memoizedState,s=0;a!==null&&(s=a.retryLane),Fv(t,s)}function xx(t,a){var s=0;switch(t.tag){case 31:case 13:var c=t.stateNode,h=t.memoizedState;h!==null&&(s=h.retryLane);break;case 19:c=t.stateNode;break;case 22:c=t.stateNode._retryCache;break;default:throw Error(r(314))}c!==null&&c.delete(a),Fv(t,s)}function Tx(t,a){return Lt(t,a)}var Ou=null,Gs=null,ug=!1,Lu=!1,dg=!1,ni=0;function Wa(t){t!==Gs&&t.next===null&&(Gs===null?Ou=Gs=t:Gs=Gs.next=t),Lu=!0,ug||(ug=!0,kx())}function vl(t,a){if(!dg&&Lu){dg=!0;do for(var s=!1,c=Ou;c!==null;){if(t!==0){var h=c.pendingLanes;if(h===0)var p=0;else{var C=c.suspendedLanes,R=c.pingedLanes;p=(1<<31-q(42|t)+1)-1,p&=h&~(C&~R),p=p&201326741?p&201326741|1:p?p|2:0}p!==0&&(s=!0,Xv(c,p))}else p=rt,p=je(c,c===Dt?p:0,c.cancelPendingCommit!==null||c.timeoutHandle!==-1),(p&3)===0||ze(c,p)||(s=!0,Xv(c,p));c=c.next}while(s);dg=!1}}function Rx(){Kv()}function Kv(){Lu=ug=!1;var t=0;ni!==0&&jx()&&(t=ni);for(var a=Jt(),s=null,c=Ou;c!==null;){var h=c.next,p=Wv(c,a);p===0?(c.next=null,s===null?Ou=h:s.next=h,h===null&&(Gs=s)):(s=c,(t!==0||(p&3)!==0)&&(Lu=!0)),c=h}un!==0&&un!==5||vl(t),ni!==0&&(ni=0)}function Wv(t,a){for(var s=t.suspendedLanes,c=t.pingedLanes,h=t.expirationTimes,p=t.pendingLanes&-62914561;0R)break;var ne=U.transferSize,ce=U.initiatorType;ne&&rS(ce)&&(U=U.responseEnd,C+=ne*(U"u"?null:document;function mS(t,a,s){var c=Vs;if(c&&typeof a=="string"&&a){var h=Hn(a);h='link[rel="'+t+'"][href="'+h+'"]',typeof s=="string"&&(h+='[crossorigin="'+s+'"]'),pS.has(h)||(pS.add(h),t={rel:t,crossOrigin:s,href:a},c.querySelector(h)===null&&(a=c.createElement("link"),Sn(a,"link",t),Zt(a),c.head.appendChild(a)))}}function Wx(t){wr.D(t),mS("dns-prefetch",t,null)}function Yx(t,a){wr.C(t,a),mS("preconnect",t,a)}function Xx(t,a,s){wr.L(t,a,s);var c=Vs;if(c&&t&&a){var h='link[rel="preload"][as="'+Hn(a)+'"]';a==="image"&&s&&s.imageSrcSet?(h+='[imagesrcset="'+Hn(s.imageSrcSet)+'"]',typeof s.imageSizes=="string"&&(h+='[imagesizes="'+Hn(s.imageSizes)+'"]')):h+='[href="'+Hn(t)+'"]';var p=h;switch(a){case"style":p=Fs(t);break;case"script":p=Ks(t)}da.has(p)||(t=b({rel:"preload",href:a==="image"&&s&&s.imageSrcSet?void 0:t,as:a},s),da.set(p,t),c.querySelector(h)!==null||a==="style"&&c.querySelector(El(p))||a==="script"&&c.querySelector(_l(p))||(a=c.createElement("link"),Sn(a,"link",t),Zt(a),c.head.appendChild(a)))}}function Jx(t,a){wr.m(t,a);var s=Vs;if(s&&t){var c=a&&typeof a.as=="string"?a.as:"script",h='link[rel="modulepreload"][as="'+Hn(c)+'"][href="'+Hn(t)+'"]',p=h;switch(c){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":p=Ks(t)}if(!da.has(p)&&(t=b({rel:"modulepreload",href:t},a),da.set(p,t),s.querySelector(h)===null)){switch(c){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(s.querySelector(_l(p)))return}c=s.createElement("link"),Sn(c,"link",t),Zt(c),s.head.appendChild(c)}}}function Qx(t,a,s){wr.S(t,a,s);var c=Vs;if(c&&t){var h=Mr(c).hoistableStyles,p=Fs(t);a=a||"default";var C=h.get(p);if(!C){var R={loading:0,preload:null};if(C=c.querySelector(El(p)))R.loading=5;else{t=b({rel:"stylesheet",href:t,"data-precedence":a},s),(s=da.get(p))&&Tg(t,s);var U=C=c.createElement("link");Zt(U),Sn(U,"link",t),U._p=new Promise(function(Y,ne){U.onload=Y,U.onerror=ne}),U.addEventListener("load",function(){R.loading|=1}),U.addEventListener("error",function(){R.loading|=2}),R.loading|=4,Hu(C,a,c)}C={type:"stylesheet",instance:C,count:1,state:R},h.set(p,C)}}}function Zx(t,a){wr.X(t,a);var s=Vs;if(s&&t){var c=Mr(s).hoistableScripts,h=Ks(t),p=c.get(h);p||(p=s.querySelector(_l(h)),p||(t=b({src:t,async:!0},a),(a=da.get(h))&&Rg(t,a),p=s.createElement("script"),Zt(p),Sn(p,"link",t),s.head.appendChild(p)),p={type:"script",instance:p,count:1,state:null},c.set(h,p))}}function eT(t,a){wr.M(t,a);var s=Vs;if(s&&t){var c=Mr(s).hoistableScripts,h=Ks(t),p=c.get(h);p||(p=s.querySelector(_l(h)),p||(t=b({src:t,async:!0,type:"module"},a),(a=da.get(h))&&Rg(t,a),p=s.createElement("script"),Zt(p),Sn(p,"link",t),s.head.appendChild(p)),p={type:"script",instance:p,count:1,state:null},c.set(h,p))}}function yS(t,a,s,c){var h=(h=de.current)?Iu(h):null;if(!h)throw Error(r(446));switch(t){case"meta":case"title":return null;case"style":return typeof s.precedence=="string"&&typeof s.href=="string"?(a=Fs(s.href),s=Mr(h).hoistableStyles,c=s.get(a),c||(c={type:"style",instance:null,count:0,state:null},s.set(a,c)),c):{type:"void",instance:null,count:0,state:null};case"link":if(s.rel==="stylesheet"&&typeof s.href=="string"&&typeof s.precedence=="string"){t=Fs(s.href);var p=Mr(h).hoistableStyles,C=p.get(t);if(C||(h=h.ownerDocument||h,C={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},p.set(t,C),(p=h.querySelector(El(t)))&&!p._p&&(C.instance=p,C.state.loading=5),da.has(t)||(s={rel:"preload",as:"style",href:s.href,crossOrigin:s.crossOrigin,integrity:s.integrity,media:s.media,hrefLang:s.hrefLang,referrerPolicy:s.referrerPolicy},da.set(t,s),p||tT(h,t,s,C.state))),a&&c===null)throw Error(r(528,""));return C}if(a&&c!==null)throw Error(r(529,""));return null;case"script":return a=s.async,s=s.src,typeof s=="string"&&a&&typeof a!="function"&&typeof a!="symbol"?(a=Ks(s),s=Mr(h).hoistableScripts,c=s.get(a),c||(c={type:"script",instance:null,count:0,state:null},s.set(a,c)),c):{type:"void",instance:null,count:0,state:null};default:throw Error(r(444,t))}}function Fs(t){return'href="'+Hn(t)+'"'}function El(t){return'link[rel="stylesheet"]['+t+"]"}function bS(t){return b({},t,{"data-precedence":t.precedence,precedence:null})}function tT(t,a,s,c){t.querySelector('link[rel="preload"][as="style"]['+a+"]")?c.loading=1:(a=t.createElement("link"),c.preload=a,a.addEventListener("load",function(){return c.loading|=1}),a.addEventListener("error",function(){return c.loading|=2}),Sn(a,"link",s),Zt(a),t.head.appendChild(a))}function Ks(t){return'[src="'+Hn(t)+'"]'}function _l(t){return"script[async]"+t}function vS(t,a,s){if(a.count++,a.instance===null)switch(a.type){case"style":var c=t.querySelector('style[data-href~="'+Hn(s.href)+'"]');if(c)return a.instance=c,Zt(c),c;var h=b({},s,{"data-href":s.href,"data-precedence":s.precedence,href:null,precedence:null});return c=(t.ownerDocument||t).createElement("style"),Zt(c),Sn(c,"style",h),Hu(c,s.precedence,t),a.instance=c;case"stylesheet":h=Fs(s.href);var p=t.querySelector(El(h));if(p)return a.state.loading|=4,a.instance=p,Zt(p),p;c=bS(s),(h=da.get(h))&&Tg(c,h),p=(t.ownerDocument||t).createElement("link"),Zt(p);var C=p;return C._p=new Promise(function(R,U){C.onload=R,C.onerror=U}),Sn(p,"link",c),a.state.loading|=4,Hu(p,s.precedence,t),a.instance=p;case"script":return p=Ks(s.src),(h=t.querySelector(_l(p)))?(a.instance=h,Zt(h),h):(c=s,(h=da.get(p))&&(c=b({},s),Rg(c,h)),t=t.ownerDocument||t,h=t.createElement("script"),Zt(h),Sn(h,"link",c),t.head.appendChild(h),a.instance=h);case"void":return null;default:throw Error(r(443,a.type))}else a.type==="stylesheet"&&(a.state.loading&4)===0&&(c=a.instance,a.state.loading|=4,Hu(c,s.precedence,t));return a.instance}function Hu(t,a,s){for(var c=s.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),h=c.length?c[c.length-1]:null,p=h,C=0;C title"):null)}function nT(t,a,s){if(s===1||a.itemProp!=null)return!1;switch(t){case"meta":case"title":return!0;case"style":if(typeof a.precedence!="string"||typeof a.href!="string"||a.href==="")break;return!0;case"link":if(typeof a.rel!="string"||typeof a.href!="string"||a.href===""||a.onLoad||a.onError)break;return a.rel==="stylesheet"?(t=a.disabled,typeof a.precedence=="string"&&t==null):!0;case"script":if(a.async&&typeof a.async!="function"&&typeof a.async!="symbol"&&!a.onLoad&&!a.onError&&a.src&&typeof a.src=="string")return!0}return!1}function CS(t){return!(t.type==="stylesheet"&&(t.state.loading&3)===0)}function aT(t,a,s,c){if(s.type==="stylesheet"&&(typeof c.media!="string"||matchMedia(c.media).matches!==!1)&&(s.state.loading&4)===0){if(s.instance===null){var h=Fs(c.href),p=a.querySelector(El(h));if(p){a=p._p,a!==null&&typeof a=="object"&&typeof a.then=="function"&&(t.count++,t=ju.bind(t),a.then(t,t)),s.state.loading|=4,s.instance=p,Zt(p);return}p=a.ownerDocument||a,c=bS(c),(h=da.get(h))&&Tg(c,h),p=p.createElement("link"),Zt(p);var C=p;C._p=new Promise(function(R,U){C.onload=R,C.onerror=U}),Sn(p,"link",c),s.instance=p}t.stylesheets===null&&(t.stylesheets=new Map),t.stylesheets.set(s,a),(a=s.state.preload)&&(s.state.loading&3)===0&&(t.count++,s=ju.bind(t),a.addEventListener("load",s),a.addEventListener("error",s))}}var kg=0;function rT(t,a){return t.stylesheets&&t.count===0&&Bu(t,t.stylesheets),0kg?50:800)+a);return t.unsuspend=s,function(){t.unsuspend=null,clearTimeout(c),clearTimeout(h)}}:null}function ju(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Bu(this,this.stylesheets);else if(this.unsuspend){var t=this.unsuspend;this.unsuspend=null,t()}}}var Uu=null;function Bu(t,a){t.stylesheets=null,t.unsuspend!==null&&(t.count++,Uu=new Map,a.forEach(iT,t),Uu=null,ju.call(t))}function iT(t,a){if(!(a.state.loading&4)){var s=Uu.get(t);if(s)var c=s.get(null);else{s=new Map,Uu.set(t,s);for(var h=t.querySelectorAll("link[data-precedence],style[data-precedence]"),p=0;p"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(o)}catch(e){console.error(e)}}return o(),Ju.exports=PS(),Ju.exports}var td=qS();const nd=Xa(td),Xs=[],GS=50;let ad=!1;function Vg(){try{return window.G7Core?.devTools}catch{return}}function Fi(o,e,n){const r=Vg();if(ad&&r?.isEnabled?.()){r.trackLog?.(o,e,n);return}ad||(o==="error"||o==="warn")&&Xs.length{n.isDebugEnabled()&&console.log(e,...r),Fi("log",o,r)},warn:(...r)=>{n.isDebugEnabled()&&console.warn(e,...r),Fi("warn",o,r)},error:(...r)=>{n.isDebugEnabled()&&console.error(e,...r),Fi("error",o,r)}}}Js.getInstance();const Ki=dt("networkResilience"),Fg=2,Kg=300,Wg=2e3,VS=15e3;function Yg(o){return o?.name==="AbortError"}function FS(o){return Yg(o)?!1:o instanceof TypeError}let kl=!1,Xg=!1;function id(){return kl}function KS(){typeof window>"u"||Xg||(Xg=!0,window.addEventListener("pagehide",()=>{kl=!0}),window.addEventListener("pageshow",o=>{o.persisted&&(kl=!1)}),window.addEventListener("beforeunload",()=>{kl=!0}))}function Jg(o,e,n){const r=Math.min(e*Math.pow(2,o),n),i=r*.25*(Math.random()*2-1);return Math.max(0,Math.round(r+i))}function Qg(o){return new Promise(e=>setTimeout(e,o))}async function Dl(o,e={}){const{retries:n=Fg,baseDelayMs:r=Kg,maxDelayMs:i=Wg,timeoutMs:l=VS,label:u=o,init:d}=e,f=n+1;let g;for(let m=0;m0?new AbortController:null;try{const _={...d};if(S){const k=d?.signal;k&&(k.aborted?S.abort():k.addEventListener("abort",()=>S.abort(),{once:!0})),_.signal=S.signal,v=setTimeout(()=>{b=!0,S.abort()},l)}return await fetch(o,_)}catch(_){if(g=_,Yg(_)&&!b||!(b||FS(_)))throw _;if(id())throw Ki.warn(`Document unloading, aborting retries: ${u}`),_;if(m===f-1)throw Ki.warn(`All ${f} attempts failed: ${u}`,_),_;const O=Jg(m,r,i);Ki.warn(`Network failure (attempt ${m+1}/${f}), retrying in ${O}ms: ${u}`),await Qg(O)}finally{v!==void 0&&clearTimeout(v)}}throw g}async function Zg(o,e={},n={}){const{retries:r=Fg,baseDelayMs:i=Kg,maxDelayMs:l=Wg,label:u=o}=n,d=r+1;for(let f=0;f{const i=document.createElement("script");i.src=o,i.async=!1;for(const[l,u]of Object.entries(e))l==="id"?i.id=u:i.setAttribute(l,u);i.onload=()=>n(),i.onerror=()=>r(new Error(`Failed to load script: ${o}`)),document.head.appendChild(i)})}const ep="extension",Wi="extensionless",YS="file";function XS(){const o=globalThis?.G7Config;if(globalThis?.__g7AssetUrlMode===Wi)return Wi;const n=o?.assetUrlMode;return n===Wi||n===ep?n:o?.settings?.general?.asset_url_mode===Wi?Wi:ep}function tp(){return XS()===Wi}function Ma(o,e,n,r){const i=o.replace(/\/+$/,""),l=e.replace(/^\.+/,""),u=tp()?i:`${i}.${l}`,d=[];return r&&d.push(r.replace(/^[?&]+/,"")),n!=null&&n!==""&&d.push(`v=${n}`),d.length>0?`${u}?${d.join("&")}`:u}function Cr(o){if(!o||!tp())return o;const e=globalThis?.location?.origin,n=e&&o.startsWith(e)?o.slice(e.length):o;if(!n.startsWith("/api/"))return o;const[r,i]=JS(n),l=r.match(/^\/api\/(modules|plugins)\/bundle\.(js|css)$/);if(l)return np(`/api/${l[1]}/bundle/${l[2]}`,i);const u=r.match(/^\/api\/(templates|modules|plugins)\/assets\/([^/]+)\/(.+)$/);if(u){const[,f,g,m]=u,b=`${YS}=${encodeURIComponent(decodeURIComponent(m))}`;return`/api/${f}/assets/${g}?${b}${i?`&${i}`:""}`}const d=r.match(/^(\/api\/.+)\.(json|js|css)$/);return d?np(d[1],i):o}function JS(o){const e=o.indexOf("?");return e===-1?[o,""]:[o.slice(0,e),o.slice(e+1)]}function np(o,e){return e?`${o}?${e}`:o}const $a=dt("ComponentRegistry");class dn extends Error{constructor(n,r,i){super(n);$(this,"code");$(this,"details");this.code=r,this.details=i,this.name="ComponentRegistryError"}}const Vn=class Vn{constructor(){$(this,"registry",{});$(this,"manifest",null);$(this,"loadingState","idle");$(this,"error",null);$(this,"templateId",null);$(this,"templateType",null)}static getInstance(){return Vn.instance||(Vn.instance=new Vn),Vn.instance}static createIsolatedInstance(){return new Vn}static resetInstance(){Vn.instance=null}async loadComponents(e,n){if(this.loadingState==="loading")throw new dn("Components are already being loaded","LOADING_IN_PROGRESS");if(this.loadingState==="loaded"&&this.templateId===e&&this.templateType===n){$a.log("Components already loaded for template:",e,n);return}this.loadingState="loading",this.templateId=e,this.templateType=n,this.error=null;try{await this.loadManifest(),await this.loadComponentBundle(),this.loadingState="loaded",$a.log("Successfully loaded components:",Object.keys(this.registry).length)}catch(r){throw this.loadingState="error",this.error=r instanceof Error?r:new Error(String(r)),new dn(`Failed to load components: ${this.error.message}`,"LOAD_FAILED",{originalError:this.error})}}async loadManifest(){try{if(!this.templateId)throw new dn("Template ID not set","TEMPLATE_ID_NOT_SET");const e=`${this.templateId}:${this.templateType}`;if(Vn.manifestCache.has(e)){this.manifest=Vn.manifestCache.get(e),$a.log("Manifest loaded from cache:",this.manifest.templateId);return}const n=Ma(`/api/templates/${this.templateId}/components`,"json"),r=await Dl(n,{label:"components.json"});if(!r.ok)throw new dn(`Failed to fetch manifest: ${r.status} ${r.statusText}`,"MANIFEST_FETCH_FAILED",{status:r.status,statusText:r.statusText});const i=await r.json();this.validateManifest(i),this.manifest=i,Vn.manifestCache.set(e,i),$a.log("Manifest loaded and cached:",i.templateId)}catch(e){throw e instanceof dn?e:new dn("Failed to load component manifest","MANIFEST_LOAD_FAILED",{originalError:e})}}validateManifest(e){if(!e.version)throw new dn("Manifest missing required field: version","MANIFEST_INVALID",{field:"version"});if(!e.templateId)throw new dn("Manifest missing required field: templateId","MANIFEST_INVALID",{field:"templateId"});if(!e.components||typeof e.components!="object")throw new dn("Manifest missing required field: components","MANIFEST_INVALID",{field:"components"});const n=["basic","composite","layout"];for(const r of n){if(!Array.isArray(e.components[r]))throw new dn(`Manifest field 'components.${r}' must be an array`,"MANIFEST_INVALID",{field:`components.${r}`,value:e.components[r]});e.components[r].forEach((i,l)=>{if(!i.name||typeof i.name!="string")throw new dn(`Invalid component metadata at ${r}[${l}]: missing or invalid 'name'`,"MANIFEST_INVALID",{type:r,index:l,metadata:i});if(!i.type||typeof i.type!="string")throw new dn(`Invalid component metadata at ${r}[${l}]: missing or invalid 'type'`,"MANIFEST_INVALID",{type:r,index:l,metadata:i})})}$a.log("Manifest validation passed")}async loadComponentBundle(){try{if(!this.templateId)throw new dn("Template ID not set","TEMPLATE_ID_NOT_SET");const e=this.getGlobalVariableName(),n=window[e];if(!n||typeof n!="object")throw new dn(`Component bundle not loaded. Expected global variable: ${e}. Ensure admin.blade.php includes the IIFE bundle script.`,"BUNDLE_NOT_LOADED",{expectedVariable:e});await this.registerComponentsFromManifest(n),$a.log("Component bundle loaded from global variable:",e)}catch(e){throw e instanceof dn?e:new dn("Failed to load component bundle","BUNDLE_LOAD_FAILED",{originalError:e})}}getGlobalVariableName(){if(!this.templateId)throw new dn("Template ID not set","TEMPLATE_ID_NOT_SET");return this.templateId.split(/[-_]/).map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}async registerComponentsFromManifest(e){if(!this.manifest)throw new dn("Manifest not loaded","MANIFEST_NOT_LOADED");const n=["basic","composite","layout"];for(const r of n){const i=this.manifest.components[r]||[];for(const l of i){const u=l.name,d=e[u];if(!d){$a.warn(`Component '${u}' not found in bundle`);continue}this.registerComponent(u,d,l)}}}registerComponent(e,n,r){this.registry[e]&&$a.warn(`Component '${e}' already registered, overwriting`);const i=Xe.memo(n);this.registry[e]={component:i,metadata:r},$a.log(`[ComponentRegistry] Registered component: ${e} (${r.type})`)}getComponent(e){const n=this.registry[e];return n?n.component:null}getMetadata(e){const n=this.registry[e];return n?n.metadata:null}hasComponent(e){return e in this.registry}getComponentsByType(e){return Object.entries(this.registry).filter(([n,r])=>r.metadata.type===e).map(([n,r])=>n)}getAllComponents(){return Object.keys(this.registry)}getComponentMap(){const e={};for(const[n,r]of Object.entries(this.registry))e[n]=r.component;return e}getLoadingState(){return this.loadingState}getError(){return this.error}getTemplateId(){return this.templateId}getManifest(){return this.manifest}clear(){this.registry={},this.manifest=null,this.loadingState="idle",this.error=null,this.templateId=null,this.templateType=null,$a.log("Registry cleared")}};$(Vn,"instance",null),$(Vn,"manifestCache",new Map);let fa=Vn;const ap=dt("TranslationEngine");class sd extends Error{constructor(n,r,i){super(n);$(this,"key");$(this,"locale");this.key=r,this.locale=i,this.name="TranslationError"}}const $n=class $n{constructor(e={}){$(this,"cache",new Map);$(this,"translations",new Map);$(this,"options");$(this,"cacheVersion",0);this.options={defaultLocale:e.defaultLocale||"ko",fallbackLocale:e.fallbackLocale||"en",cacheTTL:e.cacheTTL||3e5}}static getInstance(e={}){return $n.instance||($n.instance=new $n(e)),$n.instance}static resetInstance(){$n.instance=null}setCacheVersion(e){this.cacheVersion!==e&&(ap.log("Cache version updated:",this.cacheVersion,"->",e),this.cacheVersion=e,this.cache.clear())}getCacheVersion(){return this.cacheVersion}async loadTranslations(e,n,r="/api",i=!1){const l=`${e}:${n}`;if(!i){const u=this.getFromCache(l);if(u)return this.translations.set(l,u),u}try{const u=[];i&&u.push(`_=${Date.now()}`);const d=Ma(`${r}/templates/${e}/lang/${n}`,"json",this.cacheVersion>0?this.cacheVersion:null,u.length>0?u.join("&"):void 0),f=await fetch(d);if(!f.ok)throw new sd(`Failed to load translations: ${f.statusText}`,void 0,n);const m=await f.json();return this.saveToCache(l,m),this.translations.set(l,m),m}catch(u){throw new sd(`Failed to fetch translations for ${n}: ${u instanceof Error?u.message:String(u)}`,void 0,n)}}resolveTranslations(e,n,r){let i=e;const l=5;let u=0;for(;u"="+this.translate(m,n,void 0,r)),i===d)break;u++}return i.replace($n.TRANSLATION_PATTERN,(d,f,g)=>{const{cleanedParams:m,trailing:b}=this.separateTrailingText(g);return this.translate(f,n,m,r)+b})}translate(e,n,r,i){const l=this.getTranslation(e,n),u=r&&this.cleanParamsStr(r);if(u){const d=this.parseParams(u,i);return this.replaceParams(l,d)}return l}getTranslation(e,n){const{templateId:r,locale:i}=n,l=`${r}:${i}`,u=this.translations.get(l);if(u){const d=this.getNestedValue(u,e);if(d!==null)return d}if(i!==this.options.fallbackLocale){const d=`${r}:${this.options.fallbackLocale}`,f=this.translations.get(d);if(f){const g=this.getNestedValue(f,e);if(g!==null)return g}}return e}getNestedValue(e,n){const r=n.split(".");let i=e;for(const l of r){if(i==null||typeof i!="object")return null;i=i[l]}return typeof i=="string"?i:null}setTranslationValue(e,n,r,i){const l=`${e}:${n}`,u=this.translations.get(l)??{},d=r.split(".");let f=u;for(let g=0;g(l.push(f),`__PLACEHOLDER_${l.length-1}__`)).matchAll($n.PARAM_PATTERN);for(const f of d){const[,g,m]=f,b=m.replace(/__PLACEHOLDER_(\d+)__/g,(v,S)=>l[parseInt(S,10)]);r[g.trim()]=this.resolveParamValue(b.trim(),n)}return r}resolveParamValue(e,n){if(e.startsWith("{{")&&e.endsWith("}}")){const r=e.slice(2,-2).trim();if(/[|&()[\]!?:+\-*/%<>=\s]/.test(r)&&n)try{const u=new Function(...Object.keys(n),`return ${r}`)(...Object.values(n));return String(u??"")}catch(l){return ap.error("Expression evaluation failed:",r,l),""}else{const l=this.getNestedDataValue(n,r);return String(l??"")}}return e}separateTrailingText(e){if(!e)return{cleanedParams:void 0,trailing:""};if(e.trimEnd().endsWith("}}"))return{cleanedParams:e,trailing:""};if(!(e.startsWith("|")?e.slice(1):e).includes("="))return{cleanedParams:void 0,trailing:e};const r=e.match(/(\s+[^\p{L}\w=|&\s][^\p{L}\w=]*\s*)$/u);return r?{cleanedParams:e.slice(0,-r[1].length),trailing:r[1]}:{cleanedParams:e,trailing:""}}cleanParamsStr(e){return this.separateTrailingText(e).cleanedParams||""}getNestedDataValue(e,n){if(!e)return;const r=n.split(".");let i=e;for(const l of r){if(i==null)return;i=i[l]}return i}replaceParams(e,n){let r=e;for(const[i,l]of Object.entries(n)){const u=new RegExp(`\\{\\{${i}\\}\\}`,"g");r=r.replace(u,String(l));const d=new RegExp(`\\{${i}\\}`,"g");r=r.replace(d,String(l))}return r}getFromCache(e){const n=this.cache.get(e);return n?Date.now()-n.timestamp>this.options.cacheTTL?(this.cache.delete(e),null):n.data:null}saveToCache(e,n){this.cache.set(e,{data:n,timestamp:Date.now()})}clearCache(){this.cache.clear(),this.translations.clear()}pruneCache(){const e=Date.now(),n=[];for(const[r,i]of this.cache.entries())e-i.timestamp>this.options.cacheTTL&&n.push(r);for(const r of n)this.cache.delete(r)}getCacheStats(){const e=Date.now();let n=0;for(const r of this.cache.values())e-r.timestamp>this.options.cacheTTL&&n++;return{size:this.cache.size,expired:n}}};$($n,"instance",null),$($n,"TRANSLATION_PATTERN",/\$t:(?:defer:)?([a-zA-Z0-9._-]+)(\|(?:(?!\$t:).)+)?/g),$($n,"NESTED_TRANSLATION_PARAM_PATTERN",/=(\$t:([a-zA-Z0-9._-]+))(?=[|&\s]|$)/g),$($n,"PARAM_PATTERN",/([^=|&]+)=([^|&]+)/g);let Er=$n,od=null;function QS(o){return od||(od=new Er(o)),od}const rp=Object.freeze(Object.defineProperty({__proto__:null,TranslationEngine:Er,TranslationError:sd,getTranslationEngine:QS},Symbol.toStringTag,{value:"Module"})),Yi=dt("PipeRegistry");function ip(o,e){const n=o.getFullYear(),r=String(o.getMonth()+1).padStart(2,"0"),i=String(o.getDate()).padStart(2,"0"),l=String(o.getHours()).padStart(2,"0"),u=String(o.getMinutes()).padStart(2,"0"),d=String(o.getSeconds()).padStart(2,"0");return e.replace("YYYY",String(n)).replace("YY",String(n).slice(-2)).replace("MM",r).replace("M",String(o.getMonth()+1)).replace("DD",i).replace("D",String(o.getDate())).replace("HH",l).replace("H",String(o.getHours())).replace("mm",u).replace("m",String(o.getMinutes())).replace("ss",d).replace("s",String(o.getSeconds()))}function ZS(o,e="ko"){const r=new Date().getTime()-o.getTime(),i=Math.floor(r/1e3),l=Math.floor(i/60),u=Math.floor(l/60),d=Math.floor(u/24),f=Math.floor(d/7),g=Math.floor(d/30),m=Math.floor(d/365);return e==="ko"?i<60?"방금 전":l<60?`${l}분 전`:u<24?`${u}시간 전`:d<7?`${d}일 전`:f<4?`${f}주 전`:g<12?`${g}개월 전`:`${m}년 전`:i<60?"just now":l<60?`${l} minute${l===1?"":"s"} ago`:u<24?`${u} hour${u===1?"":"s"} ago`:d<7?`${d} day${d===1?"":"s"} ago`:f<4?`${f} week${f===1?"":"s"} ago`:g<12?`${g} month${g===1?"":"s"} ago`:`${m} year${m===1?"":"s"} ago`}function ld(o){if(o==null)return null;if(o instanceof Date)return o;if(typeof o=="number")return new Date(o);if(typeof o=="string"){const e=new Date(o);return isNaN(e.getTime())?null:e}return null}const Qs={date:{fn:(o,e="YYYY-MM-DD")=>{const n=ld(o);return n?ip(n,e):""},description:"날짜 포맷 (기본: YYYY-MM-DD)"},datetime:{fn:(o,e="YYYY-MM-DD HH:mm")=>{const n=ld(o);return n?ip(n,e):""},description:"날짜+시간 포맷 (기본: YYYY-MM-DD HH:mm)"},relativeTime:{fn:(o,e="ko")=>{const n=ld(o);return n?ZS(n,e):""},description:'상대 시간 표시 (예: "3분 전")'},number:{fn:(o,e)=>{const n=Number(o);if(isNaN(n))return String(o??"");const r={};return e!==void 0&&(r.minimumFractionDigits=e,r.maximumFractionDigits=e),n.toLocaleString(void 0,r)},description:"숫자 포맷 (천단위 구분, 선택적 소수점)"},truncate:{fn:(o,e=100,n="...")=>typeof o!="string"?String(o??""):o.length<=e?o:o.slice(0,e)+n,description:'문자열 자르기 (기본: 100자, 접미사: "...")'},uppercase:{fn:o=>typeof o!="string"?String(o??""):o.toUpperCase(),description:"대문자 변환"},lowercase:{fn:o=>typeof o!="string"?String(o??""):o.toLowerCase(),description:"소문자 변환"},stripHtml:{fn:o=>typeof o!="string"?String(o??""):o.replace(/<[^>]*>/g,""),description:"HTML 태그 제거"},default:{fn:(o,e="")=>o==null||o===""?e:o,description:"기본값 설정 (null, undefined, 빈문자열 시)"},fallback:{fn:(o,e)=>o??e,description:"폴백 값 설정 (null, undefined 시만)"},first:{fn:o=>{if(Array.isArray(o))return o[0]},description:"배열의 첫 번째 요소"},last:{fn:o=>{if(Array.isArray(o))return o[o.length-1]},description:"배열의 마지막 요소"},join:{fn:(o,e=", ")=>Array.isArray(o)?o.join(e):"",description:'배열을 문자열로 결합 (기본 구분자: ", ")'},length:{fn:o=>Array.isArray(o)||typeof o=="string"?o.length:0,description:"배열/문자열 길이"},filterBy:{fn:(o,e,n)=>Array.isArray(o)?Array.isArray(e)?o.filter(r=>{const i=n?r?.[n]:r;return e.includes(i)}):o:[],description:"배열 필터링 (allowList에 포함된 항목만 반환)"},keys:{fn:o=>o==null||typeof o!="object"?[]:Object.keys(o),description:"객체의 키 배열"},values:{fn:o=>o==null||typeof o!="object"?[]:Object.values(o),description:"객체의 값 배열"},json:{fn:(o,e)=>{try{return JSON.stringify(o,null,e)}catch{return""}},description:"JSON 문자열로 변환"},localized:{fn:(o,e)=>o==null?"":typeof o=="string"?o:typeof o!="object"?String(o):o[e||"ko"]||o.ko||o.en||Object.values(o)[0]||"",description:"다국어 객체에서 로케일에 맞는 값 추출"}},Xi=new Map,yi=class yi{static getInstance(){return yi.instance||(yi.instance=new yi),yi.instance}register(e,n,r){if(Qs[e]){Yi.warn(`[PipeRegistry] 내장 파이프를 덮어쓸 수 없습니다: ${e}`);return}Xi.set(e,{fn:n,description:r}),Yi.log(`[PipeRegistry] 커스텀 파이프 등록됨: ${e}`)}unregister(e){if(Qs[e])return Yi.warn(`[PipeRegistry] 내장 파이프는 해제할 수 없습니다: ${e}`),!1;const n=Xi.delete(e);return n&&Yi.log(`[PipeRegistry] 커스텀 파이프 해제됨: ${e}`),n}get(e){const n=Qs[e];return n?n.fn:Xi.get(e)?.fn}has(e){return!!Qs[e]||Xi.has(e)}execute(e,n,r=[]){const i=this.get(e);if(!i)return Yi.warn(`[PipeRegistry] 알 수 없는 파이프: ${e}`),n;try{return i(n,...r)}catch(l){return Yi.error(`[PipeRegistry] 파이프 실행 오류 (${e}):`,l),n}}list(){const e=[];for(const[n,r]of Object.entries(Qs))e.push({name:n,description:r.description,type:"built-in"});for(const[n,r]of Xi.entries())e.push({name:n,description:r.description,type:"custom"});return e.sort((n,r)=>n.name.localeCompare(r.name))}clearCustomPipes(){Xi.clear()}};$(yi,"instance",null);let Ol=yi;Ol.getInstance();function ew(o){const e=o.trim(),n=e.indexOf("(");if(n===-1)return{name:e,args:[]};const r=e.slice(0,n).trim(),i=e.slice(n+1,-1);if(!i.trim())return{name:r,args:[]};const l=[];let u="",d=null,f=0;for(let g=0;g0?i[g-1]:"")==="\\"){u+=m;continue}if((m==='"'||m==="'")&&!d){d=m;continue}if(m===d){d=null;continue}if(d){u+=m;continue}if(m==="("||m==="["||m==="{"){f++,u+=m;continue}if(m===")"||m==="]"||m==="}"){f--,u+=m;continue}if(m===","&&f===0){l.push(sp(u.trim())),u="";continue}u+=m}return u.trim()&&l.push(sp(u.trim())),{name:r,args:l}}function sp(o){if(o==="null")return null;if(o==="undefined")return;if(o==="true")return!0;if(o==="false")return!1;const e=Number(o);return!isNaN(e)&&o!==""?e:o}function tw(o){const e=[];let n="",r=null,i=0;for(let l=0;l0?o[l-1]:"",f=l0?o[r-1]:"",u=r=2&&o.charCodeAt(0)===64976&&o.charCodeAt(o.length-1)===64977}function lp(o){return o.includes(Ll)}function cp(o){return o.slice(1,-1)}function Ji(o){if(typeof o=="string")return eo(o);if(Array.isArray(o))return o.map(Ji);if(o&&typeof o=="object"){const e={};for(const[n,r]of Object.entries(o))e[n]=Ji(r);return e}return o}const to=dt("DataBindingEngine");function Ml(){try{return window.G7Core?.devTools}catch{return}}class cd extends Error{constructor(n,r,i){super(n);$(this,"path");$(this,"context");this.path=r,this.context=i,this.name="DataBindingError"}}const wa=class wa{constructor(e){$(this,"cache",new Map);$(this,"expressionFnCache",new Map);$(this,"renderCycleCache",new Map);$(this,"currentRenderCycleId",0);$(this,"defaultOptions",{defaultValue:void 0,nullSafe:!0,detectCircular:!0,maxDepth:10});e&&(this.defaultOptions={...this.defaultOptions,...e})}startRenderCycle(){this.currentRenderCycleId++,this.renderCycleCache.clear()}isRenderCycleCacheActive(){return this.currentRenderCycleId>0}getFromRenderCycleCache(e){if(this.isRenderCycleCacheActive())return this.renderCycleCache.get(e)}saveToRenderCycleCache(e,n){this.isRenderCycleCacheActive()&&this.renderCycleCache.set(e,n)}resolveBindings(e,n,r,i){const l={...this.defaultOptions,...r},u=Ml(),d=n._computed&&!n.$computed?{...n,$computed:n._computed}:n;return e.replace(wa.BINDING_PATTERN,(f,g)=>{const m=g.trim();let b=!1,v=m;if(m.startsWith(Na)&&(b=!0,v=m.slice(Na.length)),ci(v)){const T=u?.isEnabled()?performance.now():0;try{const[D,j]=tw(v);let H,P=!1;const X=/[?:|&!+\-*/<>=()]/.test(D)||/\[['"]/.test(D),pe=D.startsWith("_global")||D.startsWith("_local")||D.startsWith("_isolated")||D.startsWith("$parent");if(l.skipCache)X?H=this.evaluateExpression(D,d):H=this.resolvePath(D,d,l);else if(X){const Me=this.getFromRenderCycleCache(`expr:${D}`);Me!==void 0?(H=Me,P=!0):(H=this.evaluateExpression(D,d),this.saveToRenderCycleCache(`expr:${D}`,H))}else if(pe){const Me=this.getFromRenderCycleCache(D);Me!==void 0?(H=Me,P=!0):(H=this.resolvePath(D,d,l),this.saveToRenderCycleCache(D,H))}else{const Me=this.getFromCache(D);Me!==void 0?(H=Me,P=!0):(H=this.resolvePath(D,d,l),this.saveToCache(D,H))}const _e=nw(H,j);if(u?.isEnabled()){const Me=performance.now()-T;u.trackExpressionEval({expression:`{{${m}}}`,result:this.sanitizeResultForTracking(_e),resultType:this.getResultType(_e),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:P,duration:Me,method:"resolveBindings",skipCache:l.skipCache})}const we=this.formatValue(_e);return b?eo(we):we}catch(D){return to.error("Pipe expression evaluation failed:",v,D),f}}if(/[?:&!+\-*/<>=()]/.test(v)||/\|\|/.test(v)||/\[['"]/.test(v)){const T=u?.isEnabled()?performance.now():0;try{let D,j=!1;if(l.skipCache)D=this.evaluateExpression(v,d);else{const P=`expr:${v}`,X=this.getFromRenderCycleCache(P);X!==void 0?(D=X,j=!0):(D=this.evaluateExpression(v,d),this.saveToRenderCycleCache(P,D))}if(u?.isEnabled()){const P=performance.now()-T;u.trackExpressionEval({expression:`{{${m}}}`,result:this.sanitizeResultForTracking(D),resultType:this.getResultType(D),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:j,duration:P,method:"resolveBindings",skipCache:l.skipCache})}const H=this.formatValue(D);return b?eo(H):H}catch(D){return to.error("Expression evaluation failed:",v,D),f}}if(l.skipCache){const T=u?.isEnabled()?performance.now():0,D=this.resolvePath(v,d,l);if(u?.isEnabled()){const H=performance.now()-T;u.trackExpressionEval({expression:`{{${m}}}`,result:this.sanitizeResultForTracking(D),resultType:this.getResultType(D),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:!1,duration:H,method:"resolveBindings",skipCache:!0})}const j=this.formatValue(D);return b?eo(j):j}const _=v.startsWith("_global")||v.startsWith("_local")||v.startsWith("_isolated")||v.startsWith("$parent"),x=u?.isEnabled()?performance.now():0;let k,O=!1;if(_){const T=this.getFromRenderCycleCache(v);T!==void 0?(k=T,O=!0):(k=this.resolvePath(v,d,l),this.saveToRenderCycleCache(v,k))}else{const T=this.getFromCache(v);T!==void 0?(k=T,O=!0):(k=this.resolvePath(v,d,l),this.saveToCache(v,k))}if(u?.isEnabled()){const T=performance.now()-x;u.trackExpressionEval({expression:`{{${m}}}`,result:this.sanitizeResultForTracking(k),resultType:this.getResultType(k),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:O,duration:T,method:"resolveBindings",skipCache:l.skipCache})}const M=this.formatValue(k);return b?eo(M):M})}resolve(e,n,r,i){const l={...this.defaultOptions,...r},u=Ml(),d=u?.isEnabled()?performance.now():0;if(l.skipCache){const b=this.resolvePath(e,n,l);return u?.isEnabled()&&u.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(b),resultType:this.getResultType(b),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:!1,duration:performance.now()-d,method:"resolve",skipCache:!0}),b}const f=e.startsWith("_global")||e.startsWith("_local")||e.startsWith("_isolated")||e.startsWith("$parent");let g=!1;if(f){const b=this.getFromRenderCycleCache(e);if(b!==void 0)return g=!0,u?.isEnabled()&&u.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(b),resultType:this.getResultType(b),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:!0,duration:performance.now()-d,method:"resolve",skipCache:l.skipCache}),b}else{const b=this.getFromCache(e);if(b!==void 0)return g=!0,u?.isEnabled()&&u.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(b),resultType:this.getResultType(b),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:!0,duration:performance.now()-d,method:"resolve",skipCache:l.skipCache}),b}const m=this.resolvePath(e,n,l);return f?this.saveToRenderCycleCache(e,m):this.saveToCache(e,m),u?.isEnabled()&&u.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(m),resultType:this.getResultType(m),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:g,duration:performance.now()-d,method:"resolve",skipCache:l.skipCache}),m}resolvePath(e,n,r,i=0,l=new WeakSet){if(r.maxDepth&&i>r.maxDepth){if(r.detectCircular)throw new cd(`Maximum depth exceeded (${r.maxDepth}). Possible circular reference.`,e,n);return r.defaultValue}const u=this.parsePath(e);let d=n;for(let f=0;fwa.CACHE_EXPIRY){this.cache.delete(e),r?.isEnabled()&&r.recordCacheMiss();return}return r?.isEnabled()&&r.recordCacheHit(),n.value}saveToCache(e,n){this.cache.set(e,{value:n,timestamp:Date.now()})}isActionDefinition(e){return typeof e.handler!="string"?!1:e.params!==void 0||Array.isArray(e.actions)||typeof e.target=="string"||e.onSuccess!==void 0||e.onError!==void 0}extractSingleBinding(e){if(!e.startsWith("{{")||!e.endsWith("}}")||e.length<5)return null;const n=e.slice(2,-2);let r=0;for(let i=0;i0)r--;else if(n[i+1]==="}")return null}}return n}resolveObject(e,n,r){if(this.isSwitchExpression(e)){const d=e;return this.resolveSwitch(d,n,r)}if(this.isActionDefinition(e))return{...e};if("iteration"in e)return{...e};const i={},u=[...["cellChildren","expandChildren","expandContext","render"],...r?.skipBindingKeys||[]];for(const[d,f]of Object.entries(e)){if(u.includes(d)){i[d]=f;continue}if(typeof f=="string"){const g=this.extractSingleBinding(f);if(g!==null){const m=g.trim();let b=!1,v=m;m.startsWith(Na)&&(b=!0,v=m.slice(Na.length));const S=/[?:|&!+\-*/<>=()]/.test(v)||/\[['"]/.test(v),_=ci(v)?this.resolveBindings(`{{${v}}}`,n,r):S?this.evaluateExpression(v,n,r):this.resolve(v,n,r);i[d]=b&&_!=null?Ji(_):_}else i[d]=this.resolveBindings(f,n,r)}else Array.isArray(f)?i[d]=f.map(g=>typeof g=="string"?this.resolveBindings(g,n,r):typeof g=="object"&&g!==null?this.resolveObject(g,n,r):g):f&&typeof f=="object"?i[d]=this.resolveObject(f,n,r):i[d]=f}return i}clearCache(){this.cache.clear(),this.expressionFnCache.clear()}invalidateCacheByKeys(e){for(const n of this.cache.keys())for(const r of e)if(n===r||n.startsWith(`${r}.`)||n.startsWith(`${r}[`)){this.cache.delete(n);break}}pruneCache(){const e=Date.now();for(const[n,r]of this.cache.entries())e-r.timestamp>wa.CACHE_EXPIRY&&this.cache.delete(n)}getCacheStats(){const e=Date.now();let n=0;for(const r of this.cache.values())e-r.timestamp>wa.CACHE_EXPIRY&&n++;return{size:this.cache.size,expired:n}}evaluateExpression(e,n,r){const i=Ml(),l=i?.isEnabled()?performance.now():0;i?.isEnabled()&&i.trackBindingEval();try{let u=this.preprocessOptionalChaining(e);u=this.preprocessTranslationTokens(u);const d=this.extractVariablesFromExpression(u),f={...n};for(const D of d)D in f||(f[D]=void 0);n._computed&&!f.$computed&&(f.$computed=n._computed);let g=n.$templateId,m=n.$locale;if(typeof window<"u"&&(!g||!m)){const D=window.__templateApp?.getConfig?.();g??(g=D?.templateId),m??(m=D?.locale)}const b=m||"ko";f.$localized=(D,j)=>{if(D==null&&!j)return"";if(typeof D=="string")return D;if(D&&typeof D=="object"&&D[b])return D[b];if(j&&typeof j=="string"){const H=f.$t?f.$t(j):j;if(H&&H!==j)return H}return D&&typeof D=="object"?D.ko||D.en||Object.values(D)[0]||"":D==null?"":String(D)};const v=typeof window<"u"?window.G7Core:void 0;f.$uuid=()=>v?.uuid?v.uuid():typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,D=>{const j=Math.random()*16|0;return(D==="x"?j:j&3|8).toString(16)});const S={templateId:g||"",locale:b};f.$t=D=>{if(!D||typeof D!="string")return"";try{return Er.getInstance().translate(D,S)}catch(j){return to.warn("$t() translation failed for key:",D,j),D}},f.$get=(D,j,H=void 0)=>{if(D==null)return H;const P=Array.isArray(j)?j:[j];if(P.length===0)return D;let X=D;for(const pe of P){if(X==null||pe==null)return H;X=X[pe]}return X??H};const _=Object.keys(f),x=Object.values(f),k=`${u}|${_.join(",")}`;let O=this.expressionFnCache.get(k);const M=!!O;O||(O=new Function(..._,`return (${u});`),this.expressionFnCache.set(k,O));const T=O(...x);if(i?.isEnabled()){const D=performance.now()-l;i.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(T),resultType:this.getResultType(T),componentId:r?.componentId,componentName:r?.componentName,propName:r?.propName,fromCache:M,duration:D,method:"evaluateExpression",skipCache:r?.skipCache})}return T}catch(u){throw new Error(`Failed to evaluate expression "${e}": ${u instanceof Error?u.message:String(u)}`)}}getResultType(e){return e===null?"null":e===void 0?"undefined":Array.isArray(e)?"array":typeof e}sanitizeResultForTracking(e){if(e==null||typeof e!="object")return e;try{if(Array.isArray(e))return e.length>10?`[Array(${e.length})]`:e.slice(0,10);const n=Object.keys(e);return n.length>20?`{Object(${n.length} keys)}`:(JSON.stringify(e),e)}catch{return"[Complex Object]"}}preprocessTranslationTokens(e){return e=e.replace(/(['"])(\$t:([a-zA-Z_][a-zA-Z0-9_.\-]*))\1/g,(n,r,i,l)=>`$t('${l}')`),e.replace(/(?(n.push(l),`__STRING_LITERAL_${n.length-1}__`));const i=[];return r=r.replace(/\$t:[a-zA-Z_][a-zA-Z0-9_.\-]*(?:\|[^'"\s,)]+)?/g,l=>(i.push(l),`__TRANSLATION_TOKEN_${i.length-1}__`)),r=r.replace(/([a-zA-Z_$][a-zA-Z0-9_$]*)\.(?!\?)/g,"$1?."),r=r.replace(/__TRANSLATION_TOKEN_(\d+)__/g,(l,u)=>i[parseInt(u,10)]),r=r.replace(/__STRING_LITERAL_(\d+)__/g,(l,u)=>n[parseInt(u,10)]),r}extractVariablesFromExpression(e){const n=new Set(["true","false","null","undefined","NaN","Infinity","if","else","for","while","do","switch","case","break","continue","return","function","class","const","let","var","new","delete","typeof","instanceof","this","super","import","export","default","try","catch","finally","throw","Math","Date","JSON","Array","Object","String","Number","Boolean","RegExp","Set","Map","WeakSet","WeakMap","Symbol","Promise","BigInt","Error","parseInt","parseFloat","isNaN","isFinite","encodeURI","decodeURI","encodeURIComponent","decodeURIComponent"]),r=/(?{n!==null&&clearTimeout(n),n=setTimeout(()=>{o(...r)},e)})}class iw{constructor(){$(this,"subscribers",new Set);$(this,"currentWidth",1024);$(this,"debouncedHandler",null);$(this,"isInitialized",!1);this.initialize()}initialize(){typeof window>"u"||(this.currentWidth=window.innerWidth,this.isInitialized=!0,this.debouncedHandler=rw(()=>{this.currentWidth=window.innerWidth,this.notifySubscribers()},150),window.addEventListener("resize",this.debouncedHandler))}notifySubscribers(){this.subscribers.forEach(e=>{e(this.currentWidth)})}subscribe(e){return this.subscribers.add(e),e(this.currentWidth),()=>{this.subscribers.delete(e)}}getWidth(){return this.currentWidth}parseRange(e){if(Nl.has(e))return Nl.get(e)??null;let n=null;if($l[e])n={...$l[e]};else{const r=e.match(/^(-?\d*)-(-?\d*)$/);if(r){const[,i,l]=r,u=i===""?0:parseInt(i,10),d=l===""?1/0:parseInt(l,10);!isNaN(u)&&!isNaN(d)&&u<=d&&(n={min:u,max:d})}}return Nl.set(e,n),n}getMatchingKey(e,n){const r=[];for(const i of Object.keys(e)){const l=this.parseRange(i);l&&n>=l.min&&n<=l.max&&r.push({key:i,range:l,isPreset:!!$l[i]})}return r.length===0?null:(r.sort((i,l)=>{if(i.isPreset!==l.isPreset)return i.isPreset?1:-1;const u=i.range.max-i.range.min,d=l.range.max-l.range.min;return u-d}),r[0].key)}matches(e){const n=this.parseRange(e);return n?this.currentWidth>=n.min&&this.currentWidth<=n.max:!1}clearSubscribers(){this.subscribers.clear()}destroy(){this.debouncedHandler&&typeof window<"u"&&window.removeEventListener("resize",this.debouncedHandler),this.clearSubscribers(),Nl.clear()}_setWidthForTesting(e){this.currentWidth=e,this.notifySubscribers()}}const ui=new iw,Il=dt("ConditionEvaluator");function sw(o){switch(o){case"true":return{value:!0};case"false":return{value:!1};case"null":return{value:null};case"undefined":return{value:void 0};default:return}}function ow(o){return/[?:|&!+\-*/<>=()]/.test(o)}function lw(o){if(!o.startsWith("{{")||!o.endsWith("}}"))return null;const e=o.slice(2,-2);let n=null,r=0;for(let i=0;i0?e[i-1]:"")!=="\\"&&((l==='"'||l==="'")&&!n?n=l:l===n&&(n=null),!n&&(l==="{"&&r++,l==="}"&&r--,r<0)))return null}return r===0?e.trim():null}function cw(o,e,n){if(!o)return!0;try{const r=lw(o);let i;if(r!==null){const l=sw(r);l!==void 0?i=l.value:ci(r)?i=n.resolveBindings(`{{${r}}}`,e,{skipCache:!0}):ow(r)?i=n.evaluateExpression(r,e):i=n.resolve(r,e,{skipCache:!0})}else i=n.resolveBindings(o,e,{skipCache:!0});if(typeof i=="string"){const l=i.toLowerCase().trim();if(l==="false"||l==="0"||l===""||l==="null"||l==="undefined")return!1}return!!i}catch(r){return Il.warn(`evaluateStringCondition: 조건 평가 실패: ${o}`,r),!1}}function Hl(o,e,n){if(typeof o=="string")return cw(o,e,n);if("and"in o){if(!Array.isArray(o.and)||o.and.length===0)return Il.warn("evaluateConditionExpression: AND 그룹이 비어있습니다"),!0;for(const r of o.and)if(!Hl(r,e,n))return!1;return!0}if("or"in o){if(!Array.isArray(o.or)||o.or.length===0)return Il.warn("evaluateConditionExpression: OR 그룹이 비어있습니다"),!1;for(const r of o.or)if(Hl(r,e,n))return!0;return!1}return Il.warn("evaluateConditionExpression: 알 수 없는 조건 형식",o),!1}function up(o,e,n){if(!Array.isArray(o)||o.length===0)return{matched:!1,branchIndex:-1};for(let r=0;r=()[\]{}]/.test(o)}function hp(o){if(!o.startsWith("{{")||!o.endsWith("}}"))return null;const e=o.slice(2,-2);let n=null,r=0;for(let i=0;i0?e[i-1]:"")!=="\\"&&((l==='"'||l==="'")&&!n?n=l:l===n&&(n=null),!n&&(l==="{"&&r++,l==="}"&&r--,r<0)))return null}return r===0?e.trim():null}function dd(o,e,n){let r=o;if(o.startsWith("{{")&&o.endsWith("}}")&&(r=o.slice(2,-2).trim()),ud(r))try{return n.evaluateExpression(r,e)}catch(i){Ja.warn(`resolveIterationSource: 표현식 평가 실패: ${o}`,i);return}return n.resolve(r,e,{skipCache:!0})}function hw(o,e){const n={...o};if(e?.parentDataContext)for(const[r,i]of Object.entries(e.parentDataContext))r in n||(n[r]=i);if(e?.state){const r=n._local||{};n._local={...r,...e.state}}return e?.isolatedContext?.state&&(n._isolated=e.isolatedContext.state),n}function fd(o,e,n,r){if(!e||!Array.isArray(e)||e.length===0)return o;const i=r?.actionDispatcher??lm(),l={...o,actions:e},u=i.bindActionsToProps(l,n,r?.componentContext);return delete u.actions,u}function gp(o,e,n,r){if(typeof o=="boolean")return o;if(!o)return!0;try{const i=hp(o);let l;if(i!==null){const u=fw.get(i);u!==void 0?l=u:ci(i)?l=n.resolveBindings(`{{${i}}}`,e,{skipCache:!0}):ud(i)?l=n.evaluateExpression(i,e):l=n.resolve(i,e,{skipCache:!0})}else l=n.resolveBindings(o,e,{skipCache:!0});if(typeof l=="string"){const u=l.toLowerCase().trim();if(u==="false"||u==="0"||u===""||u==="null"||u==="undefined")return!1}return!!l}catch(i){return Ja.warn(`evaluateIfCondition: 조건 평가 실패 (컴포넌트: ${r||"unknown"}):`,i),!1}}function Qi(o,e,n,r){if(o.if!==void 0)return gp(o.if,e,n,r);if(o.condition!==void 0)return gp(o.condition,e,n,r);if(o.conditions===void 0)return!0;const i=o.conditions;try{return uw(i)?Hl(i,e,n):dw(i)?up(i,e,n).matched:(Ja.warn(`evaluateRenderCondition: 알 수 없는 conditions 형식 (컴포넌트: ${r||"unknown"})`),!0)}catch(l){return Ja.warn(`evaluateRenderCondition: conditions 평가 실패 (컴포넌트: ${r||"unknown"}):`,l),!1}}function pp(o){if(!o.responsive)return o;const e=ui.getWidth(),n=ui.getMatchingKey(o.responsive,e);if(!n)return o;const r=o.responsive[n];return{...o,props:{...o.props,...r.props},children:r.children??o.children,text:r.text??o.text,if:r.if??o.if,iteration:r.iteration??o.iteration}}function no(o,e,n,r,i){if(!o||o.length===0)return[];const l=i?.bindingEngine??new Rn,u=i?.translationEngine??Er.getInstance(),d=i?.translationContext??{templateId:"",locale:"ko"},f=hw(e,i?.componentContext),g=(v,S)=>{if(typeof v=="string"){if(op(v))return cp(v);if(lp(v)){const x=[],k=v.replace(new RegExp(`${Ll}([^${Zs}]*)${Zs}`,"g"),(M,T)=>(x.push(T),`${_r}${x.length-1}${_r}`));let O=k;return/\$t:[a-zA-Z0-9._-]+/.test(k)&&(O=u.resolveTranslations(k,d,S)),O.replace(new RegExp(`${_r}(\\d+)${_r}`,"g"),(M,T)=>x[parseInt(T)])}if(v.startsWith("$t:defer:")){const x="$t:"+v.slice(9);return u.resolveTranslations(x,d,S)}if(v.startsWith("$t:"))return u.resolveTranslations(v,d,S);const _=hp(v);if(_!==null){let x=!1,k=_;_.startsWith(Na)&&(x=!0,k=_.slice(Na.length));let O;if(ci(k))O=l.resolveBindings(`{{${k}}}`,S,{skipCache:!0});else if(ud(k))try{O=l.evaluateExpression(k,S)}catch(M){Ja.warn("renderItemChildren: 표현식 평가 실패:",M);return}else O=l.resolve(k,S,{skipCache:!0});return!x&&typeof O=="string"&&/\$t:[a-zA-Z0-9._-]+/.test(O)&&(O=u.resolveTranslations(O,d,S)),x&&O!=null?Ji(O):O}if(v.includes("{{")){const x=l.resolveBindings(v,S,{skipCache:!0});return typeof x=="string"&&/\$t:[a-zA-Z0-9._-]+/.test(x)?u.resolveTranslations(x,d,S):x}return v}if(Array.isArray(v))return v.map(_=>g(_,S));if(v&&typeof v=="object"){const _={};for(const[x,k]of Object.entries(v))_[x]=g(k,S);return _}return v},m=(v,S)=>{if(!v)return{};const _={};for(const[x,k]of Object.entries(v))_[x]=g(k,S);return _},b=(v,S,_)=>{const x=pp(v),k=x.iteration;if(!k)return[];const O=dd(k.source,_,l);if(!Array.isArray(O))return Ja.warn(`renderItemChildren: iteration.source가 배열이 아닙니다: ${k.source}`),[];const M=dp();if(M?.isEnabled()){const D=`${S}-iteration`;M.trackIteration(D,k.source,k.item_var,k.index_var,O.length)}const T=n[x.name];return T?O.flatMap((D,j)=>{const H={..._,[k.item_var]:D,[`${k.item_var}_index`]:j,...k.index_var?{[k.index_var]:j}:{}},P=Qi({if:x.if,condition:x.condition,conditions:x.conditions},H,l,x.id);if(x.if&&M?.isEnabled()){const Je=`${S}-iter-${j}-if`;M.trackIfCondition(Je,x.if,P,x.name)}if(!P)return[];const X=x.id?String(g(x.id,H)):void 0,pe=`${S}-iter-${j}`,_e=i?.getRemountKey?i.getRemountKey(X,pe):pe,we=m(x.props,H),Me=fd(we,x.actions,H,{actionDispatcher:i?.actionDispatcher,componentContext:i?.componentContext});let qe=null;return x.text!==void 0?qe=g(x.text,H):x.children&&x.children.length>0&&(qe=no(x.children,H,n,_e,i)),M?.isEnabled()&&M.trackRender(x.name),[Xe.createElement(T,{key:_e,...Me},qe)]}):(Ja.warn(`renderItemChildren: 컴포넌트를 찾을 수 없습니다: ${x.name}`),[])};return o.flatMap((v,S)=>{const _=pp(v),x=_.id?String(g(_.id,f)):void 0,k=r?`${r}-${x||S}`:x||`child-${S}`,O=i?.getRemountKey?i.getRemountKey(x,k):k;if(_.iteration)return b(_,O,f);const M=Qi({if:_.if,condition:_.condition,conditions:_.conditions},f,l,_.id),T=dp();if(_.if&&T?.isEnabled()){const X=`${O}-if`;T.trackIfCondition(X,_.if,M,_.name)}if(!M)return[];const D=n[_.name];if(!D)return Ja.warn(`renderItemChildren: 컴포넌트를 찾을 수 없습니다: ${_.name}`),[];const j=m(_.props,f),H=fd(j,_.actions,f,{actionDispatcher:i?.actionDispatcher,componentContext:i?.componentContext});let P=null;return _.text!==void 0?P=g(_.text,f):_.children&&_.children.length>0&&(P=no(_.children,f,n,O,i)),T?.isEnabled()&&T.trackRender(_.name),[Xe.createElement(D,{key:O,...H},P)]})}function Zi(o,e,n,r){let i,l;return n instanceof Rn?(i=n,l=r):(i=fp,l=n),i.resolveBindings(o,e,l)}function gw(o,e,n,r){const i=n??fp,l={skipCache:!0,...r};let u;try{u=i.resolveBindings(o.key,e,{skipCache:l.skipCache})?.toString()?.trim()??""}catch(g){Ja.warn("resolveClassMap: key 평가 실패:",o.key,g),u=""}let d="";u&&o.variants&&u in o.variants?d=o.variants[u]:o.default&&(d=o.default);const f=[];return o.base?.trim()&&f.push(o.base.trim()),d?.trim()&&f.push(d.trim()),f.join(" ")}function mp(o,e){return function(){return o.apply(e,arguments)}}const{toString:pw}=Object.prototype,{getPrototypeOf:es}=Object,{iterator:ao,toStringTag:yp}=Symbol,zl=(({hasOwnProperty:o})=>(e,n)=>o.call(e,n))(Object.prototype),ro=(o,e)=>{let n=o;const r=[];for(;n!=null&&n!==Object.prototype;){if(r.indexOf(n)!==-1)return!1;if(r.push(n),zl(n,e))return!0;n=es(n)}return!1},mw=(o,e)=>o!=null&&ro(o,e)?o[e]:void 0,hd=(o=>e=>{const n=pw.call(e);return o[n]||(o[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),ha=o=>(o=o.toLowerCase(),e=>hd(e)===o),jl=o=>e=>typeof e===o,{isArray:di}=Array,ts=jl("undefined");function ns(o){return o!==null&&!ts(o)&&o.constructor!==null&&!ts(o.constructor)&&Ln(o.constructor.isBuffer)&&o.constructor.isBuffer(o)}const bp=ha("ArrayBuffer");function yw(o){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(o):e=o&&o.buffer&&bp(o.buffer),e}const bw=jl("string"),Ln=jl("function"),vp=jl("number"),as=o=>o!==null&&typeof o=="object",vw=o=>o===!0||o===!1,Ul=o=>{if(!as(o))return!1;const e=es(o);return(e===null||e===Object.prototype||es(e)===null)&&!ro(o,yp)&&!ro(o,ao)},Sw=o=>{if(!as(o)||ns(o))return!1;try{return Object.keys(o).length===0&&Object.getPrototypeOf(o)===Object.prototype}catch{return!1}},ww=ha("Date"),Cw=ha("File"),Ew=o=>!!(o&&typeof o.uri<"u"),_w=o=>o&&typeof o.getParts<"u",Aw=ha("Blob"),xw=ha("FileList"),Tw=o=>as(o)&&Ln(o.pipe);function Rw(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}}const Sp=Rw(),wp=typeof Sp.FormData<"u"?Sp.FormData:void 0,kw=o=>{if(!o)return!1;if(wp&&o instanceof wp)return!0;const e=es(o);if(!e||e===Object.prototype||!Ln(o.append))return!1;const n=hd(o);return n==="formdata"||n==="object"&&Ln(o.toString)&&o.toString()==="[object FormData]"},Dw=ha("URLSearchParams"),[Ow,Lw,Mw,$w]=["ReadableStream","Request","Response","Headers"].map(ha),Nw=o=>o.trim?o.trim():o.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function io(o,e,{allOwnKeys:n=!1}={}){if(o===null||typeof o>"u")return;let r,i;if(typeof o!="object"&&(o=[o]),di(o))for(r=0,i=o.length;r0;)if(i=n[r],e===i.toLowerCase())return i;return null}const fi=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Ep=o=>!ts(o)&&o!==fi;function gd(...o){const{caseless:e,skipUndefined:n}=Ep(this)&&this||{},r={},i=(l,u)=>{if(u==="__proto__"||u==="constructor"||u==="prototype")return;const d=e&&typeof u=="string"&&Cp(r,u)||u,f=zl(r,d)?r[d]:void 0;Ul(f)&&Ul(l)?r[d]=gd(f,l):Ul(l)?r[d]=gd({},l):di(l)?r[d]=l.slice():(!n||!ts(l))&&(r[d]=l)};for(let l=0,u=o.length;l(io(e,(i,l)=>{n&&Ln(i)?Object.defineProperty(o,l,{__proto__:null,value:mp(i,n),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(o,l,{__proto__:null,value:i,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:r}),o),Hw=o=>(o.charCodeAt(0)===65279&&(o=o.slice(1)),o),zw=(o,e,n,r)=>{o.prototype=Object.create(e.prototype,r),Object.defineProperty(o.prototype,"constructor",{__proto__:null,value:o,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(o,"super",{__proto__:null,value:e.prototype}),n&&Object.assign(o.prototype,n)},jw=(o,e,n,r)=>{let i,l,u;const d={};if(e=e||{},o==null)return e;do{for(i=Object.getOwnPropertyNames(o),l=i.length;l-- >0;)u=i[l],(!r||r(u,o,e))&&!d[u]&&(e[u]=o[u],d[u]=!0);o=n!==!1&&es(o)}while(o&&(!n||n(o,e))&&o!==Object.prototype);return e},Uw=(o,e,n)=>{o=String(o),(n===void 0||n>o.length)&&(n=o.length),n-=e.length;const r=o.indexOf(e,n);return r!==-1&&r===n},Bw=o=>{if(!o)return null;if(di(o))return o;let e=o.length;if(!vp(e))return null;const n=new Array(e);for(;e-- >0;)n[e]=o[e];return n},Pw=(o=>e=>o&&e instanceof o)(typeof Uint8Array<"u"&&es(Uint8Array)),qw=(o,e)=>{const r=(o&&o[ao]).call(o);let i;for(;(i=r.next())&&!i.done;){const l=i.value;e.call(o,l[0],l[1])}},Gw=(o,e)=>{let n;const r=[];for(;(n=o.exec(e))!==null;)r.push(n);return r},Vw=ha("HTMLFormElement"),Fw=o=>o.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,i){return r.toUpperCase()+i}),{propertyIsEnumerable:Kw}=Object.prototype,Ww=ha("RegExp"),_p=(o,e)=>{const n=Object.getOwnPropertyDescriptors(o),r={};io(n,(i,l)=>{let u;(u=e(i,l,o))!==!1&&(r[l]=u||i)}),Object.defineProperties(o,r)},Yw=o=>{_p(o,(e,n)=>{if(Ln(o)&&["arguments","caller","callee"].includes(n))return!1;const r=o[n];if(Ln(r)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},Xw=(o,e)=>{const n={},r=i=>{i.forEach(l=>{n[l]=!0})};return di(o)?r(o):r(String(o).split(e)),n},Jw=()=>{},Qw=(o,e)=>o!=null&&Number.isFinite(o=+o)?o:e;function Zw(o){return!!(o&&Ln(o.append)&&o[yp]==="FormData"&&o[ao])}const e0=o=>{const e=new WeakSet,n=r=>{if(as(r)){if(e.has(r))return;if(ns(r))return r;if(!("toJSON"in r)){e.add(r);const i=di(r)?[]:{};return io(r,(l,u)=>{const d=n(l);!ts(d)&&(i[u]=d)}),e.delete(r),i}}return r};return n(o)},t0=ha("AsyncFunction"),n0=o=>o&&(as(o)||Ln(o))&&Ln(o.then)&&Ln(o.catch),Ap=((o,e)=>o?setImmediate:e?((n,r)=>(fi.addEventListener("message",({source:i,data:l})=>{i===fi&&l===n&&r.length&&r.shift()()},!1),i=>{r.push(i),fi.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",Ln(fi.postMessage)),a0=typeof queueMicrotask<"u"?queueMicrotask.bind(fi):typeof process<"u"&&process.nextTick||Ap,xp=o=>o!=null&&Ln(o[ao]),V={isArray:di,isArrayBuffer:bp,isBuffer:ns,isFormData:kw,isArrayBufferView:yw,isString:bw,isNumber:vp,isBoolean:vw,isObject:as,isPlainObject:Ul,isEmptyObject:Sw,isReadableStream:Ow,isRequest:Lw,isResponse:Mw,isHeaders:$w,isUndefined:ts,isDate:ww,isFile:Cw,isReactNativeBlob:Ew,isReactNative:_w,isBlob:Aw,isRegExp:Ww,isFunction:Ln,isStream:Tw,isURLSearchParams:Dw,isTypedArray:Pw,isFileList:xw,forEach:io,merge:gd,extend:Iw,trim:Nw,stripBOM:Hw,inherits:zw,toFlatObject:jw,kindOf:hd,kindOfTest:ha,endsWith:Uw,toArray:Bw,forEachEntry:qw,matchAll:Gw,isHTMLForm:Vw,hasOwnProperty:zl,hasOwnProp:zl,hasOwnInPrototypeChain:ro,getSafeProp:mw,reduceDescriptors:_p,freezeMethods:Yw,toObjectSet:Xw,toCamelCase:Fw,noop:Jw,toFiniteNumber:Qw,findKey:Cp,global:fi,isContextDefined:Ep,isSpecCompliantForm:Zw,toJSONObject:e0,isAsyncFn:t0,isThenable:n0,setImmediate:Ap,asap:a0,isIterable:xp,isSafeIterable:o=>o!=null&&ro(o,ao)&&xp(o)},r0=V.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),i0=o=>{const e={};let n,r,i;return o&&o.split(` +`).forEach(function(u){i=u.indexOf(":"),n=u.substring(0,i).trim().toLowerCase(),r=u.substring(i+1).trim(),!(!n||e[n]&&r0[n])&&(n==="set-cookie"?e[n]?e[n].push(r):e[n]=[r]:e[n]=e[n]?e[n]+", "+r:r)}),e};function s0(o){let e=0,n=o.length;for(;ee;){const r=o.charCodeAt(n-1);if(r!==9&&r!==32)break;n-=1}return e===0&&n===o.length?o:o.slice(e,n)}const o0=new RegExp("[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+","g"),l0=new RegExp("[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+","g");function pd(o,e){return V.isArray(o)?o.map(n=>pd(n,e)):s0(String(o).replace(e,""))}const c0=o=>pd(o,o0),u0=o=>pd(o,l0);function Tp(o){const e=Object.create(null);return V.forEach(o.toJSON(),(n,r)=>{e[r]=u0(n)}),e}const Rp=Symbol("internals");function so(o){return o&&String(o).trim().toLowerCase()}function Bl(o){return o===!1||o==null?o:V.isArray(o)?o.map(Bl):c0(String(o))}function d0(o){const e=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(o);)e[r[1]]=r[2];return e}const f0=o=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(o.trim());function md(o,e,n,r,i){if(V.isFunction(r))return r.call(this,e,n);if(i&&(e=n),!!V.isString(e)){if(V.isString(r))return e.indexOf(r)!==-1;if(V.isRegExp(r))return r.test(e)}}function h0(o){return o.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,n,r)=>n.toUpperCase()+r)}function g0(o,e){const n=V.toCamelCase(" "+e);["get","set","has"].forEach(r=>{Object.defineProperty(o,r+n,{__proto__:null,value:function(i,l,u){return this[r].call(this,e,i,l,u)},configurable:!0})})}let Cn=class{constructor(e){e&&this.set(e)}set(e,n,r){const i=this;function l(d,f,g){const m=so(f);if(!m)return;const b=V.findKey(i,m);(!b||i[b]===void 0||g===!0||g===void 0&&i[b]!==!1)&&(i[b||f]=Bl(d))}const u=(d,f)=>V.forEach(d,(g,m)=>l(g,m,f));if(V.isPlainObject(e)||e instanceof this.constructor)u(e,n);else if(V.isString(e)&&(e=e.trim())&&!f0(e))u(i0(e),n);else if(V.isObject(e)&&V.isSafeIterable(e)){let d=Object.create(null),f,g;for(const m of e){if(!V.isArray(m))throw new TypeError("Object iterator must return a key-value pair");g=m[0],V.hasOwnProp(d,g)?(f=d[g],d[g]=V.isArray(f)?[...f,m[1]]:[f,m[1]]):d[g]=m[1]}u(d,n)}else e!=null&&l(n,e,r);return this}get(e,n){if(e=so(e),e){const r=V.findKey(this,e);if(r){const i=this[r];if(!n)return i;if(n===!0)return d0(i);if(V.isFunction(n))return n.call(this,i,r);if(V.isRegExp(n))return n.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,n){if(e=so(e),e){const r=V.findKey(this,e);return!!(r&&this[r]!==void 0&&(!n||md(this,this[r],r,n)))}return!1}delete(e,n){const r=this;let i=!1;function l(u){if(u=so(u),u){const d=V.findKey(r,u);d&&(!n||md(r,r[d],d,n))&&(delete r[d],i=!0)}}return V.isArray(e)?e.forEach(l):l(e),i}clear(e){const n=Object.keys(this);let r=n.length,i=!1;for(;r--;){const l=n[r];(!e||md(this,this[l],l,e,!0))&&(delete this[l],i=!0)}return i}normalize(e){const n=this,r={};return V.forEach(this,(i,l)=>{const u=V.findKey(r,l);if(u){n[u]=Bl(i),delete n[l];return}const d=e?h0(l):String(l).trim();d!==l&&delete n[l],n[d]=Bl(i),r[d]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const n=Object.create(null);return V.forEach(this,(r,i)=>{r!=null&&r!==!1&&(n[i]=e&&V.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,n])=>e+": "+n).join(` +`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...n){const r=new this(e);return n.forEach(i=>r.set(i)),r}static accessor(e){const r=(this[Rp]=this[Rp]={accessors:{}}).accessors,i=this.prototype;function l(u){const d=so(u);r[d]||(g0(i,u),r[d]=!0)}return V.isArray(e)?e.forEach(l):l(e),this}};Cn.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),V.reduceDescriptors(Cn.prototype,({value:o},e)=>{let n=e[0].toUpperCase()+e.slice(1);return{get:()=>o,set(r){this[n]=r}}}),V.freezeMethods(Cn);const p0="[REDACTED ****]";function m0(o){if(V.hasOwnProp(o,"toJSON"))return!0;let e=Object.getPrototypeOf(o);for(;e&&e!==Object.prototype;){if(V.hasOwnProp(e,"toJSON"))return!0;e=Object.getPrototypeOf(e)}return!1}function y0(o,e){const n=new Set(e.map(l=>String(l).toLowerCase())),r=[],i=l=>{if(l===null||typeof l!="object"||V.isBuffer(l))return l;if(r.indexOf(l)!==-1)return;l instanceof Cn&&(l=l.toJSON()),r.push(l);let u;if(V.isArray(l))u=[],l.forEach((d,f)=>{const g=i(d);V.isUndefined(g)||(u[f]=g)});else{if(!V.isPlainObject(l)&&m0(l))return r.pop(),l;u=Object.create(null);for(const[d,f]of Object.entries(l)){const g=n.has(d.toLowerCase())?p0:i(f);V.isUndefined(g)||(u[d]=g)}}return r.pop(),u};return i(o)}let Ce=class IS extends Error{static from(e,n,r,i,l,u){const d=new IS(e.message,n||e.code,r,i,l);return Object.defineProperty(d,"cause",{__proto__:null,value:e,writable:!0,enumerable:!1,configurable:!0}),d.name=e.name,e.status!=null&&d.status==null&&(d.status=e.status),u&&Object.assign(d,u),d}constructor(e,n,r,i,l){super(e),Object.defineProperty(this,"message",{__proto__:null,value:e,enumerable:!0,writable:!0,configurable:!0}),this.name="AxiosError",this.isAxiosError=!0,n&&(this.code=n),r&&(this.config=r),i&&(this.request=i),l&&(this.response=l,this.status=l.status)}toJSON(){const e=this.config,n=e&&V.hasOwnProp(e,"redact")?e.redact:void 0,r=V.isArray(n)&&n.length>0?y0(e,n):V.toJSONObject(e);return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:r,code:this.code,status:this.status}}};Ce.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE",Ce.ERR_BAD_OPTION="ERR_BAD_OPTION",Ce.ECONNABORTED="ECONNABORTED",Ce.ETIMEDOUT="ETIMEDOUT",Ce.ECONNREFUSED="ECONNREFUSED",Ce.ERR_NETWORK="ERR_NETWORK",Ce.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS",Ce.ERR_DEPRECATED="ERR_DEPRECATED",Ce.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE",Ce.ERR_BAD_REQUEST="ERR_BAD_REQUEST",Ce.ERR_CANCELED="ERR_CANCELED",Ce.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT",Ce.ERR_INVALID_URL="ERR_INVALID_URL",Ce.ERR_FORM_DATA_DEPTH_EXCEEDED="ERR_FORM_DATA_DEPTH_EXCEEDED";const b0=null,kp=100;function yd(o){return V.isPlainObject(o)||V.isArray(o)}function Dp(o){return V.endsWith(o,"[]")?o.slice(0,-2):o}function bd(o,e,n){return o?o.concat(e).map(function(i,l){return i=Dp(i),!n&&l?"["+i+"]":i}).join(n?".":""):e}function v0(o){return V.isArray(o)&&!o.some(yd)}const S0=V.toFlatObject(V,{},null,function(e){return/^is[A-Z]/.test(e)});function Pl(o,e,n){if(!V.isObject(o))throw new TypeError("target must be an object");e=e||new FormData,n=V.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(M,T){return!V.isUndefined(T[M])});const r=n.metaTokens,i=n.visitor||_,l=n.dots,u=n.indexes,d=n.Blob||typeof Blob<"u"&&Blob,f=n.maxDepth===void 0?kp:n.maxDepth,g=d&&V.isSpecCompliantForm(e),m=[];if(!V.isFunction(i))throw new TypeError("visitor must be a function");function b(O){if(O===null)return"";if(V.isDate(O))return O.toISOString();if(V.isBoolean(O))return O.toString();if(!g&&V.isBlob(O))throw new Ce("Blob is not supported. Use a Buffer instead.");if(V.isArrayBuffer(O)||V.isTypedArray(O)){if(g&&typeof d=="function")return new d([O]);if(typeof Buffer<"u")return Buffer.from(O);throw new Ce("Blob is not supported. Use a Buffer instead.",Ce.ERR_NOT_SUPPORT)}return O}function v(O){if(O>f)throw new Ce("Object is too deeply nested ("+O+" levels). Max depth: "+f,Ce.ERR_FORM_DATA_DEPTH_EXCEEDED)}function S(O,M){if(f===1/0)return JSON.stringify(O);const T=[];return JSON.stringify(O,function(j,H){if(!V.isObject(H))return H;for(;T.length&&T[T.length-1]!==this;)T.pop();return T.push(H),v(M+T.length-1),H})}function _(O,M,T){let D=O;if(V.isReactNative(e)&&V.isReactNativeBlob(O))return e.append(bd(T,M,l),b(O)),!1;if(O&&!T&&typeof O=="object"){if(V.endsWith(M,"{}"))M=r?M:M.slice(0,-2),O=S(O,1);else if(V.isArray(O)&&v0(O)||(V.isFileList(O)||V.endsWith(M,"[]"))&&(D=V.toArray(O)))return M=Dp(M),D.forEach(function(H,P){!(V.isUndefined(H)||H===null)&&e.append(u===!0?bd([M],P,l):u===null?M:M+"[]",b(H))}),!1}return yd(O)?!0:(e.append(bd(T,M,l),b(O)),!1)}const x=Object.assign(S0,{defaultVisitor:_,convertValue:b,isVisitable:yd});function k(O,M,T=0){if(!V.isUndefined(O)){if(v(T),m.indexOf(O)!==-1)throw new Error("Circular reference detected in "+M.join("."));m.push(O),V.forEach(O,function(j,H){(!(V.isUndefined(j)||j===null)&&i.call(e,j,V.isString(H)?H.trim():H,M,x))===!0&&k(j,M?M.concat(H):[H],T+1)}),m.pop()}}if(!V.isObject(o))throw new TypeError("data must be an object");return k(o),e}function Op(o){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"};return encodeURIComponent(o).replace(/[!'()~]|%20/g,function(r){return e[r]})}function vd(o,e){this._pairs=[],o&&Pl(o,this,e)}const Lp=vd.prototype;Lp.append=function(e,n){this._pairs.push([e,n])},Lp.toString=function(e){const n=e?r=>e.call(this,r,Op):Op;return this._pairs.map(function(i){return n(i[0])+"="+n(i[1])},"").join("&")};function w0(o){return encodeURIComponent(o).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Mp(o,e,n){if(!e)return o;o=o||"";const r=V.isFunction(n)?{serialize:n}:n,i=V.getSafeProp(r,"encode")||w0,l=V.getSafeProp(r,"serialize");let u;if(l?u=l(e,r):u=V.isURLSearchParams(e)?e.toString():new vd(e,r).toString(i),u){const d=o.indexOf("#");d!==-1&&(o=o.slice(0,d)),o+=(o.indexOf("?")===-1?"?":"&")+u}return o}class $p{constructor(){this.handlers=[]}use(e,n,r){return this.handlers.push({fulfilled:e,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){V.forEach(this.handlers,function(r){r!==null&&e(r)})}}const Sd={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0,advertiseZstdAcceptEncoding:!1,validateStatusUndefinedResolves:!0},C0={isBrowser:!0,classes:{URLSearchParams:typeof URLSearchParams<"u"?URLSearchParams:vd,FormData:typeof FormData<"u"?FormData:null,Blob:typeof Blob<"u"?Blob:null},protocols:["http","https","file","blob","url","data"]},wd=typeof window<"u"&&typeof document<"u",Cd=typeof navigator=="object"&&navigator||void 0,E0=wd&&(!Cd||["ReactNative","NativeScript","NS"].indexOf(Cd.product)<0),_0=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",A0=wd&&window.location.href||"http://localhost",pn={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:wd,hasStandardBrowserEnv:E0,hasStandardBrowserWebWorkerEnv:_0,navigator:Cd,origin:A0},Symbol.toStringTag,{value:"Module"})),...C0};function x0(o,e){return Pl(o,new pn.classes.URLSearchParams,{visitor:function(n,r,i,l){return pn.isNode&&V.isBuffer(n)?(this.append(r,n.toString("base64")),!1):l.defaultVisitor.apply(this,arguments)},...e})}const Np=kp;function Ip(o){if(o>Np)throw new Ce("FormData field is too deeply nested ("+o+" levels). Max depth: "+Np,Ce.ERR_FORM_DATA_DEPTH_EXCEEDED)}function T0(o){const e=[],n=/\w+|\[(\w*)]/g;let r;for(;(r=n.exec(o))!==null;)Ip(e.length),e.push(r[0]==="[]"?"":r[1]||r[0]);return e}function R0(o){const e={},n=Object.keys(o);let r;const i=n.length;let l;for(r=0;r=n.length;return u=!u&&V.isArray(i)?i.length:u,f?(V.hasOwnProp(i,u)?i[u]=V.isArray(i[u])?i[u].concat(r):[i[u],r]:i[u]=r,!d):((!V.hasOwnProp(i,u)||!V.isObject(i[u]))&&(i[u]=[]),e(n,r,i[u],l)&&V.isArray(i[u])&&(i[u]=R0(i[u])),!d)}if(V.isFormData(o)&&V.isFunction(o.entries)){const n={};return V.forEachEntry(o,(r,i)=>{e(T0(r),i,n,0)}),n}return null}const rs=(o,e)=>o!=null&&V.hasOwnProp(o,e)?o[e]:void 0;function k0(o,e,n){if(V.isString(o))try{return(e||JSON.parse)(o),V.trim(o)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(o)}const oo={transitional:Sd,adapter:["xhr","http","fetch"],transformRequest:[function(e,n){const r=n.getContentType()||"",i=r.indexOf("application/json")>-1,l=V.isObject(e);if(l&&V.isHTMLForm(e)&&(e=new FormData(e)),V.isFormData(e))return i?JSON.stringify(Hp(e)):e;if(V.isArrayBuffer(e)||V.isBuffer(e)||V.isStream(e)||V.isFile(e)||V.isBlob(e)||V.isReadableStream(e))return e;if(V.isArrayBufferView(e))return e.buffer;if(V.isURLSearchParams(e))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let d;if(l){const f=rs(this,"formSerializer");if(r.indexOf("application/x-www-form-urlencoded")>-1)return x0(e,f).toString();if((d=V.isFileList(e))||r.indexOf("multipart/form-data")>-1){const g=rs(this,"env"),m=g&&g.FormData;return Pl(d?{"files[]":e}:e,m&&new m,f)}}return l||i?(n.setContentType("application/json",!1),k0(e)):e}],transformResponse:[function(e){const n=rs(this,"transitional")||oo.transitional,r=n&&n.forcedJSONParsing,i=rs(this,"responseType"),l=i==="json";if(V.isResponse(e)||V.isReadableStream(e))return e;if(e&&V.isString(e)&&(r&&!i||l)){const d=!(n&&n.silentJSONParsing)&&l;try{return JSON.parse(e,rs(this,"parseReviver"))}catch(f){if(d)throw f.name==="SyntaxError"?Ce.from(f,Ce.ERR_BAD_RESPONSE,this,null,rs(this,"response")):f}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:pn.classes.FormData,Blob:pn.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};V.forEach(["delete","get","head","post","put","patch","query"],o=>{oo.headers[o]={}});function Ed(o,e){const n=this||oo,r=e||n,i=Cn.from(r.headers);let l=r.data;return V.forEach(o,function(d){l=d.call(n,l,i.normalize(),e?e.status:void 0)}),i.normalize(),l}function zp(o){return!!(o&&o.__CANCEL__)}let lo=class extends Ce{constructor(e,n,r){super(e??"canceled",Ce.ERR_CANCELED,n,r),this.name="CanceledError",this.__CANCEL__=!0}};function jp(o,e,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?o(n):e(new Ce("Request failed with status code "+n.status,n.status>=400&&n.status<500?Ce.ERR_BAD_REQUEST:Ce.ERR_BAD_RESPONSE,n.config,n.request,n))}function D0(o){const e=/^([-+\w]{1,25}):(?:\/\/)?/.exec(o);return e&&e[1]||""}function O0(o,e){o=o||10;const n=new Array(o),r=new Array(o);let i=0,l=0,u;return e=e!==void 0?e:1e3,function(f){const g=Date.now(),m=r[l];u||(u=g),n[i]=f,r[i]=g;let b=l,v=0;for(;b!==i;)v+=n[b++],b=b%o;if(i=(i+1)%o,i===l&&(l=(l+1)%o),g-u{n=m,i=null,l&&(clearTimeout(l),l=null),o(...g)};return[(...g)=>{const m=Date.now(),b=m-n;b>=r?u(g,m):(i=g,l||(l=setTimeout(()=>{l=null,u(i)},r-b)))},()=>i&&u(i)]}const ql=(o,e,n=3)=>{let r=0;const i=O0(50,250);return L0(l=>{if(!l||typeof l.loaded!="number")return;const u=l.loaded,d=l.lengthComputable?l.total:void 0,f=d!=null?Math.min(u,d):u,g=Math.max(0,f-r),m=i(g);r=Math.max(r,f);const b={loaded:f,total:d,progress:d?f/d:void 0,bytes:g,rate:m||void 0,estimated:m&&d?(d-f)/m:void 0,event:l,lengthComputable:d!=null,[e?"download":"upload"]:!0};o(b)},n)},Up=(o,e)=>{const n=o!=null;return[r=>e[0]({lengthComputable:n,total:o,loaded:r}),e[1]]},Bp=o=>(...e)=>V.asap(()=>o(...e)),M0=pn.hasStandardBrowserEnv?((o,e)=>n=>(n=new URL(n,pn.origin),o.protocol===n.protocol&&o.host===n.host&&(e||o.port===n.port)))(new URL(pn.origin),pn.navigator&&/(msie|trident)/i.test(pn.navigator.userAgent)):()=>!0,$0=pn.hasStandardBrowserEnv?{write(o,e,n,r,i,l,u){if(typeof document>"u")return;const d=[`${o}=${encodeURIComponent(e)}`];V.isNumber(n)&&d.push(`expires=${new Date(n).toUTCString()}`),V.isString(r)&&d.push(`path=${r}`),V.isString(i)&&d.push(`domain=${i}`),l===!0&&d.push("secure"),V.isString(u)&&d.push(`SameSite=${u}`),document.cookie=d.join("; ")},read(o){if(typeof document>"u")return null;const e=document.cookie.split(";");for(let n=0;no instanceof Cn?{...o}:o;function hi(o,e){o=o||{},e=e||{};const n=Object.create(null);Object.defineProperty(n,"hasOwnProperty",{__proto__:null,value:Object.prototype.hasOwnProperty,enumerable:!1,writable:!0,configurable:!0});function r(m,b,v,S){return V.isPlainObject(m)&&V.isPlainObject(b)?V.merge.call({caseless:S},m,b):V.isPlainObject(b)?V.merge({},b):V.isArray(b)?b.slice():b}function i(m,b,v,S){if(V.isUndefined(b)){if(!V.isUndefined(m))return r(void 0,m,v,S)}else return r(m,b,v,S)}function l(m,b){if(!V.isUndefined(b))return r(void 0,b)}function u(m,b){if(V.isUndefined(b)){if(!V.isUndefined(m))return r(void 0,m)}else return r(void 0,b)}function d(m){const b=V.hasOwnProp(e,"transitional")?e.transitional:void 0;if(!V.isUndefined(b))if(V.isPlainObject(b)){if(V.hasOwnProp(b,m))return b[m]}else return;const v=V.hasOwnProp(o,"transitional")?o.transitional:void 0;if(V.isPlainObject(v)&&V.hasOwnProp(v,m))return v[m]}function f(m,b,v){if(V.hasOwnProp(e,v))return r(m,b);if(V.hasOwnProp(o,v))return r(void 0,m)}const g={url:l,method:l,data:l,baseURL:u,transformRequest:u,transformResponse:u,paramsSerializer:u,timeout:u,timeoutMessage:u,withCredentials:u,withXSRFToken:u,adapter:u,responseType:u,xsrfCookieName:u,xsrfHeaderName:u,onUploadProgress:u,onDownloadProgress:u,decompress:u,maxContentLength:u,maxBodyLength:u,beforeRedirect:u,transport:u,httpAgent:u,httpsAgent:u,cancelToken:u,socketPath:u,allowedSocketPaths:u,responseEncoding:u,validateStatus:f,headers:(m,b,v)=>i(Gp(m),Gp(b),v,!0)};return V.forEach(Object.keys({...o,...e}),function(b){if(b==="__proto__"||b==="constructor"||b==="prototype")return;const v=V.hasOwnProp(g,b)?g[b]:i,S=V.hasOwnProp(o,b)?o[b]:void 0,_=V.hasOwnProp(e,b)?e[b]:void 0,x=v(S,_,b);V.isUndefined(x)&&v!==f||(n[b]=x)}),V.hasOwnProp(e,"validateStatus")&&V.isUndefined(e.validateStatus)&&d("validateStatusUndefinedResolves")===!1&&(V.hasOwnProp(o,"validateStatus")?n.validateStatus=r(void 0,o.validateStatus):delete n.validateStatus),n}const B0=["content-type","content-length"];function P0(o,e,n){if(n!=="content-only"){o.set(e);return}Object.entries(e||{}).forEach(([r,i])=>{B0.includes(r.toLowerCase())&&o.set(r,i)})}const q0=o=>encodeURIComponent(o).replace(/%([0-9A-F]{2})/gi,(e,n)=>String.fromCharCode(parseInt(n,16)));function Vp(o){const e=hi({},o),n=v=>V.hasOwnProp(e,v)?e[v]:void 0,r=n("data");let i=n("withXSRFToken");const l=n("xsrfHeaderName"),u=n("xsrfCookieName");let d=n("headers");const f=n("auth"),g=n("baseURL"),m=n("allowAbsoluteUrls"),b=n("url");if(e.headers=d=Cn.from(d),e.url=Mp(qp(g,b,m,e),n("params"),n("paramsSerializer")),f){const v=V.getSafeProp(f,"username")||"",S=V.getSafeProp(f,"password")||"";try{d.set("Authorization","Basic "+btoa(v+":"+(S?q0(S):"")))}catch(_){throw Ce.from(_,Ce.ERR_BAD_OPTION_VALUE,o)}}if(V.isFormData(r)&&(pn.hasStandardBrowserEnv||pn.hasStandardBrowserWebWorkerEnv||V.isReactNative(r)?d.setContentType(void 0):V.isFunction(r.getHeaders)&&P0(d,r.getHeaders(),n("formDataHeaderPolicy"))),pn.hasStandardBrowserEnv&&(V.isFunction(i)&&(i=i(e)),i===!0||i==null&&M0(e.url))){const S=l&&u&&$0.read(u);S&&d.set(l,S)}return e}const G0=typeof XMLHttpRequest<"u"&&function(o){return new Promise(function(n,r){const i=Vp(o);let l=i.data;const u=Cn.from(i.headers).normalize();let{responseType:d,onUploadProgress:f,onDownloadProgress:g}=i,m,b,v,S,_;function x(){S&&S(),_&&_(),i.cancelToken&&i.cancelToken.unsubscribe(m),i.signal&&i.signal.removeEventListener("abort",m)}let k=new XMLHttpRequest;k.open(i.method.toUpperCase(),i.url,!0),k.timeout=i.timeout;function O(){if(!k)return;const T=Cn.from("getAllResponseHeaders"in k&&k.getAllResponseHeaders()),j={data:!d||d==="text"||d==="json"?k.responseText:k.response,status:k.status,statusText:k.statusText,headers:T,config:o,request:k};jp(function(P){n(P),x()},function(P){r(P),x()},j),k=null}"onloadend"in k?k.onloadend=O:k.onreadystatechange=function(){!k||k.readyState!==4||k.status===0&&!(k.responseURL&&k.responseURL.startsWith("file:"))||setTimeout(O)},k.onabort=function(){k&&(r(new Ce("Request aborted",Ce.ECONNABORTED,o,k)),x(),k=null)},k.onerror=function(D){const j=D&&D.message?D.message:"Network Error",H=new Ce(j,Ce.ERR_NETWORK,o,k);H.event=D||null,r(H),x(),k=null},k.ontimeout=function(){let D=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const j=i.transitional||Sd;i.timeoutErrorMessage&&(D=i.timeoutErrorMessage),r(new Ce(D,j.clarifyTimeoutError?Ce.ETIMEDOUT:Ce.ECONNABORTED,o,k)),x(),k=null},l===void 0&&u.setContentType(null),"setRequestHeader"in k&&V.forEach(Tp(u),function(D,j){k.setRequestHeader(j,D)}),V.isUndefined(i.withCredentials)||(k.withCredentials=!!i.withCredentials),d&&d!=="json"&&(k.responseType=i.responseType),g&&([v,_]=ql(g,!0),k.addEventListener("progress",v)),f&&k.upload&&([b,S]=ql(f),k.upload.addEventListener("progress",b),k.upload.addEventListener("loadend",S)),(i.cancelToken||i.signal)&&(m=T=>{k&&(r(!T||T.type?new lo(null,o,k):T),k.abort(),x(),k=null)},i.cancelToken&&i.cancelToken.subscribe(m),i.signal&&(i.signal.aborted?m():i.signal.addEventListener("abort",m)));const M=D0(i.url);if(M&&!pn.protocols.includes(M)){r(new Ce("Unsupported protocol "+M+":",Ce.ERR_BAD_REQUEST,o)),x();return}k.send(l||null)})},V0=(o,e)=>{if(o=o?o.filter(Boolean):[],!e&&!o.length)return;const n=new AbortController;let r=!1;const i=function(f){if(!r){r=!0,u();const g=f instanceof Error?f:this.reason;n.abort(g instanceof Ce?g:new lo(g instanceof Error?g.message:g))}};let l=e&&setTimeout(()=>{l=null,i(new Ce(`timeout of ${e}ms exceeded`,Ce.ETIMEDOUT))},e);const u=()=>{o&&(l&&clearTimeout(l),l=null,o.forEach(f=>{f.unsubscribe?f.unsubscribe(i):f.removeEventListener("abort",i)}),o=null)};o.forEach(f=>f.addEventListener("abort",i,{once:!0}));const{signal:d}=n;return d.unsubscribe=()=>V.asap(u),d},F0=function*(o,e){let n=o.byteLength;if(n{const i=K0(o,e);let l=0,u,d=f=>{u||(u=!0,r&&r(f))};return new ReadableStream({async pull(f){try{const{done:g,value:m}=await i.next();if(g){d(),f.close();return}let b=m.byteLength;if(n){let v=l+=b;n(v)}f.enqueue(new Uint8Array(m))}catch(g){throw d(g),g}},cancel(f){return d(f),i.return()}},{highWaterMark:2})},Gl=o=>o>=48&&o<=57||o>=65&&o<=70||o>=97&&o<=102,Y0=(o,e,n)=>e+2S>=2&&r.charCodeAt(S-2)===37&&r.charCodeAt(S-1)===51&&(r.charCodeAt(S)===68||r.charCodeAt(S)===100);g>=0&&(r.charCodeAt(g)===61?(f++,g--):m(g)&&(f++,g-=3)),f===1&&g>=0&&(r.charCodeAt(g)===61||m(g))&&f++;const v=Math.floor(u/4)*3-(f||0);return v>0?v:0}let l=0;for(let u=0,d=r.length;u=55296&&f<=56319&&u+1=56320&&g<=57343?(l+=4,u++):l+=3}else l+=3}return l}const _d="1.18.1",Kp=64*1024,{isFunction:Vl}=V,J0=o=>encodeURIComponent(o).replace(/%([0-9A-F]{2})/gi,(e,n)=>String.fromCharCode(parseInt(n,16))),Wp=o=>{if(!V.isString(o))return o;try{return decodeURIComponent(o)}catch{return o}},Yp=(o,...e)=>{try{return!!o(...e)}catch{return!1}},Q0=o=>{const e=o.indexOf("://");let n=o;return e!==-1&&(n=n.slice(e+3)),n.includes("@")||n.includes(":")},Z0=o=>{const e=V.global!==void 0&&V.global!==null?V.global:globalThis,{ReadableStream:n,TextEncoder:r}=e;o=V.merge.call({skipUndefined:!0},{Request:e.Request,Response:e.Response},o);const{fetch:i,Request:l,Response:u}=o,d=i?Vl(i):typeof fetch=="function",f=Vl(l),g=Vl(u);if(!d)return!1;const m=d&&Vl(n),b=d&&(typeof r=="function"?(O=>M=>O.encode(M))(new r):async O=>new Uint8Array(await new l(O).arrayBuffer())),v=f&&m&&Yp(()=>{let O=!1;const M=new l(pn.origin,{body:new n,method:"POST",get duplex(){return O=!0,"half"}}),T=M.headers.has("Content-Type");return M.body!=null&&M.body.cancel(),O&&!T}),S=g&&m&&Yp(()=>V.isReadableStream(new u("").body)),_={stream:S&&(O=>O.body)};d&&["text","arrayBuffer","blob","formData","stream"].forEach(O=>{!_[O]&&(_[O]=(M,T)=>{let D=M&&M[O];if(D)return D.call(M);throw new Ce(`Response type '${O}' is not supported`,Ce.ERR_NOT_SUPPORT,T)})});const x=async O=>{if(O==null)return 0;if(V.isBlob(O))return O.size;if(V.isSpecCompliantForm(O))return(await new l(pn.origin,{method:"POST",body:O}).arrayBuffer()).byteLength;if(V.isArrayBufferView(O)||V.isArrayBuffer(O))return O.byteLength;if(V.isURLSearchParams(O)&&(O=O+""),V.isString(O))return(await b(O)).byteLength},k=async(O,M)=>{const T=V.toFiniteNumber(O.getContentLength());return T??x(M)};return async O=>{let{url:M,method:T,data:D,signal:j,cancelToken:H,timeout:P,onDownloadProgress:X,onUploadProgress:pe,responseType:_e,headers:we,withCredentials:Me="same-origin",fetchOptions:qe,maxContentLength:Je,maxBodyLength:gt}=Vp(O);const Q=V.isNumber(Je)&&Je>-1,fe=V.isNumber(gt)&>>-1,ve=de=>V.hasOwnProp(O,de)?O[de]:void 0;let ae=i||fetch;_e=_e?(_e+"").toLowerCase():"text";let ge=V0([j,H&&H.toAbortSignal()],P),A=null;const K=ge&&ge.unsubscribe&&(()=>{ge.unsubscribe()});let ue,he=null;const le=()=>new Ce("Request body larger than maxBodyLength limit",Ce.ERR_BAD_REQUEST,O,A);try{let de;const Oe=ve("auth");if(Oe){const Ee=V.getSafeProp(Oe,"username")||"",Nt=V.getSafeProp(Oe,"password")||"";de={username:Ee,password:Nt}}if(Q0(M)){const Ee=new URL(M,pn.origin);if(!de&&(Ee.username||Ee.password)){const Nt=Wp(Ee.username),zt=Wp(Ee.password);de={username:Nt,password:zt}}(Ee.username||Ee.password)&&(Ee.username="",Ee.password="",M=Ee.href)}if(de&&(we.delete("authorization"),we.set("Authorization","Basic "+btoa(J0((de.username||"")+":"+(de.password||""))))),Q&&typeof M=="string"&&M.startsWith("data:")&&X0(M)>Je)throw new Ce("maxContentLength size of "+Je+" exceeded",Ce.ERR_BAD_RESPONSE,O,A);if(fe&&T!=="get"&&T!=="head"){const Ee=await x(D);if(typeof Ee=="number"&&isFinite(Ee)&&(ue=Ee,Ee>gt))throw le()}const He=fe&&(V.isReadableStream(D)||V.isStream(D)),Pe=(Ee,Nt,zt)=>Fp(Ee,Kp,qt=>{if(fe&&qt>gt)throw he=le();Nt&&Nt(qt)},zt);if(v&&T!=="get"&&T!=="head"&&(pe||He)){if(ue=ue??await k(we,D),ue!==0||He){let Ee=new l(M,{method:"POST",body:D,duplex:"half"}),Nt;if(V.isFormData(D)&&(Nt=Ee.headers.get("content-type"))&&we.setContentType(Nt),Ee.body){const[zt,qt]=pe&&Up(ue,ql(Bp(pe)))||[];D=Pe(Ee.body,zt,qt)}}}else if(He&&!f&&m&&T!=="get"&&T!=="head")D=Pe(D);else if(He&&f&&!v&&T!=="get"&&T!=="head")throw new Ce("Stream request bodies are not supported by the current fetch implementation",Ce.ERR_NOT_SUPPORT,O,A);V.isString(Me)||(Me=Me?"include":"omit");const ke=f&&"credentials"in l.prototype;if(V.isFormData(D)){const Ee=we.getContentType();Ee&&/^multipart\/form-data/i.test(Ee)&&!/boundary=/i.test(Ee)&&we.delete("content-type")}we.set("User-Agent","axios/"+_d,!1);const Ot={...qe,signal:ge,method:T.toUpperCase(),headers:Tp(we.normalize()),body:D,duplex:"half",credentials:ke?Me:void 0};A=f&&new l(M,Ot);let ut=await(f?ae(A,qe):ae(M,Ot));const Ct=Cn.from(ut.headers);if(Q){const Ee=V.toFiniteNumber(Ct.getContentLength());if(Ee!=null&&Ee>Je)throw new Ce("maxContentLength size of "+Je+" exceeded",Ce.ERR_BAD_RESPONSE,O,A)}const vt=S&&(_e==="stream"||_e==="response");if(S&&ut.body&&(X||Q||vt&&K)){const Ee={};["status","statusText","headers"].forEach(hn=>{Ee[hn]=ut[hn]});const Nt=V.toFiniteNumber(Ct.getContentLength()),[zt,qt]=X&&Up(Nt,ql(Bp(X),!0))||[];let Lt=0;const _n=hn=>{if(Q&&(Lt=hn,Lt>Je))throw new Ce("maxContentLength size of "+Je+" exceeded",Ce.ERR_BAD_RESPONSE,O,A);zt&&zt(hn)};ut=new u(Fp(ut.body,Kp,_n,()=>{qt&&qt(),K&&K()}),Ee)}_e=_e||"text";let kt=await _[V.findKey(_,_e)||"text"](ut,O);if(Q&&!S&&!vt){let Ee;if(kt!=null&&(typeof kt.byteLength=="number"?Ee=kt.byteLength:typeof kt.size=="number"?Ee=kt.size:typeof kt=="string"&&(Ee=typeof r=="function"?new r().encode(kt).byteLength:kt.length)),typeof Ee=="number"&&Ee>Je)throw new Ce("maxContentLength size of "+Je+" exceeded",Ce.ERR_BAD_RESPONSE,O,A)}return!vt&&K&&K(),await new Promise((Ee,Nt)=>{jp(Ee,Nt,{data:kt,headers:Cn.from(ut.headers),status:ut.status,statusText:ut.statusText,config:O,request:A})})}catch(de){if(K&&K(),ge&&ge.aborted&&ge.reason instanceof Ce){const Oe=ge.reason;throw Oe.config=O,A&&(Oe.request=A),de!==Oe&&Object.defineProperty(Oe,"cause",{__proto__:null,value:de,writable:!0,enumerable:!1,configurable:!0}),Oe}if(he)throw A&&!he.request&&(he.request=A),he;if(de instanceof Ce)throw A&&!de.request&&(de.request=A),de;if(de&&de.name==="TypeError"&&/Load failed|fetch/i.test(de.message)){const Oe=new Ce("Network Error",Ce.ERR_NETWORK,O,A,de&&de.response);throw Object.defineProperty(Oe,"cause",{__proto__:null,value:de.cause||de,writable:!0,enumerable:!1,configurable:!0}),Oe}throw Ce.from(de,de&&de.code,O,A,de&&de.response)}}},eC=new Map,Xp=o=>{let e=o&&o.env||{};const{fetch:n,Request:r,Response:i}=e,l=[r,i,n];let u=l.length,d=u,f,g,m=eC;for(;d--;)f=l[d],g=m.get(f),g===void 0&&m.set(f,g=d?new Map:Z0(e)),m=g;return g};Xp();const Ad={http:b0,xhr:G0,fetch:{get:Xp}};V.forEach(Ad,(o,e)=>{if(o){try{Object.defineProperty(o,"name",{__proto__:null,value:e})}catch{}Object.defineProperty(o,"adapterName",{__proto__:null,value:e})}});const Jp=o=>`- ${o}`,tC=o=>V.isFunction(o)||o===null||o===!1;function nC(o,e){o=V.isArray(o)?o:[o];const{length:n}=o;let r,i;const l={};for(let u=0;u`adapter ${f} `+(g===!1?"is not supported by the environment":"is not available in the build"));let d=n?u.length>1?`since : +`+u.map(Jp).join(` +`):" "+Jp(u[0]):"as no adapter specified";throw new Ce("There is no suitable adapter to dispatch the request "+d,Ce.ERR_NOT_SUPPORT)}return i}const Qp={getAdapter:nC,adapters:Ad};function xd(o){if(o.cancelToken&&o.cancelToken.throwIfRequested(),o.signal&&o.signal.aborted)throw new lo(null,o)}function Zp(o){return xd(o),o.headers=Cn.from(o.headers),o.data=Ed.call(o,o.transformRequest),["post","put","patch"].indexOf(o.method)!==-1&&o.headers.setContentType("application/x-www-form-urlencoded",!1),Qp.getAdapter(o.adapter||oo.adapter,o)(o).then(function(r){xd(o),o.response=r;try{r.data=Ed.call(o,o.transformResponse,r)}finally{delete o.response}return r.headers=Cn.from(r.headers),r},function(r){if(!zp(r)&&(xd(o),r&&r.response)){o.response=r.response;try{r.response.data=Ed.call(o,o.transformResponse,r.response)}finally{delete o.response}r.response.headers=Cn.from(r.response.headers)}return Promise.reject(r)})}const Fl={};["object","boolean","number","function","string","symbol"].forEach((o,e)=>{Fl[o]=function(r){return typeof r===o||"a"+(e<1?"n ":" ")+o}});const em={};Fl.transitional=function(e,n,r){function i(l,u){return"[Axios v"+_d+"] Transitional option '"+l+"'"+u+(r?". "+r:"")}return(l,u,d)=>{if(e===!1)throw new Ce(i(u," has been removed"+(n?" in "+n:"")),Ce.ERR_DEPRECATED);return n&&!em[u]&&(em[u]=!0,console.warn(i(u," has been deprecated since v"+n+" and will be removed in the near future"))),e?e(l,u,d):!0}},Fl.spelling=function(e){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};function aC(o,e,n){if(typeof o!="object"||o===null)throw new Ce("options must be an object",Ce.ERR_BAD_OPTION_VALUE);const r=Object.keys(o);let i=r.length;for(;i-- >0;){const l=r[i],u=Object.prototype.hasOwnProperty.call(e,l)?e[l]:void 0;if(u){const d=o[l],f=d===void 0||u(d,l,o);if(f!==!0)throw new Ce("option "+l+" must be "+f,Ce.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new Ce("Unknown option "+l,Ce.ERR_BAD_OPTION)}}const Kl={assertOptions:aC,validators:Fl},En=Kl.validators;let gi=class{constructor(e){this.defaults=e||{},this.interceptors={request:new $p,response:new $p}}async request(e,n){try{return await this._request(e,n)}catch(r){if(r instanceof Error){let i={};Error.captureStackTrace?Error.captureStackTrace(i):i=new Error;const l=(()=>{if(!i.stack)return"";const u=i.stack.indexOf(` `);return u===-1?"":i.stack.slice(u+1)})();try{if(!r.stack)r.stack=l;else if(l){const u=l.indexOf(` `),d=u===-1?-1:l.indexOf(` `,u+1),f=d===-1?"":l.slice(d+1);String(r.stack).endsWith(f)||(r.stack+=` -`+l)}}catch{}}throw r}}_request(e,a){typeof e=="string"?(a=a||{},a.url=e):a=e||{},a=fi(this.defaults,a);const{transitional:r,paramsSerializer:i,headers:l}=a;r!==void 0&&Gl.assertOptions(r,{silentJSONParsing:Jn.transitional(Jn.boolean),forcedJSONParsing:Jn.transitional(Jn.boolean),clarifyTimeoutError:Jn.transitional(Jn.boolean),legacyInterceptorReqResOrdering:Jn.transitional(Jn.boolean)},!1),i!=null&&(F.isFunction(i)?a.paramsSerializer={serialize:i}:Gl.assertOptions(i,{encode:Jn.function,serialize:Jn.function},!0)),a.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?a.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:a.allowAbsoluteUrls=!0),Gl.assertOptions(a,{baseUrl:Jn.spelling("baseURL"),withXsrfToken:Jn.spelling("withXSRFToken")},!0),a.method=(a.method||this.defaults.method||"get").toLowerCase();let u=l&&F.merge(l.common,l[a.method]);l&&F.forEach(["delete","get","head","post","put","patch","query","common"],E=>{delete l[E]}),a.headers=Cn.concat(u,l);const d=[];let f=!0;this.interceptors.request.forEach(function(A){if(typeof A.runWhen=="function"&&A.runWhen(a)===!1)return;f=f&&A.synchronous;const T=a.transitional||md;T&&T.legacyInterceptorReqResOrdering?d.unshift(A.fulfilled,A.rejected):d.push(A.fulfilled,A.rejected)});const g=[];this.interceptors.response.forEach(function(A){g.push(A.fulfilled,A.rejected)});let m,b=0,v;if(!f){const E=[Gp.bind(this),void 0];for(E.unshift(...d),E.push(...g),v=E.length,m=Promise.resolve(a);b{if(!r._listeners)return;let l=r._listeners.length;for(;l-- >0;)r._listeners[l](i);r._listeners=null}),this.promise.then=i=>{let l;const u=new Promise(d=>{r.subscribe(d),l=d}).then(i);return u.cancel=function(){r.unsubscribe(l)},u},e(function(l,u,d){r.reason||(r.reason=new io(l,u,d),a(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const a=this._listeners.indexOf(e);a!==-1&&this._listeners.splice(a,1)}toAbortSignal(){const e=new AbortController,a=r=>{e.abort(r)};return this.subscribe(a),e.signal.unsubscribe=()=>this.unsubscribe(a),e.signal}static source(){let e;return{token:new kS(function(i){e=i}),cancel:e}}};function q0(o){return function(a){return o.apply(null,a)}}function G0(o){return F.isObject(o)&&o.isAxiosError===!0}const Ed={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(Ed).forEach(([o,e])=>{Ed[e]=o});function Fp(o){const e=new hi(o),a=hp(hi.prototype.request,e);return F.extend(a,hi.prototype,e,{allOwnKeys:!0}),F.extend(a,e,null,{allOwnKeys:!0}),a.create=function(i){return Fp(fi(o,i))},a}const Pt=Fp(ro);Pt.Axios=hi,Pt.CanceledError=io,Pt.CancelToken=P0,Pt.isCancel=Op,Pt.VERSION=Sd,Pt.toFormData=Ul,Pt.AxiosError=Oe,Pt.Cancel=Pt.CanceledError,Pt.all=function(e){return Promise.all(e)},Pt.spread=q0,Pt.isAxiosError=G0,Pt.mergeConfig=fi,Pt.AxiosHeaders=Cn,Pt.formToJSON=o=>Dp(F.isHTMLForm(o)?new FormData(o):o),Pt.getAdapter=qp.getAdapter,Pt.HttpStatusCode=Ed,Pt.default=Pt;const{Axios:sT,AxiosError:oT,CanceledError:lT,isCancel:cT,CancelToken:uT,VERSION:dT,all:fT,Cancel:hT,isAxiosError:gT,spread:pT,toFormData:mT,AxiosHeaders:yT,HttpStatusCode:bT,formToJSON:vT,getAdapter:ST,mergeConfig:wT,create:CT}=Pt,_d="g7.identity.redirectStash",Vl=ct("IdentityGuardInterceptor");class St{static setLauncher(e){this.launcher=e}static hasLauncher(){return this.launcher!==null}static markDomainNoticeShown(){this.domainNoticeShown=!0}static consumeDomainNoticeShown(){const e=this.domainNoticeShown;return this.domainNoticeShown=!1,e}static resolveDeferred(e){const a=this.deferredResolver;if(!a){Vl.warn("IdentityGuardInterceptor.resolveDeferred 호출됐지만 대기 중인 launcher 가 없습니다. 모달이 launcher 외부에서 열렸는지 확인하세요.");return}this.deferredResolver=null,a(e)}static createDeferred(){if(this.deferredResolver){const e=this.deferredResolver;this.deferredResolver=null,e({status:"cancelled"})}return new Promise(e=>{this.deferredResolver=e})}static isIdentityRequired(e,a){return e===428&&typeof a=="object"&&a!==null&&a.error_code==="identity_verification_required"}static async handle(e,a,r){this.domainNoticeShown=!1;const i=this.launcher??F0,u=!!(r&&(r.email||r.phone))?{...e.verification,target:r}:e.verification,d=await i(u);if(d.status!=="verified")return null;const f=u.return_request;if(!f)return null;const g=V0(f.url,d.token);return fetch(g,{method:f.method,headers:a?.headers??{Accept:"application/json","Content-Type":"application/json"},body:a?.body,credentials:a?.credentials??"same-origin"})}static redirectExternally(e){const a=e.redirect_url;if(!a)return Vl.error("redirectExternally 호출 시 verification.redirect_url 이 없습니다. payload:",e),Promise.resolve({status:"failed",failureCode:"MISSING_REDIRECT_URL",reason:"verification.redirect_url is required for external_redirect flow"});if(typeof window<"u"){const r={return_url:window.location.href,payload:e,stashed_at:Date.now()};try{window.sessionStorage?.setItem(_d,JSON.stringify(r))}catch(i){Vl.warn("sessionStorage 접근 실패 — stash 없이 redirect 합니다.",i)}window.location.href=a}return new Promise(()=>{})}static reset(){if(this.deferredResolver){const e=this.deferredResolver;this.deferredResolver=null;try{e({status:"cancelled"})}catch{}}this.launcher=null,this.domainNoticeShown=!1}}$(St,"launcher",null),$(St,"deferredResolver",null),$(St,"domainNoticeShown",!1);function V0(o,e){if(!e)return o;try{const a=typeof window<"u"?window.location.origin:"http://localhost",r=new URL(o,a);return r.searchParams.set("verification_token",e),/^https?:\/\//i.test(o)?r.toString():`${r.pathname}${r.search}${r.hash}`}catch{const a=o.includes("?")?"&":"?";return`${o}${a}verification_token=${encodeURIComponent(e)}`}}const F0=async o=>{if(typeof window>"u")return{status:"cancelled"};if(o.render_hint==="external_redirect"||o.redirect_url)return St.redirectExternally(o);const e=window.G7Core;if(!e?.dispatch)return console.error("[IdentityGuardInterceptor] defaultLauncher: G7Core 가 초기화되지 않아 본인인증 흐름을 시작할 수 없습니다."),{status:"failed",failureCode:"G7_NOT_READY"};try{await e.dispatch({handler:"toast",params:{message:"본인 확인이 필요합니다.",variant:"warning"}})}catch{}const a=window.location.href,r={return_url:a,payload:o,stashed_at:Date.now()};try{window.sessionStorage?.setItem(_d,JSON.stringify(r))}catch{}const i=`/identity/challenge?return=${encodeURIComponent(a)}`;try{await e.dispatch({handler:"navigate",params:{path:i}})}catch(l){Vl.warn("navigate 실패 — window.location 으로 폴백",l),window.location.href=i}return new Promise(()=>{})},K0=ct("ApiClient");function Ad(){return typeof window<"u"&&window.__G7_DEVTOOLS__?window.__G7_DEVTOOLS__:null}class W0{constructor(e={}){$(this,"client");$(this,"config");$(this,"TOKEN_KEY","auth_token");this.config={baseURL:e.baseURL||"/api",timeout:e.timeout||3e4,onTokenExpired:e.onTokenExpired,onUnauthorized:e.onUnauthorized,onError:e.onError},this.client=Pt.create({baseURL:this.config.baseURL,timeout:this.config.timeout,headers:{"Content-Type":"application/json",Accept:"application/json"},paramsSerializer:{serialize:a=>{const r=[];for(const[i,l]of Object.entries(a))if(l!=null)if(Array.isArray(l)){const u=i.endsWith("[]")?i:`${i}[]`;for(const d of l)r.push(`${encodeURIComponent(u)}=${encodeURIComponent(String(d))}`)}else r.push(`${encodeURIComponent(i)}=${encodeURIComponent(String(l))}`);return r.join("&")}}}),this.setupInterceptors()}setToken(e){typeof window<"u"&&localStorage.setItem(this.TOKEN_KEY,e)}getToken(){return typeof window<"u"?localStorage.getItem(this.TOKEN_KEY):null}removeToken(){typeof window<"u"&&localStorage.removeItem(this.TOKEN_KEY)}setupInterceptors(){this.client.interceptors.request.use(e=>{e.url?.startsWith("/api")&&e.baseURL==="/api"&&(e.baseURL="");const a=this.getToken();if(a&&e.headers&&(e.headers.Authorization=`Bearer ${a}`),typeof window<"u"&&e.headers){const i=localStorage.getItem("g7_locale");i&&(e.headers["Accept-Language"]=i)}const r=Ad();if(r?.isEnabled()){const i=this.buildFullUrl(e),l=(e.method||"GET").toUpperCase(),u=r.trackRequest(i,l,{requestBody:e.data});e._devToolsRequestId=u}return e},e=>Promise.reject(e)),this.client.interceptors.response.use(e=>{const a=e.config,r=a._devToolsRequestId;if(r){const i=Ad();i?.isEnabled()&&i.completeRequest(r,e.status,e.data),a._devToolsRequestId=null}return e},async e=>{const a=e.config,r=a?.url||"",l=["/auth/","/layouts/"].some(u=>r.includes(u));if(e.response?.status===401&&!a?._retry&&!l){if(a._retry=!0,await ha.getInstance().refreshToken()){const f=this.getToken();return f&&(a.headers.Authorization=`Bearer ${f}`),a._devToolsRequestId=null,this.client(a)}return this.completeDevToolsRequest(a,e),this.removeToken(),this.config.onUnauthorized&&this.config.onUnauthorized(),Promise.reject(e)}if(e.response?.status===401&&l)return this.completeDevToolsRequest(a,e),Promise.reject(e);if(St.isIdentityRequired(e.response?.status,e.response?.data)){this.completeDevToolsRequest(a,e);const u={},d=a?.headers??{};for(const[v,S]of Object.entries(d))typeof S=="string"&&(u[v]=S);let f;a?.data!==void 0&&a?.data!==null&&(f=typeof a.data=="string"?a.data:JSON.stringify(a.data),u["Content-Type"]=u["Content-Type"]??"application/json");const g=a?.identity_target,m=await St.handle(e.response.data,{headers:u,body:f,credentials:"same-origin"},g);if(!m)return Promise.reject(e);let b=null;try{b=await m.json()}catch{b=null}return m.ok?{...e.response,status:m.status,data:b}:Promise.reject(Object.assign(new Error("replay failed"),{response:{status:m.status,data:b}}))}return e.response?.status===403?(this.completeDevToolsRequest(a,e),this.callOnError(e),Promise.reject(e)):(this.completeDevToolsRequest(a,e),e.response&&this.callOnError(e),Promise.reject(e))})}async get(e,a){return(await this.client.get(e,a)).data}async post(e,a,r){return(await this.client.post(e,a,r)).data}async put(e,a,r){return(await this.client.put(e,a,r)).data}async patch(e,a,r){return(await this.client.patch(e,a,r)).data}async delete(e,a){return(await this.client.delete(e,a)).data}getInstance(){return this.client}setOnUnauthorized(e){this.config.onUnauthorized=e}setOnError(e){this.config.onError=e}completeDevToolsRequest(e,a){if(!e?._devToolsRequestId)return;const r=Ad();if(!r?.isEnabled())return;const i=e._devToolsRequestId;e._devToolsRequestId=null,a.response?r.completeRequest(i,a.response.status,a.response.data):a.request?r.failRequest(i,a.message||"Network error"):r.failRequest(i,a.message||"Request error")}buildFullUrl(e){let a=e.url||"";if(e.baseURL&&!a.startsWith("http")&&(a=`${e.baseURL}${a.startsWith("/")?"":"/"}${a}`),e.params&&typeof e.params=="object"){const r=e.params,i=[];for(const[l,u]of Object.entries(r))if(u!=null)if(Array.isArray(u)){const d=l.endsWith("[]")?l:`${l}[]`;for(const f of u)i.push(`${encodeURIComponent(d)}=${encodeURIComponent(String(f))}`)}else i.push(`${encodeURIComponent(l)}=${encodeURIComponent(String(u))}`);i.length>0&&(a+=(a.includes("?")?"&":"?")+i.join("&"))}return a}callOnError(e){if(!this.config.onError)return;const a={status:e.response?.status||0,message:e.response?.data?.message||e.message||"Unknown error",data:e.response?.data,statusText:e.response?.statusText};try{this.config.onError(a)}catch(r){K0.error("Error in onError handler:",r)}}}let xd=null;function $a(){return xd||(xd=new W0),xd}const so=ct("AuthManager");function ts(o,e,a,r){try{window.G7Core?.devTools?.trackAuthEvent?.(o,e,a,r)}catch{}}const Fl={admin:{type:"admin",loginPath:"/admin/login",defaultPath:"/admin",userEndpoint:"/admin/auth/user",loginEndpoint:"/auth/admin/login",logoutEndpoint:"/admin/auth/logout",refreshEndpoint:"/admin/auth/refresh"},user:{type:"user",loginPath:"/login",defaultPath:"/",userEndpoint:"/auth/user",loginEndpoint:"/auth/login",logoutEndpoint:"/auth/logout",refreshEndpoint:"/auth/refresh"}},wa=class wa{constructor(){$(this,"state");$(this,"config");$(this,"isRefreshing",!1);$(this,"refreshPromise",null);$(this,"eventHandlers",new Map);this.state={isAuthenticated:!1,user:null,type:null},this.config=new Map,this.config.set("admin",Fl.admin),this.config.set("user",Fl.user)}static getInstance(){return wa.instance||(wa.instance=new wa),wa.instance}on(e,a){this.eventHandlers.has(e)||this.eventHandlers.set(e,[]),this.eventHandlers.get(e).push(a)}emit(e,...a){const r=this.eventHandlers.get(e);r&&r.forEach(i=>i(...a))}isAuthenticated(){return this.state.isAuthenticated}getUser(){return this.state.user}getAuthType(){return this.state.type}async checkAuth(e){const a=$a();if(!a.getToken())return this.clearState(),!1;const i=this.config.get(e);if(!i)return so.error(`Unknown auth type: ${e}`),!1;try{const l=await a.get(i.userEndpoint);return l.success&&l.data?(this.state={isAuthenticated:!0,user:l.data,type:e},this.emit("authStateChange",this.state),!0):(this.clearState(),!1)}catch(l){return l.response?.status===401&&await this.refreshToken()?this.checkAuth(e):(this.clearState(),!1)}}async preloadAuth(e){try{return await this.checkAuth(e)}catch(a){return so.warn(`Preload auth failed for type ${e}:`,a),!1}}async login(e,a,r){const i=$a();if(!this.config.get(e))throw new Error(`Unknown auth type: ${e}`);const u=e==="admin"?Fl.admin.loginEndpoint:Fl.user.loginEndpoint;try{const d=r?.headers?{headers:r.headers}:void 0,f=await i.post(u,a,d);if(f.success&&f.data){i.setToken(f.data.token);const g=f.data.user.language,m=localStorage.getItem(wa.LOCALE_STORAGE_KEY),b=g&&g!==m;if(g)try{localStorage.setItem(wa.LOCALE_STORAGE_KEY,g)}catch(v){so.warn("Failed to save user language to localStorage:",v)}return this.state={isAuthenticated:!0,user:f.data.user,type:e},this.emit("login",this.state),this.emit("authStateChange",this.state),ts("login",!0,void 0,{userId:f.data.user.uuid,email:f.data.user.email,type:e}),b&&window.__templateApp&&window.__templateApp.changeLocale(g),f.data.user}throw new Error("Login failed")}catch(d){this.clearState();const f=d.response?.data?.message,g=new Error(f||d.message||"Login failed");throw g.response=d.response,g.status=d.response?.status,ts("login",!1,g.message,{type:e,status:d.response?.status}),g}}async logout(){const e=$a(),a=this.state.type?this.config.get(this.state.type):null;try{a&&await e.post(a.logoutEndpoint)}catch(r){so.warn("Logout API call failed:",r)}finally{e.removeToken();const r={...this.state};if(this.clearState(),this.emit("logout",r),this.emit("authStateChange",this.state),ts("logout",!0,void 0,{previousType:r.type}),a&&r.type){const i=window.location.pathname+window.location.search;window.location.href=this.getLoginRedirectUrl(r.type,i)}}}async refreshToken(){if(this.isRefreshing&&this.refreshPromise)return this.refreshPromise;this.isRefreshing=!0,this.refreshPromise=this.doRefreshToken();try{return await this.refreshPromise}finally{this.isRefreshing=!1,this.refreshPromise=null}}async doRefreshToken(){const e=this.state.type;if(!e)return!1;const a=this.config.get(e);if(!a)return!1;const r=$a();try{const i=await r.post(a.refreshEndpoint);return i.success&&i.data?.token?(r.setToken(i.data.token),this.emit("tokenRefreshed"),ts("token-refresh",!0,void 0,{type:e}),!0):(ts("token-refresh",!1,"No token in response",{type:e}),!1)}catch(i){return so.error("Token refresh failed:",i),ts("token-refresh",!1,i instanceof Error?i.message:"Unknown error",{type:e}),!1}}getLoginRedirectUrl(e,a,r){const i=this.config.get(e);if(!i)return"/login";const l=encodeURIComponent(a);let u=`${i.loginPath}?redirect=${l}`;return r&&(u+=`&reason=${encodeURIComponent(r)}`),u}updateConfig(e,a){if(a.loginPath!==void 0){const i=a.loginPath;if(!i.startsWith("/")||i.startsWith("//"))throw new Error(`AuthManager.updateConfig: loginPath must be a same-origin path starting with '/' (got: ${i})`)}const r=this.config.get(e);r&&this.config.set(e,{...r,...a})}getRedirectUrl(e){const r=this.config.get(e)?.defaultPath||"/",l=new URLSearchParams(window.location.search).get("redirect");if(l)try{const u=decodeURIComponent(l);if(u.startsWith("/"))return u}catch{}return r}getConfig(e){return this.config.get(e)}clearState(){this.state={isAuthenticated:!1,user:null,type:null}}static resetInstance(){wa.instance=null}};$(wa,"instance"),$(wa,"LOCALE_STORAGE_KEY","g7_locale");let ha=wa;const Kp={401:{handler:"navigate",params:{path:"{{auth.loginPath}}"}},403:{handler:"toast",params:{type:"error",message:"{{error.message}}"}},404:{handler:"toast",params:{type:"error",message:"{{error.message}}"}},422:{handler:"toast",params:{type:"error",message:"{{error.message}}"}},default:{handler:"toast",params:{type:"error",message:"{{error.message}}"}}},Ja={findHandler(o,e){if(o){if(o[e])return o[e];if(o[String(e)])return o[String(e)];if(o.default)return o.default}},normalizeOnError(o){return o?Array.isArray(o)?o:[o]:[]},injectErrorCode(o,e,a){if(o.handler!=="showErrorPage"||o.params?.errorCode!==void 0)return o;const r=typeof e=="string"?parseInt(e,10):e,i=isNaN(r)?a:r;return i===void 0?o:{...o,params:{...o.params,errorCode:i}}}},ga=ct("ErrorHandlingResolver"),kr=class kr{constructor(){$(this,"templateErrorHandling",null);$(this,"layoutErrorHandling",null);$(this,"executeAction",null)}static getInstance(){return kr.instance||(kr.instance=new kr),kr.instance}static resetInstance(){kr.instance=null}setTemplateConfig(e){this.templateErrorHandling=e,ga.log("Template config set:",e)}setLayoutConfig(e){this.layoutErrorHandling=e,ga.log("Layout config set:",e)}setActionExecutor(e){this.executeAction=e}resolve(e,a={}){const{errorHandling:r,onError:i}=a;ga.log("Resolving error:",e,{hasActionErrorHandling:!!r,hasActionOnError:!!i,hasLayoutConfig:!!this.layoutErrorHandling,hasTemplateConfig:!!this.templateErrorHandling});let l=Ja.findHandler(r,e);if(l){const u=this.getMatchedKey(r,e);return{handler:Ja.injectErrorCode(l,u,e),level:"action",matchedKey:u}}if(i){const u=Ja.normalizeOnError(i);if(u.length>0)return{handler:u.length===1?u[0]:{handler:"sequence",actions:u},level:"action",matchedKey:"onError"}}if(l=Ja.findHandler(this.layoutErrorHandling||void 0,e),l){const u=this.getMatchedKey(this.layoutErrorHandling,e);return{handler:Ja.injectErrorCode(l,u,e),level:"layout",matchedKey:u}}if(l=Ja.findHandler(this.templateErrorHandling||void 0,e),l){const u=this.getMatchedKey(this.templateErrorHandling,e);return{handler:Ja.injectErrorCode(l,u,e),level:"template",matchedKey:u}}if(l=Ja.findHandler(Kp,e),l){const u=this.getMatchedKey(Kp,e);return{handler:Ja.injectErrorCode(l,u,e),level:"system",matchedKey:u}}return{handler:null,level:null,matchedKey:null}}async execute(e,a){if(!this.executeAction){ga.error("Action executor is not set");return}ga.log("Executing handler:",e.handler,{errorContext:a});try{return await this.executeAction(e,{error:a})}catch(r){throw ga.error("Failed to execute handler:",r),r}}async resolveAndExecute(e,a,r={}){const i=this.resolve(e,r);if(ga.log("Resolve result:",{errorCode:e,handler:i.handler?.handler,level:i.level,matchedKey:i.matchedKey}),!i.handler)return ga.warn("No handler found for error:",e),{handled:!1};try{return{handled:!0,result:await this.execute(i.handler,a)}}catch(l){return ga.error("Handler execution failed:",l),{handled:!1}}}getMatchedKey(e,a){return e[a]?a:e[String(a)]?String(a):"default"}clearLayoutConfig(){this.layoutErrorHandling=null,ga.log("Layout config cleared")}clearAllConfig(){this.templateErrorHandling=null,this.layoutErrorHandling=null,ga.log("All config cleared")}getConfigStatus(){return{hasTemplate:this.templateErrorHandling!==null,hasLayout:this.layoutErrorHandling!==null,hasExecutor:this.executeAction!==null}}};$(kr,"instance",null);let Td=kr;function pa(){return Td.getInstance()}var Rd={exports:{}},oo={};var Wp;function Y0(){if(Wp)return oo;Wp=1;var o=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function a(r,i,l){var u=null;if(l!==void 0&&(u=""+l),i.key!==void 0&&(u=""+i.key),"key"in i){l={};for(var d in i)d!=="key"&&(l[d]=i[d])}else l=i;return i=l.ref,{$$typeof:o,type:r,key:u,ref:i!==void 0?i:null,props:l}}return oo.Fragment=e,oo.jsx=a,oo.jsxs=a,oo}var Yp;function X0(){return Yp||(Yp=1,Rd.exports=Y0()),Rd.exports}var ut=X0();const J0=Wa({__proto__:null,default:Ya(ut)},[ut]),kd=ct("ParentContextProvider"),Xp=N.createContext(null);let Kl=null;function Dd(){Kl?(kd.log("[triggerModalParentUpdate] 모달 부모 컨텍스트 업데이트 트리거"),Kl()):kd.warn("[triggerModalParentUpdate] Provider가 아직 마운트되지 않음")}const Jp=({children:o})=>{const[e,a]=N.useState(0),r=N.useRef(!0),i=N.useCallback(()=>{const u=window.__g7LayoutContextStack||[];return u[u.length-1]?.dataContext},[]);N.useEffect(()=>(r.current=!0,Kl=()=>{r.current&&(a(u=>u+1),kd.log("[ParentContextProvider] 버전 업데이트됨"))},()=>{r.current=!1,Kl=null}),[]);const l={version:e,getParentDataContext:i};return ut.jsx(Xp.Provider,{value:l,children:o})};function Q0(){return N.useContext(Xp)}const H=ct("ActionDispatcher"),Qp=new Set(["navigate","navigateBack","navigateForward","replaceUrl","refresh","logout"]),Z0=new Set(["redirect"]);function Un(){try{return window.G7Core?.devTools}catch{return}}class It extends Error{constructor(a,r,i){super(a);$(this,"action");$(this,"originalError");$(this,"unknownHandler",!1);this.action=r,this.originalError=i,this.name="ActionError"}}const us=class us{constructor(e={},a,r){$(this,"bindingEngine");$(this,"translationEngine");$(this,"translationContext");$(this,"customHandlers",new Map);$(this,"defaultContext");$(this,"globalStateUpdater");$(this,"errorHandlingSetup",!1);$(this,"debounceTimers",new Map);$(this,"pendingDebounceFlushers",new Map);$(this,"debounceAccumulatedValues",new Map);$(this,"globalHeaders",[]);$(this,"namedActions",{});$(this,"previewMode",!1);$(this,"intervals",new Map);this.bindingEngine=new wn,this.translationEngine=a,this.translationContext=r,this.defaultContext=e,this.registerDefaultHandlers(),this.setupErrorHandling()}setGlobalHeaders(e){this.globalHeaders=e||[]}setNamedActions(e){this.namedActions=e||{};const a=Un();a?.isEnabled?.()&&a.setNamedActionDefinitions?.(this.namedActions),H.log("[setNamedActions] registered:",Object.keys(this.namedActions))}getNamedActions(){return this.namedActions}setPreviewMode(e){this.previewMode=e,H.log("Preview mode:",e?"enabled":"disabled")}isPreviewMode(){return this.previewMode}static getPreviewSuppressedHandlers(){return Qp}static getPreviewSuppressedLayoutFeatures(){return Z0}resolveActionRef(e){if(!e.actionRef)return e;const a=this.namedActions[e.actionRef];if(!a)return H.warn(`[resolveActionRef] named action not found: "${e.actionRef}"`),e;const r=Un();r?.isEnabled?.()&&r.trackNamedActionRef?.({actionRefName:e.actionRef,resolvedHandler:a.handler,timestamp:Date.now()});const{actionRef:i,type:l,key:u,event:d,...f}=e,g={...a,...Object.fromEntries(Object.entries(f).filter(([,m])=>m!==void 0)),type:l??a.type};return u!==void 0&&(g.key=u),d!==void 0&&(g.event=d),g}matchesPattern(e,a){if(a==="*")return!0;const r=a.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(e)}getMatchingGlobalHeaders(e,a){const r={};for(const i of this.globalHeaders)this.matchesPattern(e,i.pattern)&&Object.entries(i.headers).forEach(([l,u])=>{const d=Ji(u,a,{skipCache:!0});d!=null&&d!==""&&(r[l]=String(d))});return r}setupErrorHandling(){if(this.errorHandlingSetup)return;pa().setActionExecutor(async(a,r)=>{const i={type:"click",handler:a.handler,target:a.target,params:a.params,actions:a.actions},l={data:{...this.defaultContext.data,error:r.error}};return await this.dispatchAction(i,l)}),this.errorHandlingSetup=!0}registerDefaultHandlers(){this.registerHandler("refetchDataSource",async(a,r)=>{const i=a.params?.dataSourceId,l=a.params?.sync;if(!i){H.warn("refetchDataSource: dataSourceId is required");return}if(typeof window<"u"&&window.G7Core?.dataSource?.refetch){const u=window.G7Core?.state?.get?.()||{},d={...r.state?._global,...u},f=window.G7Core?.state?.getLocal?.()||{},g=r.data?._local||r.state||{},m={...f,...g},b=r.isolatedContext?.state;H.log("[refetchDataSource] localStateOverride:",m),await window.G7Core.dataSource.refetch(i,{...l?{sync:!0}:{},...d?{globalStateOverride:d}:{},...m?{localStateOverride:m}:{},...b?{isolatedStateOverride:b}:{}})}else H.warn("refetchDataSource: G7Core.dataSource.refetch is not available")}),this.registerHandler("appendDataSource",async(a,r)=>{const{dataSourceId:i,dataPath:l,newData:u}=a.params||{};if(!i){H.warn("appendDataSource: dataSourceId is required");return}if(u===void 0){H.warn("appendDataSource: newData is required");return}if(typeof window<"u"&&window.G7Core?.dataSource?.updateData){if(!Array.isArray(u)){H.warn("appendDataSource: newData must be an array, got:",typeof u,u);return}await window.G7Core.dataSource.updateData(i,l||null,u,"append")}else H.warn("appendDataSource: G7Core.dataSource.updateData is not available")}),this.registerHandler("updateDataSource",async(a,r)=>{const{dataSourceId:i,data:l,merge:u=!1}=a.params||{};if(!i){H.warn("updateDataSource: dataSourceId is required");return}if(l===void 0){H.warn("updateDataSource: data is required");return}typeof window<"u"&&window.G7Core?.dataSource?.set?(H.log(`[updateDataSource] Updating dataSource '${i}' with:`,l),window.G7Core.dataSource.set(i,l,{merge:u})):H.warn("updateDataSource: G7Core.dataSource.set is not available")}),this.registerHandler("scrollIntoView",async(a,r)=>{const{selector:i,behavior:l="smooth",block:u="nearest",inline:d="nearest",waitForElement:f=!1,timeout:g=2e3,delay:m=0,retryCount:b=0,retryInterval:v=50,scrollContainer:S}=a.params||{};if(!i){H.warn("scrollIntoView: selector is required");return}if(typeof window>"u"||typeof document>"u"){H.warn("scrollIntoView: window/document is not available");return}let E=null;if(f){if(E=await new Promise(A=>{const T=document.querySelector(i);if(T){A(T);return}const L=setTimeout(()=>{M.disconnect(),A(null)},g),M=new MutationObserver(()=>{const R=document.querySelector(i);R&&(clearTimeout(L),M.disconnect(),A(R))});M.observe(document.body,{childList:!0,subtree:!0})}),!E){H.warn(`scrollIntoView: element not found for selector "${i}" after ${g}ms timeout`);return}}else{m>0&&await new Promise(T=>setTimeout(T,m)),E=document.querySelector(i);let A=0;for(;!E&&AsetTimeout(T,v)),E=document.querySelector(i),A++;if(!E){H.warn(`scrollIntoView: element not found for selector "${i}" after ${A+1} attempts`);return}}if(S){const A=document.querySelector(S);if(!A){H.warn(`scrollIntoView: container not found for selector "${S}"`);return}const T=E.getBoundingClientRect(),L=A.getBoundingClientRect(),M=T.top-L.top+A.scrollTop,R=M+T.height;let D;switch(u){case"start":D=M;break;case"center":D=M-A.clientHeight/2+T.height/2;break;case"end":D=R-A.clientHeight;break;default:const U=T.topL.bottom;if(U)D=M;else if(j)D=R-A.clientHeight;else return;break}A.scrollTo({top:Math.max(0,D),behavior:l});return}E.scrollIntoView({behavior:l,block:u,inline:d})}),this.registerHandler("reloadExtensions",async(a,r)=>{if(typeof window>"u"){H.warn("reloadExtensions: window is not available");return}const i=window.__templateApp;if(!i){H.warn("reloadExtensions: TemplateApp not initialized");return}if(typeof i.reloadExtensionState=="function")try{await i.reloadExtensionState()}catch(d){throw H.error("reloadExtensions: reloadExtensionState failed",d),d}else H.warn("reloadExtensions: TemplateApp.reloadExtensionState unavailable");const{moduleInfo:l,pluginInfo:u}=a.params||{};if(l)try{await this.executeAction({handler:"reloadModuleHandlers",params:a.params},r)}catch(d){H.error("reloadExtensions: reloadModuleHandlers failed",d)}if(u)try{await this.executeAction({handler:"reloadPluginHandlers",params:a.params},r)}catch(d){H.error("reloadExtensions: reloadPluginHandlers failed",d)}H.log("reloadExtensions: done")}),this.registerHandler("reloadRoutes",async(a,r)=>{if(typeof window>"u"){H.warn("reloadRoutes: window is not available");return}const i=window.__templateApp;if(!i){H.warn("reloadRoutes: TemplateApp not initialized");return}if(typeof i.reloadExtensionState=="function")try{await i.reloadExtensionState(),H.log("reloadRoutes: delegated to reloadExtensionState")}catch(l){throw H.error("reloadRoutes: Failed to reload routes",l),l}else{const l=i.getRouter?.();l&&(await l.loadRoutes(),H.log("reloadRoutes: Routes reloaded (legacy fallback)"))}}),this.registerHandler("refresh",async(a,r)=>{if(typeof window>"u"){H.warn("refresh: window is not available");return}const i=Number(a.params?.delayMs??0);i>0&&await new Promise(l=>setTimeout(l,i)),window.location.reload()}),this.registerHandler("remount",async(a,r)=>{const{componentId:i}=a.params||{};if(!i){H.warn("remount: componentId parameter is required");return}if(!this.globalStateUpdater){H.warn("remount: globalStateUpdater is not set");return}const d=(window.G7Core?.state?.get()||{})._global?._remountKeys||{},f=d[i]||0;this.globalStateUpdater({_remountKeys:{...d,[i]:f+1}}),H.log(`remount: ${i} key incremented to ${f+1}`)}),this.registerHandler("reloadTranslations",async(a,r)=>{if(typeof window>"u"){H.warn("reloadTranslations: window is not available");return}const i=window.__templateApp;if(!i){H.warn("reloadTranslations: TemplateApp not initialized");return}if(typeof i.reloadExtensionState=="function")try{await i.reloadExtensionState(),H.log("reloadTranslations: delegated to reloadExtensionState")}catch(l){throw H.error("reloadTranslations: Failed to reload translations",l),l}}),this.registerHandler("reloadModuleHandlers",async(a,r)=>{if(typeof window>"u"){H.warn("reloadModuleHandlers: window is not available");return}const{moduleInfo:i,action:l}=a.params||{};if(!i){H.warn("reloadModuleHandlers: moduleInfo is required");return}const u=i.data||i;if(!u.identifier){H.warn("reloadModuleHandlers: moduleInfo with identifier is required");return}if(!l||l!=="add"&&l!=="remove"){H.warn('reloadModuleHandlers: action must be "add" or "remove"');return}const d=window.G7Config;if(!d){H.warn("reloadModuleHandlers: G7Config not available");return}const f=u.identifier;try{if(l==="add"){if(u.assets&&(d.moduleAssets=d.moduleAssets||{},d.moduleAssets[f]=u.assets,H.log(`reloadModuleHandlers: Added assets for ${f}`),u.assets.js)){const g=u.assets.js,m=`module-${f}`;if(document.getElementById(m)){H.warn(`reloadModuleHandlers: Script ${m} already loaded`);return}const b=document.createElement("script");if(b.id=m,b.src=g,b.async=!0,await new Promise((v,S)=>{b.onload=()=>{H.log(`reloadModuleHandlers: Script loaded successfully for ${f}`),v()},b.onerror=()=>{H.error(`reloadModuleHandlers: Failed to load script for ${f}`),S(new Error(`Failed to load module script: ${g}`))},document.head.appendChild(b)}),u.assets.css){const v=u.assets.css,S=`module-css-${f}`;if(!document.getElementById(S)){const E=document.createElement("link");E.id=S,E.rel="stylesheet",E.href=v,document.head.appendChild(E),H.log(`reloadModuleHandlers: CSS loaded for ${f}`)}}}}else if(l==="remove"){d.moduleAssets&&d.moduleAssets[f]&&(delete d.moduleAssets[f],H.log(`reloadModuleHandlers: Removed assets for ${f}`));const g=`module-${f}`,m=document.getElementById(g);m&&(m.remove(),H.log(`reloadModuleHandlers: Removed script for ${f}`));const b=`module-css-${f}`,v=document.getElementById(b);v&&(v.remove(),H.log(`reloadModuleHandlers: Removed CSS for ${f}`))}}catch(g){throw H.error(`reloadModuleHandlers: Failed to ${l} module assets`,g),g}}),this.registerHandler("reloadPluginHandlers",async(a,r)=>{if(typeof window>"u"){H.warn("reloadPluginHandlers: window is not available");return}const{pluginInfo:i,action:l}=a.params||{};if(!i){H.warn("reloadPluginHandlers: pluginInfo is required");return}const u=i.data||i;if(!u.identifier){H.warn("reloadPluginHandlers: pluginInfo with identifier is required");return}if(!l||l!=="add"&&l!=="remove"){H.warn('reloadPluginHandlers: action must be "add" or "remove"');return}const d=window.G7Config;if(!d){H.warn("reloadPluginHandlers: G7Config not available");return}const f=u.identifier;try{if(l==="add"){if(u.assets&&(d.pluginAssets=d.pluginAssets||{},d.pluginAssets[f]=u.assets,H.log(`reloadPluginHandlers: Added assets for ${f}`),u.assets.js)){const g=u.assets.js,m=`plugin-${f}`;if(document.getElementById(m)){H.warn(`reloadPluginHandlers: Script ${m} already loaded`);return}const b=document.createElement("script");if(b.id=m,b.src=g,b.async=!0,await new Promise((v,S)=>{b.onload=()=>{H.log(`reloadPluginHandlers: Script loaded successfully for ${f}`),v()},b.onerror=()=>{H.error(`reloadPluginHandlers: Failed to load script for ${f}`),S(new Error(`Failed to load plugin script: ${g}`))},document.head.appendChild(b)}),u.assets.css){const v=u.assets.css,S=`plugin-css-${f}`;if(!document.getElementById(S)){const E=document.createElement("link");E.id=S,E.rel="stylesheet",E.href=v,document.head.appendChild(E),H.log(`reloadPluginHandlers: CSS loaded for ${f}`)}}}}else if(l==="remove"){d.pluginAssets&&d.pluginAssets[f]&&(delete d.pluginAssets[f],H.log(`reloadPluginHandlers: Removed assets for ${f}`));const g=`plugin-${f}`,m=document.getElementById(g);m&&(m.remove(),H.log(`reloadPluginHandlers: Removed script for ${f}`));const b=`plugin-css-${f}`,v=document.getElementById(b);v&&(v.remove(),H.log(`reloadPluginHandlers: Removed CSS for ${f}`))}}catch(g){throw H.error(`reloadPluginHandlers: Failed to ${l} plugin assets`,g),g}});let e=!1;this.registerHandler("showErrorPage",async(a,r)=>{if(e){H.log("showErrorPage: Already active, skipping duplicate call");return}if(e=!0,typeof window>"u"){e=!1,H.warn("showErrorPage: window is not available");return}const i=window.__templateApp;if(!i){e=!1,H.warn("showErrorPage: TemplateApp not initialized");return}const l=i.getErrorPageHandler?.();if(!l){e=!1,H.warn("showErrorPage: ErrorPageHandler not available");return}const u=a.params?.errorCode||500,d=a.params?.target||"content";let f=a.params?.containerId;f||(f=d==="full"?"app":"main_content"),H.log("showErrorPage:",{errorCode:u,target:d,containerId:f});const g=(m,b=6e4)=>new Promise((v,S)=>{const E=document.getElementById(m);if(E){v(E);return}H.log(`showErrorPage: Waiting for container #${m}...`);let A;const T=new MutationObserver((L,M)=>{const R=document.getElementById(m);R&&(H.log(`showErrorPage: Container #${m} found`),M.disconnect(),clearTimeout(A),v(R))});T.observe(document.body,{childList:!0,subtree:!0}),A=setTimeout(()=>{T.disconnect(),S(new Error(`Container #${m} not found within ${b}ms`))},b)});try{await g(f);const m=pa(),b=m.layoutErrorHandling;m.clearLayoutConfig();try{await l.renderError(u,f)||H.warn(`showErrorPage: Failed to render error page for code ${u}`)}finally{m.setLayoutConfig(b)}}catch(m){throw H.error("showErrorPage: Error rendering error page:",m),m}finally{e=!1}}),this.registerHandler("emitEvent",async(a,r)=>{const i=a.params?.event,l=a.params?.data;if(!i){H.warn("emitEvent: event parameter is required");return}if(typeof window>"u"){H.warn("emitEvent: window is not available");return}const u=window.G7Core;if(!u?.componentEvent?.emit){H.warn("emitEvent: G7Core.componentEvent is not available");return}try{H.log(`emitEvent: Emitting "${i}"`,l);const d={...l,_context:{data:r.data,state:r.state}},f=await u.componentEvent.emit(i,d);if(!f||f.length===0?H.warn(`emitEvent: No listeners found for "${i}"`):H.log(`emitEvent: Event "${i}" completed with ${f.length} listener(s)`,f),this.globalStateUpdater){const g=(u?.state?.get()||{})._local||{},m={event:i,success:!0,data:f.length===1?f[0]:f,listeners:f.length};this.globalStateUpdater({_local:{...g,_eventResult:m}});const b=r.state&&typeof r.state=="object"&&!Array.isArray(r.state)?r.state:g;window.__g7SequenceLocalSync={...b,_eventResult:m}}}catch(d){if(H.error(`emitEvent: Event "${i}" failed`,d),this.globalStateUpdater){const f=u?.state?.get()||{};this.globalStateUpdater({_local:{...f._local,_eventResult:{event:i,success:!1,error:d instanceof Error?d.message:String(d)}}})}throw d}}),this.registerHandler("updateProductField",async(a,r)=>{const{productId:i,field:l,value:u}=a.params||{};if(!i||!l){H.warn("updateProductField: productId and field are required");return}if(typeof window>"u"){H.warn("updateProductField: window is not available");return}const d=window.G7Core;if(!d?.state?.get||!this.globalStateUpdater){H.warn("updateProductField: G7Core.state or globalStateUpdater is not available");return}try{const f=d.state.get()||{},m=(f.products?.data?.data||[]).map(v=>v.id===i?{...v,[l]:u,_modified:!0}:v),b=new Set(f._local?.modifiedProductIds||[]);b.add(i),this.globalStateUpdater({products:{...f.products,data:{...f.products?.data,data:m}},_local:{...f._local,modifiedProductIds:Array.from(b)}}),H.log(`updateProductField: Updated product ${i}, field: ${l}, value:`,u)}catch(f){throw H.error("updateProductField: Error updating product field",f),f}}),this.registerHandler("updateOptionField",async(a,r)=>{const{productId:i,optionId:l,field:u,value:d}=a.params||{};if(!i||!l||!u){H.warn("updateOptionField: productId, optionId and field are required");return}if(typeof window>"u"){H.warn("updateOptionField: window is not available");return}const f=window.G7Core;if(!f?.state?.get||!this.globalStateUpdater){H.warn("updateOptionField: G7Core.state or globalStateUpdater is not available");return}try{const g=f.state.get()||{},b=(g.products?.data?.data||[]).map(S=>{if(S.id===i&&S.options){const E=S.options.map(A=>A.id===l?{...A,[u]:d,_modified:!0}:A);return{...S,options:E,_modified:!0}}return S}),v=new Set(g._local?.modifiedProductIds||[]);v.add(i),this.globalStateUpdater({products:{...g.products,data:{...g.products?.data,data:b}},_local:{...g._local,modifiedProductIds:Array.from(v)}}),H.log(`updateOptionField: Updated product ${i} option ${l}, field: ${u}, value:`,d)}catch(g){throw H.error("updateOptionField: Error updating option field",g),g}}),this.registerHandler("setLocale",async(a,r)=>{const i=a.target;if(!i||typeof i!="string"){H.warn("setLocale: Invalid locale:",i);return}const l=window.__templateApp;if(l&&typeof l.changeLocale=="function")try{await l.changeLocale(i),H.log("setLocale: Locale changed to",i)}catch(u){H.error("setLocale: Failed to change locale:",u),window.location.reload()}else{H.warn("setLocale: TemplateApp not found, falling back to page reload");try{localStorage.setItem("g7_locale",i)}catch{}window.location.reload()}}),this.registerHandler("suppress",async()=>{H.log("suppress: Error intentionally suppressed")}),this.registerBuiltInHandlerMetadata()}registerBuiltInHandlerMetadata(){const e=Un();if(!e?.isEnabled())return;const a=[{name:"refetchDataSource",description:"데이터 소스를 다시 fetch합니다"},{name:"appendDataSource",description:"데이터 소스에 새 데이터를 병합합니다 (무한 스크롤용)"},{name:"updateDataSource",description:"API 응답으로 데이터 소스를 직접 업데이트합니다 (refetch 대체)"},{name:"reloadRoutes",description:"라우트를 다시 로드합니다"},{name:"refresh",description:"현재 페이지를 새로고침합니다"},{name:"remount",description:"컴포넌트를 리마운트합니다"},{name:"reloadTranslations",description:"다국어 파일을 다시 로드합니다"},{name:"showErrorPage",description:"에러 페이지를 표시합니다"},{name:"emitEvent",description:"이벤트를 발생시킵니다"},{name:"updateProductField",description:"상품 필드를 인라인 수정합니다"},{name:"updateOptionField",description:"상품 옵션 필드를 인라인 수정합니다"},{name:"setLocale",description:"언어를 변경합니다 (DB 저장 + UI 리렌더링)"}];for(const r of a)e.trackHandlerRegistration(r.name,"built-in",r.description)}createHandler(e,a,r){H.log("createHandler called for:",e.handler,e.type);const i=window.__g7DevTools,l=Date.now(),u=r?.state?{...r.state}:null,d=`handler_${e.handler}_${l}`;return async f=>{if(H.log("Handler invoked for:",e.handler,"event:",f.type),i?.isEnabled?.()&&u){const m=window.G7Core?.state?.getLocal?.()??r?.state??{},b=Date.now()-l;for(const v of Object.keys(u)){const S=u[v],E=m[v];S!==E&&b>100&&(i.trackStaleClosureWarning?.({type:"event-handler-stale",location:`createHandler(${e.handler})`,capturedPath:`_local.${v}`,capturedValue:S,capturedAt:l,currentValue:E,actionId:d,stackTrace:new Error().stack}),H.warn(`[Stale Closure] _local.${v} changed after handler creation:`,`captured="${S}" → current="${E}" (${b}ms ago)`))}}try{f.type!=="change"&&f.preventDefault();let g={};if(f.type==="submit"&&f.target instanceof HTMLFormElement){const v=f.target;new FormData(v).forEach((E,A)=>{g[A]=E})}const m={...this.defaultContext,data:{...a,form:g,_local:r?.state||{},$event:f},event:f,...r&&{state:r.state,setState:r.setState},isolatedContext:r?.isolatedContext};if(e.confirm){let v=this.resolveValue(e.confirm,m.data);if(this.translationEngine&&this.translationContext&&v.startsWith("$t:")&&(v=this.translationEngine.resolveTranslations(v,this.translationContext,m.data)),!confirm(v))return}const b=window.__g7ActionContext;window.__g7ActionContext={...r,data:m.data};try{await this.executeAction(e,m)}finally{window.__g7ActionContext=b}}catch(g){if(H.error("Action execution failed:",g),e.onError){const m=g instanceof It&&g.originalError?g.originalError:g,b={...this.defaultContext,data:{...a,error:m,_local:r?.state||{},$event:f},event:f,...r&&{state:r.state,setState:r.setState}},v=Array.isArray(e.onError)?e.onError:[e.onError];for(const S of v)await this.executeAction(S,b)}}}}generateActionId(e,a){const r=e.handler,i=a||"no-target",l=Date.now(),u=Math.random().toString(36).substring(2,9);return`${r}_${i.replace(/[^a-zA-Z0-9]/g,"_")}_${l}_${u}`}async executeAction(e,a){if(e=this.resolveActionRef(e),typeof e.handler=="string"&&e.handler.includes("{{")){const f=this.evaluateExpression(e.handler,a.data);e={...e,handler:f==null?"":String(f)}}const r=Un(),i=r?.isEnabled()?`action_${Date.now()}_${Math.random().toString(36).substring(2,11)}`:void 0,l=performance.now();let u;if(i&&r&&r.logAction({id:i,type:e.handler,params:this.sanitizeForDevTools(e.params),context:this.sanitizeForDevTools({hasState:!!a.state,hasSetState:!!a.setState,dataKeys:a.data?Object.keys(a.data):[]}),startTime:l,status:"started"}),e.if!==void 0)try{const f=this.resolveValue(e.if,a.data),g=f===!0||f==="true"||f&&f!=="false"&&f!=="0"&&f!==!1;if(H.log("[executeAction] if condition result:",e.handler,g),!g)return i&&r&&r.logAction({id:i,type:e.handler,startTime:l,endTime:performance.now(),duration:performance.now()-l,status:"success",result:{skipped:!0,reason:"if condition false"}}),{success:!0,data:void 0}}catch(f){return H.error("[executeAction] if condition error:",e.handler,f),i&&r&&r.logAction({id:i,type:e.handler,startTime:l,endTime:performance.now(),duration:performance.now()-l,status:"error",error:{name:"ConditionEvaluationError",message:f instanceof Error?f.message:String(f),stack:f instanceof Error?f.stack:void 0}}),{success:!0,data:void 0}}let d;try{const f=this.resolveParams(e.params,a.data);i&&(u=this.sanitizeForDevTools(f));const g=e.target?this.resolveValue(e.target,a.data):void 0;if(e.handler==="apiCall"&&a.setState){d=this.generateActionId(e,g);const b=a.state?.loadingActions||{};a.setState({loadingActions:{...b,[d]:!0}})}if(this.previewMode&&Qp.has(e.handler))return H.warn(`Preview mode: "${e.handler}" suppressed`,g||f),i&&r&&r.logAction({id:i,type:e.handler,startTime:l,endTime:performance.now(),duration:performance.now()-l,status:"skipped",metadata:{reason:"preview_mode_suppressed"}}),{success:!0,data:void 0};let m;switch(e.handler){case"ensureIdentityVerified":m=await this.handleEnsureIdentityVerified(f);break;case"resolveIdentityChallenge":m=this.handleResolveIdentityChallenge(f);break;case"navigate":const b=f.path||g;m=await this.handleNavigate(b,f,a);break;case"navigateBack":m=await this.handleNavigateBack();break;case"navigateForward":m=await this.handleNavigateForward();break;case"openWindow":{const E=f.path||g;m=await this.handleOpenWindow(E,f);break}case"replaceUrl":{const E=f.path||g||window.location.pathname;m=await this.handleReplaceUrl(E,f);break}case"apiCall":if(e.onSuccess&&r?.isEnabled()&&i){const E=window.G7Core,A={};if(E?.state?.get){const T=E.state.get();A._global=T}a.state&&(A._local=a.state),r.registerStateCaptureForHandler?.(i,["_global","_local"],A)}const v=e.auth_mode??(e.auth_required?"required":"none"),S=e.identity_target?this.resolveParams(e.identity_target,a.data):void 0;m=await this.handleApiCall(g,f,a,v,S);break;case"login":m=await this.handleLogin(g,f,a);break;case"logout":m=await this.handleLogout(g,a);break;case"setState":H.log("[executeAction] setState resolvedParams:",f),m=await this.handleSetState(e.render!==void 0?{...f,__render:e.render}:f,a);break;case"setError":m=await this.handleSetError(g,f,a);break;case"openModal":m=await this.handleOpenModal(g,a);break;case"closeModal":m=await this.handleCloseModal(a);break;case"showAlert":m=await this.handleShowAlert(g,a);break;case"toast":m=await this.handleToast(f,a);break;case"switch":m=await this.handleSwitch(e,a);break;case"conditions":m=await this.handleConditions(e,a);break;case"sequence":m=await this.handleSequence(e,a);break;case"parallel":m=await this.handleParallel(e,a);break;case"startInterval":m=this.handleStartInterval(f,a);break;case"stopInterval":m=this.handleStopInterval(f);break;case"loadScript":m=await this.handleLoadScript(f,e,a);break;case"callExternal":m=await this.handleCallExternal(f,e,a);break;case"callExternalEmbed":m=await this.handleCallExternalEmbed(f,e,a);break;case"saveToLocalStorage":m=await this.handleSaveToLocalStorage(f,a);break;case"loadFromLocalStorage":m=await this.handleLoadFromLocalStorage(f,a);break;default:m=await this.handleCustomAction({...e,target:g,params:f},a);break}if(e.resultTo&&m!==void 0){const{target:b,key:v,merge:S}=e.resultTo,E=this.resolveValue(v,a.data),A=S==="replace"?"replace":S==="shallow"?"shallow":"deep";if(b==="_local"&&a.setState){const T=this.buildNestedUpdate(E,m),L=A!=="deep"?{...T,__mergeMode:A}:T;a.setState(L),H.log(`[resultTo] Saved to _local.${E} (merge=${A}):`,m)}else if(b==="_local"&&this.globalStateUpdater){const M=(window.G7Core?.state?.get()||{})._local||{},R=this.buildNestedUpdate(E,m);let D;A==="replace"?D=R:A==="shallow"?D={...M,...R}:D=this.deepMergeWithState(R,M),this.globalStateUpdater({_local:D}),H.log(`[resultTo] Saved to _local.${E} via globalStateUpdater (merge=${A}):`,m)}else if(b==="_global"&&this.globalStateUpdater){const T=this.buildNestedUpdate(E,m);this.globalStateUpdater(T),H.log(`[resultTo] Saved to _global.${E}:`,m)}else if(b==="_isolated"&&a.isolatedContext){const T=this.buildNestedUpdate(E,m);a.isolatedContext.mergeState(T,A),H.log(`[resultTo] Saved to _isolated.${E} (merge=${A}):`,m)}else H.warn(`[resultTo] Cannot save result: target=${b}, setState=${!!a.setState}, globalStateUpdater=${!!this.globalStateUpdater}, isolatedContext=${!!a.isolatedContext}`)}if(e.onSuccess){if(r?.isEnabled()&&i&&e.handler==="apiCall"){const S=window.G7Core,E={};S?.state?.get&&(E._global=S.state.get()),a.state&&(E._local=a.state),r.detectStaleClosure?.(i,`${e.handler} → onSuccess`,E,"callback-state-capture",i)}const b={...a,data:{...a.data,result:m,response:m}},v=Array.isArray(e.onSuccess)?e.onSuccess:[e.onSuccess];v.length>1?await this.handleSequence({handler:"sequence",type:"click",actions:v},b):v.length===1&&await this.executeAction(v[0],b)}return i&&r&&r.logAction({id:i,type:e.handler,params:this.sanitizeForDevTools(e.params),resolvedParams:u,startTime:l,endTime:performance.now(),duration:performance.now()-l,status:"success",result:this.sanitizeForDevTools(m)}),{success:!0,data:m}}catch(f){const g=f instanceof It?f:new It(`Failed to execute action: ${e.handler}`,e,f instanceof Error?f:void 0),m=g.originalError?.response||{},b=m.data||{},v=g.originalError?.status||m.status||500,S=b.message||g.message,E={status:v,message:S,errors:b.errors||m.errors,data:b,statusText:g.originalError?.statusText,error_code:b.error_code??m.error_code};if(g.unknownHandler)throw H.warn(`Unknown action handler "${e.handler}" — skipped (extension not loaded?). Not surfaced to the user.`),g;const T=pa().resolve(v,{errorHandling:e.errorHandling,onError:e.onError});if(T.handler){if(r?.isEnabled()&&i&&e.handler==="apiCall"){const M=window.G7Core,R={};M?.state?.get&&(R._global=M.state.get()),a.state&&(R._local=a.state),r.detectStaleClosure?.(i,`${e.handler} → onError`,R,"callback-state-capture",i)}const L={...a,data:{...a.data,error:E}};try{const M={type:"click",handler:T.handler.handler,target:T.handler.target,params:T.handler.params,actions:T.handler.actions};return await this.executeAction(M,L),{success:!1,error:g}}catch(M){return H.error("Error executing error handler:",M),{success:!1,error:g}}}throw i&&r&&r.logAction({id:i,type:e.handler,params:this.sanitizeForDevTools(e.params),resolvedParams:u,startTime:l,endTime:performance.now(),duration:performance.now()-l,status:"error",error:{name:g.name,message:g.message,stack:g.stack}}),g}finally{if(e.handler==="apiCall"&&a.setState&&d){const f=a.state?.loadingActions||{},{[d]:g,...m}=f;a.setState({loadingActions:m})}}}async handleNavigate(e,a,r){let i=e;if(a.query||a.mergeQuery===!0)if(a.mergeQuery===!0)i=this.buildMergedQueryPath(e,a.query??{});else{const u=new URLSearchParams;for(const[f,g]of Object.entries(a.query))if(g!=null&&g!=="")if(Array.isArray(g)){const m=f.endsWith("[]")?f:`${f}[]`;for(const b of g)b!=null&&b!==""&&u.append(m,String(b))}else u.set(f,String(g));const d=u.toString();d&&(i=`${e}?${d}`)}if(H.log("handleNavigate:",{target:e,params:a,finalPath:i,replace:a.replace,windowLocationSearch:window.location.search}),a.replace===!0){const u=window.G7Core;if(u?.updateQueryParams){const d=typeof a.transition_overlay_target=="string"?a.transition_overlay_target:void 0;await u.updateQueryParams(i,d?{transitionOverlayTarget:d}:void 0),H.log("handleNavigate: Used updateQueryParams for replace mode",d?{transitionOverlayTarget:d}:void 0),this.applyScrollOption(a.scroll,a.scrollBehavior,"top");return}H.warn("handleNavigate: G7Core.updateQueryParams not available, falling back to React Router")}const l=this.resolveNavigateFallbackAction(i,a);if(l){H.warn(`handleNavigate: No route matched, falling back to "${l.handler}"`),await this.dispatchAction({type:"click",handler:l.handler,params:l.params},r),this.applyScrollOption(a.scroll,a.scrollBehavior,"top");return}if(!r.navigate)throw new It("Navigate function is not provided in context");r.navigate(i,{replace:a.replace===!0}),this.applyScrollOption(a.scroll,a.scrollBehavior,"top")}resolveNavigateFallbackAction(e,a){const r=a.fallback;if(r===!1||a.replace===!0)return null;const l=window.__templateApp?.getRouter?.();if(!l||typeof l.match!="function"||typeof l.getRoutes=="function"&&l.getRoutes().length===0)return null;const u=e.split("?")[0];return l.match(u)?null:this.resolveNavigateFallback(r,e,a)}resolveNavigateFallback(e,a,r){return e==null?{handler:"openWindow",params:{path:a,target:"_self"}}:typeof e=="string"?{handler:e,params:{path:a}}:typeof e=="object"&&typeof e.handler=="string"?{handler:e.handler,params:{path:a,...e.params||{}}}:(H.warn("resolveNavigateFallback: unrecognized fallback option, using openWindow",e),{handler:"openWindow",params:{path:a,target:"_blank"}})}applyScrollOption(e,a,r){const i=e===void 0?r:e;if(i==="preserve")return;const l=a==="smooth"?"smooth":"instant",u=b=>{if(typeof b!="object"||b===null)return!1;const v=b;return"container"in v||"to"in v||"block"in v||"offset"in v},d=(b,v,S=0)=>{b===window?window.scrollTo({top:v,left:S,behavior:l}):b.scrollTo({top:v,left:S,behavior:l})},f=(b,v,S,E)=>{if(v===window){b.scrollIntoView({behavior:l,block:S}),E&&window.scrollBy({top:-E,left:0,behavior:l});return}const A=v,T=b.getBoundingClientRect(),L=A.getBoundingClientRect(),M=A.scrollTop+(T.top-L.top);let R;S==="center"?R=M-(A.clientHeight-b.clientHeight)/2:S==="end"?R=M-(A.clientHeight-b.clientHeight):R=M,R-=E,A.scrollTo({top:Math.max(0,R),left:0,behavior:l})},g=()=>{window.scrollTo({top:0,left:0,behavior:l});const b=document.getElementById("app")??document.body;if(!b)return;b.querySelectorAll("*").forEach(S=>{if(S.scrollTop===0&&S.scrollLeft===0)return;const E=window.getComputedStyle(S),A=E.overflowY,T=E.overflowX;(A==="auto"||A==="scroll"||T==="auto"||T==="scroll")&&S.scrollTo({top:0,left:0,behavior:l})})},m=()=>{try{if(u(i)){const b=i,v=b.block??"start",S=typeof b.offset=="number"?b.offset:0;let E=window;if(typeof b.container=="string"&&b.container.length>0){const T=document.querySelector(b.container);if(!T){H.warn(`applyScrollOption: container not found: ${b.container}`);return}E=T}const A=b.to??"top";if(A==="top"){E===window?g():d(E,0);return}if(typeof A=="number"){d(E,A-S);return}if(typeof A=="object"&&A!==null&&("x"in A||"y"in A)){const{x:T=0,y:L=0}=A;d(E,L-S,T);return}if(typeof A=="string"&&(A.startsWith("#")||A.startsWith("."))){const T=document.querySelector(A);T?f(T,E,v,S):H.warn(`applyScrollOption: target element not found: ${A}`);return}H.warn('applyScrollOption: invalid "to" value in extended form',A);return}if(i==="top"){g();return}if(typeof i=="number"){window.scrollTo({top:i,left:0,behavior:l});return}if(typeof i=="object"&&i!==null&&("x"in i||"y"in i)){const{x:b=0,y:v=0}=i;window.scrollTo({top:v,left:b,behavior:l});return}if(typeof i=="string"&&(i.startsWith("#")||i.startsWith("."))){const b=document.querySelector(i);b&&b.scrollIntoView({behavior:l,block:"start"});return}}catch(b){H.warn("applyScrollOption: failed to apply scroll",b)}};typeof window.requestAnimationFrame=="function"?window.requestAnimationFrame(m):m()}async handleOpenWindow(e,a){let r=e;if(a.query){const l=new URLSearchParams;for(const[d,f]of Object.entries(a.query))f!=null&&f!==""&&l.set(d,String(f));const u=l.toString();u&&(r=`${e}?${u}`)}const i=a.target==="_self"?"_self":"_blank";H.log("handleOpenWindow:",{target:e,params:a,finalPath:r,windowTarget:i}),i==="_self"?window.location.assign(r):window.open(r,"_blank")}async handleNavigateBack(){H.log("handleNavigateBack"),window.history.back()}async handleNavigateForward(){H.log("handleNavigateForward"),window.history.forward()}async handleReplaceUrl(e,a){let r=e;if(a.query||a.mergeQuery===!0)if(a.mergeQuery===!0)r=this.buildMergedQueryPath(e,a.query??{});else{const i=new URLSearchParams;for(const[u,d]of Object.entries(a.query))if(d!=null&&d!=="")if(Array.isArray(d)){const f=u.endsWith("[]")?u:`${u}[]`;for(const g of d)g!=null&&g!==""&&i.append(f,String(g))}else i.set(u,String(d));const l=i.toString();l&&(r=`${e}?${l}`)}H.log("handleReplaceUrl:",{target:e,params:a,finalPath:r}),window.history.replaceState(null,"",r),this.applyScrollOption(a.scroll,a.scrollBehavior,"preserve")}buildMergedQueryPath(e,a){const r=new URLSearchParams(window.location.search);for(const[u,d]of Object.entries(a))if(d==null||d==="")r.delete(u);else if(Array.isArray(d)){const f=u.endsWith("[]")?u:`${u}[]`;r.delete(u),r.delete(f);for(const g of d)g!=null&&g!==""&&r.append(f,String(g))}else r.set(u,String(d));const i=r.toString(),l=e.split("?")[0];return i?`${l}?${i}`:l}async ensureCsrfToken(){try{await fetch("/sanctum/csrf-cookie",{credentials:"include"})}catch(e){throw new It("Failed to fetch CSRF token",void 0,e instanceof Error?e:void 0)}}getCsrfTokenFromCookie(){const r=`; ${document.cookie}`.split("; XSRF-TOKEN=");if(r.length===2){const i=r.pop()?.split(";").shift();return i?decodeURIComponent(i):null}return null}buildQueryString(e){const a=new URLSearchParams;for(const[r,i]of Object.entries(e))if(!(i==null||i===""))if(Array.isArray(i))for(const l of i)l!=null&&l!==""&&a.append(`${r}[]`,String(l));else typeof i=="object"?a.append(r,JSON.stringify(i)):a.append(r,String(i));return a.toString()}async handleEnsureIdentityVerified(e){const a=typeof e.purpose=="string"?e.purpose:"sensitive_action",r=e.target&&typeof e.target=="object"?e.target:void 0;return await St.handle({success:!1,error_code:"identity_verification_required",message:"",verification:{policy_key:e.policy_key??"",purpose:a,provider_id:e.provider_id??null,render_hint:e.render_hint??null,return_request:null}},void 0,r)!==null}handleResolveIdentityChallenge(e){const a=typeof e.result=="string"?e.result:"cancelled";let r;switch(a){case"verified":{const i=typeof e.token=="string"?e.token:"";if(!i){H.warn("resolveIdentityChallenge: result=verified 인데 token 이 비어있습니다. failed 로 강등합니다."),r={status:"failed",failureCode:"MISSING_TOKEN"};break}r={status:"verified",token:i,providerData:e.providerData&&typeof e.providerData=="object"?e.providerData:void 0};break}case"pending":{const i=typeof e.pollUrl=="string"?e.pollUrl:"",l=typeof e.expiresAt=="string"?e.expiresAt:"";if(!i||!l){H.warn("resolveIdentityChallenge: result=pending 인데 pollUrl/expiresAt 누락 — failed 로 강등합니다."),r={status:"failed",failureCode:"MALFORMED_PENDING"};break}r={status:"pending",pollUrl:i,pollIntervalMs:typeof e.pollIntervalMs=="number"?e.pollIntervalMs:void 0,expiresAt:l};break}case"failed":r={status:"failed",failureCode:typeof e.failureCode=="string"?e.failureCode:"UNKNOWN",reason:typeof e.reason=="string"?e.reason:void 0};break;default:r={status:"cancelled"};break}return St.resolveDeferred(r),!0}async handleApiCall(e,a,r,i="none",l){const{method:u="GET",body:d,headers:f,contentType:g}=a;u!=="GET"&&u!=="HEAD"&&await this.ensureCsrfToken();const m=this.getCsrfTokenFromCookie();let b={};if(i==="required"||i==="optional"){const X=$a().getToken();X&&(b={Authorization:`Bearer ${X}`})}let v=e;const S=a.query||(u==="GET"?d:null);if(S&&typeof S=="object"){const P=this.buildQueryString(S);if(P){const X=e.includes("?")?"&":"?";v=`${e}${X}${P}`}}const E=window.G7Core?.state?.getGlobal?.()||r.state?._global||{},A=window.G7Core?.state?.getLocal?.()||r.state?._local||{},T={_global:E,_local:A},L=this.getMatchingGlobalHeaders(e,T),M={};if(typeof window<"u"){const P=localStorage.getItem("g7_locale");P&&(M["Accept-Language"]=P)}const R=g==="multipart/form-data",D={method:u,headers:{...R?{}:{"Content-Type":"application/json"},Accept:"application/json",...M,...m&&{"X-XSRF-TOKEN":m},...b,...L,...f},credentials:"include"};if(d&&u!=="GET")if(R){const P=new FormData;for(const[X,ge]of Object.entries(d))ge instanceof File||ge instanceof Blob?P.append(X,ge):ge!=null&&P.append(X,typeof ge=="object"?JSON.stringify(ge):String(ge));D.body=P}else D.body=JSON.stringify(d);const U=Un();let j=null;U?.isEnabled()&&(j=U.trackRequest(v,u));try{let P=await fetch(v,D),X;try{X=await P.json()}catch{X=null}if(St.isIdentityRequired(P.status,X)){const ge=await St.handle(X,{body:D.body,headers:D.headers,credentials:D.credentials},l);if(ge){P=ge;try{X=await P.json()}catch{X=null}}}if(j&&U?.isEnabled()&&(U.completeRequest(j,P.status,X),j=null),!P.ok){const ge=X||{},Ee=new Error(ge.message||`API call failed: ${P.statusText}`);throw Ee.response=ge,Ee.status=P.status,Ee.statusText=P.statusText,new It(ge.message||`API call failed: ${P.statusText}`,void 0,Ee)}return X}catch(P){throw j&&U?.isEnabled()&&U.failRequest(j,P instanceof Error?P.message:String(P)),P}}async handleLogin(e,a,r){const{body:i}=a;if(!i||!i.email||!i.password)throw new It("Login requires email and password in body params");const l=e==="user"?"user":"admin",u=l==="admin"?"/api/auth/admin/login":"/api/auth/login",d=window.G7Core?.state?.getGlobal?.()||r.state?._global||{},f=window.G7Core?.state?.getLocal?.()||r.state?._local||{},g={_global:d,_local:f},m=this.getMatchingGlobalHeaders(u,g),b=ha.getInstance();try{const v=Object.keys(m).length>0?{headers:m}:void 0;return{user:await b.login(l,{email:i.email,password:i.password},v)}}catch(v){const S=v.message||"Login failed",E=new Error(S);throw E.response=v.response?.data||{},E.status=v.status||v.response?.status||500,new It(S,void 0,E)}}async handleLogout(e,a){await ha.getInstance().logout()}async handleSetState(e,a){H.log("[handleSetState] START, params:",e);const{target:r="component",scope:i,merge:l,__render:u,...d}=e,f=Un(),g=window.G7Core;if(typeof r=="string"&&(r.startsWith("$parent.")||r.startsWith("$root.")))return this.handleParentScopeSetState(r,d,l,a);const m=a.state&&Object.keys(a.state).length>0?a.state:g?.state?.get()||{},b=r==="global"?"_global":r.startsWith("_local.")?r:"_local",v=b==="_global"?m._global:b.startsWith("_local.")?this.getNestedProperty(m._local||{},b.slice(7)):m._local,S=f?.isEnabled()?f.startStateChange(b,v,d,{actionId:a.actionId,handlerType:"setState",source:`target=${r}`}):void 0,E=l==="replace"?"replace":l==="shallow"?"shallow":"deep",A=E!=="deep"?{...d,__mergeMode:E,...S?{__setStateId:S}:{}}:{...d,...S?{__setStateId:S}:{}};if(r==="global"){if(!this.globalStateUpdater){H.warn("Global state updater is not set"),S&&f&&f.completeStateChange(S);return}const T=g?.state?.get()||{},{__setStateId:L,__mergeMode:M,...R}=A,D=E==="deep"?this.deepMergeWithState(R,T):R,U={...D,...S?{__setStateId:S}:{},...E!=="deep"?{__mergeMode:E}:{}};return H.log("setState global:",U),this.globalStateUpdater(U,{render:u}),S&&f&&setTimeout(()=>f.completeStateChange(S),0),{__target:"global",...E!=="deep"?{__mergeMode:E}:{},...D}}else if(r==="isolated"){const T=a.isolatedContext;if(T){const{__mergeMode:L,__setStateId:M,...R}=A;return T.mergeState(R,E),H.log("[handleSetState] isolated state updated:",R,"mergeMode:",E),S&&f&&setTimeout(()=>f.completeStateChange(S),0),{__target:"isolated",...R}}else if(H.warn('[handleSetState] isolated target used but no IsolatedStateContext found. Make sure the component has "isolatedState" attribute. Falling back to local state.'),a.setState){const M=window.__g7PendingLocalState||a.state||{},R=E==="deep"?this.deepMergeWithState(A,M):A;return a.setState(R),S&&f&&setTimeout(()=>f.completeStateChange(S),0),R}else throw S&&f&&f.completeStateChange(S),new It("isolated target used but no IsolatedStateContext found and no setState function in context")}else if(r==="local"||r==="component"||r==="_local"){if(i==="parent"||i==="root"){const L=window.__g7LayoutContextStack||[];if(L.length>0){const M=i==="parent"?L[L.length-1]:L[0];if(M?.setState){const{__mergeMode:R,__setStateId:D,...U}=A,j=E==="deep"?this.deepMergeWithState(U,M.state||{}):U;return H.log(`[handleSetState] scope=${i}: 타겟 컨텍스트에 상태 업데이트`,j),M.setState(j),S&&f&&setTimeout(()=>f.completeStateChange(S),0),j}}H.warn(`[handleSetState] scope=${i}: 레이아웃 컨텍스트 스택이 비어있습니다. current로 폴백합니다.`)}const T=a.setState&&!a._isDispatchFallbackContext;if(H.log("[handleSetState] isRealComponentContext:",T,"context.setState:",!!a.setState,"_isDispatchFallbackContext:",a._isDispatchFallbackContext),T){H.log("[handleSetState] Using COMPONENT setState path"),H.log("[handleSetState] resolvedPayload:",A),H.log("[handleSetState] context.state:",a.state),H.log("[handleSetState] mergeMode:",E);const M=window.__g7PendingLocalState||a.state||{},R=E==="deep"?this.deepMergeWithState(A,{}):A;H.log("[handleSetState] convertedPayload (변경 필드만, dot notation 변환):",R),a.setState(R);const D=E==="deep"?this.deepMergeWithState(A,M):E==="shallow"?{...a.state||{},...A}:A,{__mergeMode:U,__setStateId:j,...P}=D;window.__g7PendingLocalState=P,H.log("[handleSetState] __g7PendingLocalState updated:",P),this.globalStateUpdater&&(this.globalStateUpdater({_local:P},{render:!1}),H.log("[handleSetState] _global._local synced (render:false):",P));const{__mergeMode:X,__setStateId:ge,...Ee}=A;if(E==="replace")window.__g7ForcedLocalFields=Ee;else{const Ce=window.__g7ForcedLocalFields||{};window.__g7ForcedLocalFields=this.deepMergeWithState(Ee,Ce)}return H.log("[handleSetState] __g7ForcedLocalFields updated:",Ee),S&&f&&setTimeout(()=>f.completeStateChange(S),0),{__target:"local",...D}}else if(this.globalStateUpdater){H.log("[handleSetState] Using GLOBAL STATE UPDATER path for _local");const M=window.__g7PendingLocalState||m._local||{};H.log("[handleSetState] currentLocal (with pending):",M);const R=E==="deep"?this.deepMergeWithState(A,M):A;return H.log("[handleSetState] finalLocal (merged):",R),this.globalStateUpdater({_local:R},{render:u}),window.__g7PendingLocalState=R,H.log("[handleSetState] __g7PendingLocalState updated for globalStateUpdater path"),S&&f&&setTimeout(()=>f.completeStateChange(S),0),{__target:"local",...R}}else throw S&&f&&f.completeStateChange(S),new It("setState function is not provided in context and globalStateUpdater is not set")}else if(r.startsWith("_local.")){const T=r.slice(7),{__mergeMode:L,__setStateId:M,...R}=A,D=R.value!==void 0?R.value:Object.values(R)[0];if(a.setState){const j=window.__g7PendingLocalState||a.state||{},P=this.createNestedUpdate(T,D,j),X={...j,...P};return a.setState(P),S&&f&&setTimeout(()=>f.completeStateChange(S),0),X}else throw S&&f&&f.completeStateChange(S),new It("setState function is not provided in context")}else{if(!a.setState)throw S&&f&&f.completeStateChange(S),new It("setState function is not provided in context");const L=window.__g7PendingLocalState||a.state||{},M=E==="deep"?this.deepMergeWithState(A,L):A;return a.setState(M),S&&f&&setTimeout(()=>f.completeStateChange(S),0),M}}async handleParentScopeSetState(e,a,r,i){const l=Un(),u=window.G7Core,d=r==="replace"?"replace":r==="shallow"?"shallow":"deep",f=e.startsWith("$parent."),g=f?"$parent.":"$root.",m=e.slice(g.length);let b,v;if(m==="_local"||m==="_global")b=m,v=void 0;else if(m.startsWith("_local."))b="_local",v=m.slice(7);else if(m.startsWith("_global."))b="_global",v=m.slice(8);else{H.warn(`[handleParentScopeSetState] 지원하지 않는 타겟 형식: ${e}. _local 또는 _global으로 시작해야 합니다.`);return}const S=window.__g7LayoutContextStack||[];if(S.length===0){H.warn(`[handleParentScopeSetState] 레이아웃 컨텍스트 스택이 비어있습니다. target=${e}`);return}const E=f?S[S.length-1]:S[0];if(!E){H.warn(`[handleParentScopeSetState] 타겟 컨텍스트를 찾을 수 없습니다. target=${e}`);return}const A=b==="_global"?E.state?._global:E.state?._local,T=l?.isEnabled()?l.startStateChange(e,A,a,{actionId:i.actionId,handlerType:"setState",source:`target=${e}`}):void 0,{__mergeMode:L,__setStateId:M,...R}=a;if(b==="_global"){if(!this.globalStateUpdater){H.warn("[handleParentScopeSetState] globalStateUpdater가 설정되지 않았습니다."),T&&l&&l.completeStateChange(T);return}const D=u?.state?.get()||{};if(v){const U=R.value!==void 0?R.value:Object.values(R)[0],j=this.createNestedUpdate(v,U,D),P={...D,...j};H.log(`[handleParentScopeSetState] ${e}: 전역 상태 중첩 경로 업데이트`,P),this.globalStateUpdater(P)}else{const U=d==="deep"?this.deepMergeWithState(R,D):R;H.log(`[handleParentScopeSetState] ${e}: 전역 상태 업데이트 (mergeMode=${d})`,U),this.globalStateUpdater(d!=="deep"?{...U,__mergeMode:d}:U)}return T&&l&&setTimeout(()=>l.completeStateChange(T),0),{__target:e,...R}}else{if(!E.setState){H.warn(`[handleParentScopeSetState] 타겟 컨텍스트에 setState가 없습니다. target=${e}`),T&&l&&l.completeStateChange(T);return}const D=E.state||{};if(v){const U=R.value!==void 0?R.value:Object.values(R)[0],j=this.createNestedUpdate(v,U,D),P={...D,...j};return H.log(`[handleParentScopeSetState] ${e}: 로컬 상태 중첩 경로 업데이트`,j),E.setState(j),E.state=P,E.dataContext&&(E.dataContext._local=P),Dd(),T&&l&&setTimeout(()=>l.completeStateChange(T),0),P}else{const U=d!=="deep"?{...R,__mergeMode:d}:R,j=d==="replace"?R:d==="shallow"?{...D,...R}:this.deepMergeWithState(R,D);return H.log(`[handleParentScopeSetState] ${e}: 로컬 상태 업데이트 (mergeMode=${d})`,j),E.setState(U),E.state=j,E.dataContext&&(E.dataContext._local=j),Dd(),T&&l&&setTimeout(()=>l.completeStateChange(T),0),j}}}deepMergeWithState(e,a){const r=["errors"];let i=e;if("..."in e){const u=e["..."];if(u&&typeof u=="object"&&!Array.isArray(u)){const{"...":d,...f}=e;i={...u,...f}}else{const{"...":d,...f}=e;i=f}}const l={...a};for(const[u,d]of Object.entries(i)){if(r.includes(u)){l[u]=d;continue}if(u.includes(".")&&u!=="..."){const f=this.createNestedUpdate(u,d,l);this.deepMergeInto(l,f,l);continue}if(d!==null&&typeof d=="object"&&!Array.isArray(d)&&Object.getPrototypeOf(d)!==Object.prototype&&Object.getPrototypeOf(d)!==null){l[u]=d;continue}d!==null&&typeof d=="object"&&!Array.isArray(d)&&a[u]!==null&&typeof a[u]=="object"&&!Array.isArray(a[u])?l[u]=this.deepMergeWithState(d,a[u]):l[u]=d}return l}deepMergeInto(e,a,r){for(const[i,l]of Object.entries(a)){if(l===null){e[i]=l;continue}if(e[i]===null){e[i]=l;continue}typeof l=="object"&&!Array.isArray(l)&&e[i]!==void 0&&e[i]!==null&&typeof e[i]=="object"&&!Array.isArray(e[i])?(e[i]===r[i]&&(e[i]={...e[i]}),this.deepMergeInto(e[i],l,r[i]||{})):typeof l=="object"&&!Array.isArray(l)&&e[i]===void 0&&r[i]!==null&&typeof r[i]=="object"&&!Array.isArray(r[i])?e[i]={...r[i],...l}:e[i]=l}}createNestedUpdate(e,a,r){const i=e.split(".");if(i.length===1)return{[i[0]]:a};const l={};let u=l,d=r;for(let f=0;f{this.globalStateUpdater({_local:S})};m.push({state:b,setState:v,dataContext:{_local:b||a.data?._local,_global:l?a.data?._global:a.data?._global||i?.state?.get?.(),_computed:a.data?._computed}}),window.__g7LayoutContextStack=m,H.log(`[handleOpenModal] 레이아웃 컨텍스트 스택에 push, 스택 크기: ${m.length}, state:`,b,l?"(direct)":"(fallback via G7Core)")}else H.warn(`[handleOpenModal] 컨텍스트 스택에 push 실패 - setState: ${!!a.setState}, state: ${a.state!==void 0}, G7Core: ${!!i?.state?.getLocal}`);const f=[...r,e];this.globalStateUpdater({modalStack:f,activeModal:e});const g=Un();if(g?.isEnabled()){const m=r.length>0?r[r.length-1]:void 0;g.trackModalOpen?.({modalId:e,modalName:e,scopeType:"isolated",parentModalId:m,initialState:a.state?{...a.state}:{}})}}async handleCloseModal(e){if(!this.globalStateUpdater){H.warn("Global state updater is not set for closeModal");return}const a=e?.data?._global?.modalStack||[],r=a.length>0?a[a.length-1]:null,i=a.slice(0,-1),l=i.length>0?i[i.length-1]:null,u=window.__g7LayoutContextStack||[];if(u.length>0){const d=u[u.length-1];d&&(d.dataContext=void 0),u.pop(),window.__g7LayoutContextStack=u,H.log(`[handleCloseModal] 레이아웃 컨텍스트 스택에서 pop, 스택 크기: ${u.length}`)}if(r){const d=Un();d?.isEnabled()&&d.trackModalClose?.(r,e?.state)}this.globalStateUpdater({modalStack:i,activeModal:l})}async handleShowAlert(e,a){let r=e;this.translationEngine&&this.translationContext&&e.startsWith("$t:")&&(r=this.translationEngine.resolveTranslations(e,this.translationContext,a.data)),alert(r)}async handleToast(e,a){const{type:r="info",message:i,icon:l,duration:u}=e;if(r==="error"){const f=a.data?.error;if((f?.error_code==="identity_verification_required"||f?.data?.error_code==="identity_verification_required")&&St.consumeDomainNoticeShown()){H.log("[Toast] IDV 도메인 안내 표출됨 — 중복 가드 토스트 1건 skip");return}}let d=i;if(this.translationEngine&&this.translationContext&&i?.startsWith("$t:")&&(d=this.translationEngine.resolveTranslations(i,this.translationContext,a.data)),this.globalStateUpdater){const g={id:`toast_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,type:r,message:d,...l&&{icon:l},...u&&{duration:u}},S=[...window.G7Core?.state?.get()?.toasts||[],g];this.globalStateUpdater({toasts:S})}else H.log(`[Toast ${r}] ${d}`)}async handleSwitch(e,a){const{cases:r}=e;if(!r){H.warn("switch handler requires cases property");return}const i=this.resolveParams(e.params,a.data);let l;if(i?.value!==void 0?(l=i.value,H.log("switch handler: using params.value as case key:",l)):(l=a.data?.$args?.[0],H.log("switch handler: using $args[0] as case key:",l)),l==null){if(r.default)return H.log("switch handler: case key is undefined, using default case"),await this.executeAction(r.default,a);H.warn("switch handler: case key is not defined and no default case");return}const u=String(l);let d=r[u];if(!d&&r.default&&(H.log(`switch handler: no case found for key "${u}", using default case`),d=r.default),!d){H.warn(`switch handler: no case found for key "${u}" and no default case`);return}return await this.executeAction(d,a)}async handleConditions(e,a){const{conditions:r}=e;if(!r||!Array.isArray(r)){H.warn("conditions handler requires conditions array");return}const i=a.data||{},l=op(r,i,this.bindingEngine);if(!l.matched){H.log("conditions handler: no matching branch found");return}const u=r[l.branchIndex];if(H.log(`conditions handler: matched branch ${l.branchIndex}`),!u.then){H.warn('conditions handler: matched branch has no "then" action');return}return Array.isArray(u.then)?await this.handleSequence({...e,actions:u.then},a):await this.executeAction(u.then,a)}handleStartInterval(e,a){const r=typeof e.id=="string"?e.id:"",i=Number(e.intervalMs??1e3),l=Array.isArray(e.actions)?e.actions:[];if(r===""||!l.length||i<=0)return H.warn("startInterval requires non-empty id, positive intervalMs, and actions array"),{success:!1};const u=this.intervals.get(r);u&&(clearInterval(u),this.intervals.delete(r));const d=setInterval(()=>{for(const f of l)this.executeAction(f,a).catch(g=>{H.error(`[startInterval:${r}] tick action failed`,g)})},i);return this.intervals.set(r,d),{success:!0,id:r}}handleStopInterval(e){const a=typeof e.id=="string"?e.id:"";if(a==="")return H.warn("stopInterval requires id parameter"),{success:!1};const r=this.intervals.get(a);return r&&(clearInterval(r),this.intervals.delete(a)),{success:!0,id:a}}stopAllIntervals(){for(const e of this.intervals.values())clearInterval(e);this.intervals.clear()}async handleSequence(e,a){const r=e.actions||e.params?.actions;if(!r||!Array.isArray(r)||r.length===0)return H.warn("sequence handler requires non-empty actions array"),[];const i=Un(),l=i?.isEnabled()&&i.startSequenceExecution?.({eventType:e.type})||"";window.__g7SequenceLocalSync=void 0;const u=[];let d,f=a.state?{...a.state}:{},g=a.isolatedContext?.state?{...a.isolatedContext.state}:{},m=a.data?._computed||{};const b=window.G7Core,v=()=>({_global:b?.state?.get()||{},_local:{...f},_isolated:Object.keys(g).length>0?{...g}:void 0});for(let S=0;S0){const R={},D={...a.data,_local:f,_computed:R,$computed:R,_isolated:g};for(const[U,j]of Object.entries(M))if(typeof j=="string"){const P=j.trim();if(P.startsWith("{{")&&P.endsWith("}}"))try{const X=P.slice(2,-2).trim();R[U]=this.bindingEngine.evaluateExpression(X,D,{skipCache:!0})}catch{R[U]=m[U]}}m=R,H.log("[handleSequence] _computed recalculated after setState:",m)}}if(E.handler!=="setState"){const M=window.__g7SequenceLocalSync;if(M&&M!==f){f=M,window.__g7SequenceLocalSync=void 0,H.log("[handleSequence] currentState synchronized from __g7SequenceLocalSync after custom handler:",E.handler);const R=a.data?._computedDefinitions;if(R&&Object.keys(R).length>0){const D={},U={...a.data,_local:f,_computed:D,$computed:D,_isolated:g};for(const[j,P]of Object.entries(R))if(typeof P=="string"){const X=P.trim();if(X.startsWith("{{")&&X.endsWith("}}"))try{const ge=X.slice(2,-2).trim();D[j]=this.bindingEngine.evaluateExpression(ge,U,{skipCache:!0})}catch{D[j]=m[j]}}m=D,H.log("[handleSequence] _computed recalculated after custom handler:",m)}}}l&&i?.isEnabled()&&i.captureSequenceActionAfter?.(l,S,v(),Date.now()-A,L.data)}catch(L){throw l&&i?.isEnabled()&&(i.captureSequenceActionAfter?.(l,S,v(),Date.now()-A,void 0,L),i.endSequenceExecution?.(l,L)),H.error(`sequence handler: action[${S}] failed:`,L),L}}return window.__g7SequenceLocalSync=void 0,l&&i?.isEnabled()&&i.endSequenceExecution?.(l),u}async handleParallel(e,a){const r=e.actions||e.params?.actions;if(!r||!Array.isArray(r)||r.length===0)return H.warn("parallel handler requires non-empty actions array"),[];H.log(`parallel handler: executing ${r.length} actions in parallel`);const i=a.isolatedContext?{...a.isolatedContext,state:{...a.isolatedContext.state}}:null,l=r.map((f,g)=>{const m={...a,isolatedContext:i};return this.executeAction(f,m).catch(b=>{throw H.error(`parallel handler: action[${g}] failed:`,b),b})}),u=await Promise.allSettled(l),d=u.filter(f=>f.status==="rejected").length;return d>0&&H.warn(`parallel handler: ${d}/${r.length} actions failed`),u}async handleLoadScript(e,a,r){const{src:i,id:l,async:u=!0,defer:d=!1}=e;if(!i)throw new It('loadScript handler requires "src" parameter',a);const f=l||`script_${i.replace(/[^a-zA-Z0-9]/g,"_")}`;return us.loadedScripts.has(f)?(H.log(`loadScript: script already loaded, skipping: ${f}`),a.onLoad&&await this.executeAction(a.onLoad,r),!0):document.getElementById(f)?(H.log(`loadScript: script element already exists: ${f}`),us.loadedScripts.add(f),a.onLoad&&await this.executeAction(a.onLoad,r),!0):(H.log(`loadScript: loading script: ${i}`),new Promise((m,b)=>{const v=document.createElement("script");v.id=f,v.src=i,v.async=u,v.defer=d,v.onload=async()=>{if(H.log(`loadScript: script loaded successfully: ${f}`),us.loadedScripts.add(f),a.onLoad)try{await this.executeAction(a.onLoad,r)}catch(S){H.error("loadScript: onLoad action failed:",S)}m(!0)},v.onerror=S=>{H.error(`loadScript: failed to load script: ${i}`,S),b(new It(`Failed to load script: ${i}`,a))},document.head.appendChild(v)}))}async handleCallExternal(e,a,r){const i=e.constructor,l=e.args||{},u=e.method,d=e.methodArgs||[],f=e.callbackEvent,g=e.embedTarget,m=e.callbackSetState,b=e.callbackAction;if(!i)throw new It('callExternal handler requires "constructor" parameter',a);const v=this.getNestedProperty(window,i);if(!v||typeof v!="function")throw new It(`Constructor not found or not a function: ${i}. Make sure the script is loaded first using loadScript handler.`,a);H.log(`callExternal: calling constructor ${i}`);const S={...l};for(const[A,T]of Object.entries(l))T===!0&&(S[A]=L=>{if(H.log(`callExternal: callback triggered for ${A}`,L),f&&typeof window<"u"&&window.G7Core?.componentEvent&&window.G7Core.componentEvent.emit(f,L),m&&r.setState){const M=U=>{const j={};for(const[P,X]of Object.entries(U))typeof X=="string"?j[P]=this.getNestedProperty(L,X):typeof X=="object"&&X!==null&&(j[P]=M(X));return j},R=M(m);H.log("callExternal: callbackSetState mapping result",R);const D=this.deepMergeWithState(R,r.state||{});H.log("callExternal: merged with existing state",D),r.setState(D)}else f&&r.setState&&r.setState({[`${f.replace(/:/g,"_")}_result`]:L});if(b){const M={...r,data:{...r.data,$event:L}},R=Array.isArray(b)?b:[b];for(const D of R)try{this.executeAction(D,M)}catch(U){H.error("callExternal: callbackAction failed:",U)}}});const E=new v(S);if(u&&typeof E[u]=="function"){if(H.log(`callExternal: calling method ${u}`),u==="embed"&&g){const A=document.querySelector(g);if(A)return E[u](A,...d);throw new It(`Embed target element not found: ${g}`,a)}return E[u](...d)}return E}async handleCallExternalEmbed(e,a,r){const i=e.constructor,l=e.args||{},u=e.callbackSetState,d=e.callbackEvent,f=e.layerClassName,g=e.callbackAction;if(!i)throw new It('callExternalEmbed handler requires "constructor" parameter',a);const m=this.getNestedProperty(window,i);if(!m||typeof m!="function")throw new It(`Constructor not found or not a function: ${i}. Make sure the script is loaded first.`,a);H.log(`callExternalEmbed: creating layer for ${i}`);const{layer:b,closeLayer:v}=this.createEmbedLayer(f),S={...l};for(const[A,T]of Object.entries(l))T===!0&&(S[A]=L=>{if(H.log(`callExternalEmbed: callback triggered for ${A}`,L),v(),d&&typeof window<"u"&&window.G7Core?.componentEvent&&window.G7Core.componentEvent.emit(d,L),u&&r.setState){const M=U=>{const j={};for(const[P,X]of Object.entries(U))typeof X=="string"?j[P]=this.getNestedProperty(L,X):typeof X=="object"&&X!==null&&(j[P]=M(X));return j},R=M(u);H.log("callExternalEmbed: callbackSetState mapping result",R);const D=this.deepMergeWithState(R,r.state||{});H.log("callExternalEmbed: merged with existing state",D),r.setState(D)}if(g){const M={...r,data:{...r.data,$event:L}},R=Array.isArray(g)?g:[g];for(const D of R)try{this.executeAction(D,M)}catch(U){H.error("callExternalEmbed: callbackAction failed:",U)}}});const E=new m(S);if(typeof E.embed=="function")E.embed(b),H.log("callExternalEmbed: embedded in layer");else throw v(),new It(`Constructor ${i} does not have embed method`,a);return E}isImeComposing(e){return e?.isComposing===!0||e?.keyCode===229}createEmbedLayer(e){const a=document.createElement("div");a.id="g7-embed-overlay",a.style.cssText=` +`+l)}}catch{}}throw r}}_request(e,n){typeof e=="string"?(n=n||{},n.url=e):n=e||{},n=hi(this.defaults,n);const{transitional:r,paramsSerializer:i,headers:l}=n;r!==void 0&&Kl.assertOptions(r,{silentJSONParsing:En.transitional(En.boolean),forcedJSONParsing:En.transitional(En.boolean),clarifyTimeoutError:En.transitional(En.boolean),legacyInterceptorReqResOrdering:En.transitional(En.boolean),advertiseZstdAcceptEncoding:En.transitional(En.boolean),validateStatusUndefinedResolves:En.transitional(En.boolean)},!1),i!=null&&(V.isFunction(i)?n.paramsSerializer={serialize:i}:Kl.assertOptions(i,{encode:En.function,serialize:En.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),Kl.assertOptions(n,{baseUrl:En.spelling("baseURL"),withXsrfToken:En.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let u=l&&V.merge(l.common,l[n.method]);l&&V.forEach(["delete","get","head","post","put","patch","query","common"],_=>{delete l[_]}),n.headers=Cn.concat(u,l);const d=[];let f=!0;this.interceptors.request.forEach(function(x){if(typeof x.runWhen=="function"&&x.runWhen(n)===!1)return;f=f&&x.synchronous;const k=n.transitional||Sd;k&&k.legacyInterceptorReqResOrdering?d.unshift(x.fulfilled,x.rejected):d.push(x.fulfilled,x.rejected)});const g=[];this.interceptors.response.forEach(function(x){g.push(x.fulfilled,x.rejected)});let m,b=0,v;if(!f){const _=[Zp.bind(this),void 0];for(_.unshift(...d),_.push(...g),v=_.length,m=Promise.resolve(n);b{if(!r._listeners)return;let l=r._listeners.length;for(;l-- >0;)r._listeners[l](i);r._listeners=null}),this.promise.then=i=>{let l;const u=new Promise(d=>{r.subscribe(d),l=d}).then(i);return u.cancel=function(){r.unsubscribe(l)},u},e(function(l,u,d){r.reason||(r.reason=new lo(l,u,d),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const n=this._listeners.indexOf(e);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const e=new AbortController,n=r=>{e.abort(r)};return this.subscribe(n),e.signal.unsubscribe=()=>this.unsubscribe(n),e.signal}static source(){let e;return{token:new HS(function(i){e=i}),cancel:e}}};function iC(o){return function(n){return o.apply(null,n)}}function sC(o){return V.isObject(o)&&o.isAxiosError===!0}const Td={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(Td).forEach(([o,e])=>{Td[e]=o});function tm(o){const e=new gi(o),n=mp(gi.prototype.request,e);return V.extend(n,gi.prototype,e,{allOwnKeys:!0}),V.extend(n,e,null,{allOwnKeys:!0}),n.create=function(i){return tm(hi(o,i))},n}const Ft=tm(oo);Ft.Axios=gi,Ft.CanceledError=lo,Ft.CancelToken=rC,Ft.isCancel=zp,Ft.VERSION=_d,Ft.toFormData=Pl,Ft.AxiosError=Ce,Ft.Cancel=Ft.CanceledError,Ft.all=function(e){return Promise.all(e)},Ft.spread=iC,Ft.isAxiosError=sC,Ft.mergeConfig=hi,Ft.AxiosHeaders=Cn,Ft.formToJSON=o=>Hp(V.isHTMLForm(o)?new FormData(o):o),Ft.getAdapter=Qp.getAdapter,Ft.HttpStatusCode=Td,Ft.default=Ft;const{Axios:CT,AxiosError:ET,CanceledError:_T,isCancel:AT,CancelToken:xT,VERSION:TT,all:RT,Cancel:kT,isAxiosError:DT,spread:OT,toFormData:LT,AxiosHeaders:MT,HttpStatusCode:$T,formToJSON:NT,getAdapter:IT,mergeConfig:HT,create:zT}=Ft,Rd="g7.identity.redirectStash",Wl=dt("IdentityGuardInterceptor");class wt{static setLauncher(e){this.launcher=e}static hasLauncher(){return this.launcher!==null}static markDomainNoticeShown(){this.domainNoticeShown=!0}static consumeDomainNoticeShown(){const e=this.domainNoticeShown;return this.domainNoticeShown=!1,e}static resolveDeferred(e){const n=this.deferredResolver;if(!n){Wl.warn("IdentityGuardInterceptor.resolveDeferred 호출됐지만 대기 중인 launcher 가 없습니다. 모달이 launcher 외부에서 열렸는지 확인하세요.");return}this.deferredResolver=null,n(e)}static createDeferred(){if(this.deferredResolver){const e=this.deferredResolver;this.deferredResolver=null,e({status:"cancelled"})}return new Promise(e=>{this.deferredResolver=e})}static isIdentityRequired(e,n){return e===428&&typeof n=="object"&&n!==null&&n.error_code==="identity_verification_required"}static async handle(e,n,r){this.domainNoticeShown=!1;const i=this.launcher??lC,u=!!(r&&(r.email||r.phone))?{...e.verification,target:r}:e.verification,d=await i(u);if(d.status!=="verified")return null;const f=u.return_request;if(!f)return null;const g=oC(f.url,d.token);return fetch(g,{method:f.method,headers:n?.headers??{Accept:"application/json","Content-Type":"application/json"},body:n?.body,credentials:n?.credentials??"same-origin"})}static redirectExternally(e){const n=e.redirect_url;if(!n)return Wl.error("redirectExternally 호출 시 verification.redirect_url 이 없습니다. payload:",e),Promise.resolve({status:"failed",failureCode:"MISSING_REDIRECT_URL",reason:"verification.redirect_url is required for external_redirect flow"});if(typeof window<"u"){const r={return_url:window.location.href,payload:e,stashed_at:Date.now()};try{window.sessionStorage?.setItem(Rd,JSON.stringify(r))}catch(i){Wl.warn("sessionStorage 접근 실패 — stash 없이 redirect 합니다.",i)}window.location.href=n}return new Promise(()=>{})}static reset(){if(this.deferredResolver){const e=this.deferredResolver;this.deferredResolver=null;try{e({status:"cancelled"})}catch{}}this.launcher=null,this.domainNoticeShown=!1}}$(wt,"launcher",null),$(wt,"deferredResolver",null),$(wt,"domainNoticeShown",!1);function oC(o,e){if(!e)return o;try{const n=typeof window<"u"?window.location.origin:"http://localhost",r=new URL(o,n);return r.searchParams.set("verification_token",e),/^https?:\/\//i.test(o)?r.toString():`${r.pathname}${r.search}${r.hash}`}catch{const n=o.includes("?")?"&":"?";return`${o}${n}verification_token=${encodeURIComponent(e)}`}}const lC=async o=>{if(typeof window>"u")return{status:"cancelled"};if(o.render_hint==="external_redirect"||o.redirect_url)return wt.redirectExternally(o);const e=window.G7Core;if(!e?.dispatch)return console.error("[IdentityGuardInterceptor] defaultLauncher: G7Core 가 초기화되지 않아 본인인증 흐름을 시작할 수 없습니다."),{status:"failed",failureCode:"G7_NOT_READY"};try{await e.dispatch({handler:"toast",params:{message:"본인 확인이 필요합니다.",variant:"warning"}})}catch{}const n=window.location.href,r={return_url:n,payload:o,stashed_at:Date.now()};try{window.sessionStorage?.setItem(Rd,JSON.stringify(r))}catch{}const i=`/identity/challenge?return=${encodeURIComponent(n)}`;try{await e.dispatch({handler:"navigate",params:{path:i}})}catch(l){Wl.warn("navigate 실패 — window.location 으로 폴백",l),window.location.href=i}return new Promise(()=>{})},cC=dt("ApiClient");function kd(){return typeof window<"u"&&window.__G7_DEVTOOLS__?window.__G7_DEVTOOLS__:null}class uC{constructor(e={}){$(this,"client");$(this,"config");$(this,"TOKEN_KEY","auth_token");this.config={baseURL:e.baseURL||"/api",timeout:e.timeout||3e4,onTokenExpired:e.onTokenExpired,onUnauthorized:e.onUnauthorized,onError:e.onError},this.client=Ft.create({baseURL:this.config.baseURL,timeout:this.config.timeout,headers:{"Content-Type":"application/json",Accept:"application/json"},paramsSerializer:{serialize:n=>{const r=[];for(const[i,l]of Object.entries(n))if(l!=null)if(Array.isArray(l)){const u=i.endsWith("[]")?i:`${i}[]`;for(const d of l)r.push(`${encodeURIComponent(u)}=${encodeURIComponent(String(d))}`)}else r.push(`${encodeURIComponent(i)}=${encodeURIComponent(String(l))}`);return r.join("&")}}}),this.setupInterceptors()}setToken(e){typeof window<"u"&&localStorage.setItem(this.TOKEN_KEY,e)}getToken(){return typeof window<"u"?localStorage.getItem(this.TOKEN_KEY):null}removeToken(){typeof window<"u"&&localStorage.removeItem(this.TOKEN_KEY)}setupInterceptors(){this.client.interceptors.request.use(e=>{e.url?.startsWith("/api")&&e.baseURL==="/api"&&(e.baseURL="");const n=this.getToken();if(n&&e.headers&&(e.headers.Authorization=`Bearer ${n}`),typeof window<"u"&&e.headers){const i=localStorage.getItem("g7_locale");i&&(e.headers["Accept-Language"]=i)}const r=kd();if(r?.isEnabled()){const i=this.buildFullUrl(e),l=(e.method||"GET").toUpperCase(),u=r.trackRequest(i,l,{requestBody:e.data});e._devToolsRequestId=u}return e},e=>Promise.reject(e)),this.client.interceptors.response.use(e=>{const n=e.config,r=n._devToolsRequestId;if(r){const i=kd();i?.isEnabled()&&i.completeRequest(r,e.status,e.data),n._devToolsRequestId=null}return e},async e=>{const n=e.config,r=n?.url||"",l=["/auth/","/layouts/"].some(u=>r.includes(u));if(e.response?.status===401&&!n?._retry&&!l){if(n._retry=!0,await ga.getInstance().refreshToken()){const f=this.getToken();return f&&(n.headers.Authorization=`Bearer ${f}`),n._devToolsRequestId=null,this.client(n)}return this.completeDevToolsRequest(n,e),this.removeToken(),this.config.onUnauthorized&&this.config.onUnauthorized(),Promise.reject(e)}if(e.response?.status===401&&l)return this.completeDevToolsRequest(n,e),Promise.reject(e);if(wt.isIdentityRequired(e.response?.status,e.response?.data)){this.completeDevToolsRequest(n,e);const u={},d=n?.headers??{};for(const[v,S]of Object.entries(d))typeof S=="string"&&(u[v]=S);let f;n?.data!==void 0&&n?.data!==null&&(f=typeof n.data=="string"?n.data:JSON.stringify(n.data),u["Content-Type"]=u["Content-Type"]??"application/json");const g=n?.identity_target,m=await wt.handle(e.response.data,{headers:u,body:f,credentials:"same-origin"},g);if(!m)return Promise.reject(e);let b=null;try{b=await m.json()}catch{b=null}return m.ok?{...e.response,status:m.status,data:b}:Promise.reject(Object.assign(new Error("replay failed"),{response:{status:m.status,data:b}}))}return e.response?.status===403?(this.completeDevToolsRequest(n,e),this.callOnError(e),Promise.reject(e)):(this.completeDevToolsRequest(n,e),e.response&&this.callOnError(e),Promise.reject(e))})}async get(e,n){return(await this.client.get(e,n)).data}async post(e,n,r){return(await this.client.post(e,n,r)).data}async put(e,n,r){return(await this.client.put(e,n,r)).data}async patch(e,n,r){return(await this.client.patch(e,n,r)).data}async delete(e,n){return(await this.client.delete(e,n)).data}getInstance(){return this.client}setOnUnauthorized(e){this.config.onUnauthorized=e}setOnError(e){this.config.onError=e}completeDevToolsRequest(e,n){if(!e?._devToolsRequestId)return;const r=kd();if(!r?.isEnabled())return;const i=e._devToolsRequestId;e._devToolsRequestId=null,n.response?r.completeRequest(i,n.response.status,n.response.data):n.request?r.failRequest(i,n.message||"Network error"):r.failRequest(i,n.message||"Request error")}buildFullUrl(e){let n=e.url||"";if(e.baseURL&&!n.startsWith("http")&&(n=`${e.baseURL}${n.startsWith("/")?"":"/"}${n}`),e.params&&typeof e.params=="object"){const r=e.params,i=[];for(const[l,u]of Object.entries(r))if(u!=null)if(Array.isArray(u)){const d=l.endsWith("[]")?l:`${l}[]`;for(const f of u)i.push(`${encodeURIComponent(d)}=${encodeURIComponent(String(f))}`)}else i.push(`${encodeURIComponent(l)}=${encodeURIComponent(String(u))}`);i.length>0&&(n+=(n.includes("?")?"&":"?")+i.join("&"))}return n}callOnError(e){if(!this.config.onError)return;const n={status:e.response?.status||0,message:e.response?.data?.message||e.message||"Unknown error",data:e.response?.data,statusText:e.response?.statusText};try{this.config.onError(n)}catch(r){cC.error("Error in onError handler:",r)}}}let Dd=null;function Ia(){return Dd||(Dd=new uC),Dd}const co=dt("AuthManager");function is(o,e,n,r){try{window.G7Core?.devTools?.trackAuthEvent?.(o,e,n,r)}catch{}}const Yl={admin:{type:"admin",loginPath:"/admin/login",defaultPath:"/admin",userEndpoint:"/admin/auth/user",loginEndpoint:"/auth/admin/login",logoutEndpoint:"/admin/auth/logout",refreshEndpoint:"/admin/auth/refresh"},user:{type:"user",loginPath:"/login",defaultPath:"/",userEndpoint:"/auth/user",loginEndpoint:"/auth/login",logoutEndpoint:"/auth/logout",refreshEndpoint:"/auth/refresh"}},Ca=class Ca{constructor(){$(this,"state");$(this,"config");$(this,"isRefreshing",!1);$(this,"refreshPromise",null);$(this,"eventHandlers",new Map);this.state={isAuthenticated:!1,user:null,type:null},this.config=new Map,this.config.set("admin",Yl.admin),this.config.set("user",Yl.user)}static getInstance(){return Ca.instance||(Ca.instance=new Ca),Ca.instance}on(e,n){this.eventHandlers.has(e)||this.eventHandlers.set(e,[]),this.eventHandlers.get(e).push(n)}emit(e,...n){const r=this.eventHandlers.get(e);r&&r.forEach(i=>i(...n))}isAuthenticated(){return this.state.isAuthenticated}getUser(){return this.state.user}getAuthType(){return this.state.type}async checkAuth(e){const n=Ia();if(!n.getToken())return this.clearState(),!1;const i=this.config.get(e);if(!i)return co.error(`Unknown auth type: ${e}`),!1;try{const l=await n.get(i.userEndpoint);return l.success&&l.data?(this.state={isAuthenticated:!0,user:l.data,type:e},this.emit("authStateChange",this.state),!0):(this.clearState(),!1)}catch(l){return l.response?.status===401&&await this.refreshToken()?this.checkAuth(e):(this.clearState(),!1)}}async preloadAuth(e){try{return await this.checkAuth(e)}catch(n){return co.warn(`Preload auth failed for type ${e}:`,n),!1}}async login(e,n,r){const i=Ia();if(!this.config.get(e))throw new Error(`Unknown auth type: ${e}`);const u=e==="admin"?Yl.admin.loginEndpoint:Yl.user.loginEndpoint;try{const d=r?.headers?{headers:r.headers}:void 0,f=await i.post(u,n,d);if(f.success&&f.data){i.setToken(f.data.token);const g=f.data.user.language,m=localStorage.getItem(Ca.LOCALE_STORAGE_KEY),b=g&&g!==m;if(g)try{localStorage.setItem(Ca.LOCALE_STORAGE_KEY,g)}catch(v){co.warn("Failed to save user language to localStorage:",v)}return this.state={isAuthenticated:!0,user:f.data.user,type:e},this.emit("login",this.state),this.emit("authStateChange",this.state),is("login",!0,void 0,{userId:f.data.user.uuid,email:f.data.user.email,type:e}),b&&window.__templateApp&&window.__templateApp.changeLocale(g),f.data.user}throw new Error("Login failed")}catch(d){this.clearState();const f=d.response?.data?.message,g=new Error(f||d.message||"Login failed");throw g.response=d.response,g.status=d.response?.status,is("login",!1,g.message,{type:e,status:d.response?.status}),g}}async logout(){const e=Ia(),n=this.state.type?this.config.get(this.state.type):null;try{n&&await e.post(n.logoutEndpoint)}catch(r){co.warn("Logout API call failed:",r)}finally{e.removeToken();const r={...this.state};if(this.clearState(),this.emit("logout",r),this.emit("authStateChange",this.state),is("logout",!0,void 0,{previousType:r.type}),n&&r.type){const i=window.location.pathname+window.location.search;window.location.href=this.getLoginRedirectUrl(r.type,i)}}}async refreshToken(){if(this.isRefreshing&&this.refreshPromise)return this.refreshPromise;this.isRefreshing=!0,this.refreshPromise=this.doRefreshToken();try{return await this.refreshPromise}finally{this.isRefreshing=!1,this.refreshPromise=null}}async doRefreshToken(){const e=this.state.type;if(!e)return!1;const n=this.config.get(e);if(!n)return!1;const r=Ia();try{const i=await r.post(n.refreshEndpoint);return i.success&&i.data?.token?(r.setToken(i.data.token),this.emit("tokenRefreshed"),is("token-refresh",!0,void 0,{type:e}),!0):(is("token-refresh",!1,"No token in response",{type:e}),!1)}catch(i){return co.error("Token refresh failed:",i),is("token-refresh",!1,i instanceof Error?i.message:"Unknown error",{type:e}),!1}}getLoginRedirectUrl(e,n,r){const i=this.config.get(e);if(!i)return"/login";const l=encodeURIComponent(n);let u=`${i.loginPath}?redirect=${l}`;return r&&(u+=`&reason=${encodeURIComponent(r)}`),u}updateConfig(e,n){if(n.loginPath!==void 0){const i=n.loginPath;if(!i.startsWith("/")||i.startsWith("//"))throw new Error(`AuthManager.updateConfig: loginPath must be a same-origin path starting with '/' (got: ${i})`)}const r=this.config.get(e);r&&this.config.set(e,{...r,...n})}getRedirectUrl(e){const r=this.config.get(e)?.defaultPath||"/",l=new URLSearchParams(window.location.search).get("redirect");if(l)try{const u=decodeURIComponent(l);if(u.startsWith("/"))return u}catch{}return r}getConfig(e){return this.config.get(e)}clearState(){this.state={isAuthenticated:!1,user:null,type:null}}static resetInstance(){Ca.instance=null}};$(Ca,"instance"),$(Ca,"LOCALE_STORAGE_KEY","g7_locale");let ga=Ca;const nm={401:{handler:"navigate",params:{path:"{{auth.loginPath}}"}},403:{handler:"toast",params:{type:"error",message:"{{error.message}}"}},404:{handler:"toast",params:{type:"error",message:"{{error.message}}"}},422:{handler:"toast",params:{type:"error",message:"{{error.message}}"}},default:{handler:"toast",params:{type:"error",message:"{{error.message}}"}}},Qa={findHandler(o,e){if(o){if(o[e])return o[e];if(o[String(e)])return o[String(e)];if(o.default)return o.default}},normalizeOnError(o){return o?Array.isArray(o)?o:[o]:[]},injectErrorCode(o,e,n){if(o.handler!=="showErrorPage"||o.params?.errorCode!==void 0)return o;const r=typeof e=="string"?parseInt(e,10):e,i=isNaN(r)?n:r;return i===void 0?o:{...o,params:{...o.params,errorCode:i}}}},pa=dt("ErrorHandlingResolver"),kr=class kr{constructor(){$(this,"templateErrorHandling",null);$(this,"layoutErrorHandling",null);$(this,"executeAction",null)}static getInstance(){return kr.instance||(kr.instance=new kr),kr.instance}static resetInstance(){kr.instance=null}setTemplateConfig(e){this.templateErrorHandling=e,pa.log("Template config set:",e)}setLayoutConfig(e){this.layoutErrorHandling=e,pa.log("Layout config set:",e)}setActionExecutor(e){this.executeAction=e}resolve(e,n={}){const{errorHandling:r,onError:i}=n;pa.log("Resolving error:",e,{hasActionErrorHandling:!!r,hasActionOnError:!!i,hasLayoutConfig:!!this.layoutErrorHandling,hasTemplateConfig:!!this.templateErrorHandling});let l=Qa.findHandler(r,e);if(l){const u=this.getMatchedKey(r,e);return{handler:Qa.injectErrorCode(l,u,e),level:"action",matchedKey:u}}if(i){const u=Qa.normalizeOnError(i);if(u.length>0)return{handler:u.length===1?u[0]:{handler:"sequence",actions:u},level:"action",matchedKey:"onError"}}if(l=Qa.findHandler(this.layoutErrorHandling||void 0,e),l){const u=this.getMatchedKey(this.layoutErrorHandling,e);return{handler:Qa.injectErrorCode(l,u,e),level:"layout",matchedKey:u}}if(l=Qa.findHandler(this.templateErrorHandling||void 0,e),l){const u=this.getMatchedKey(this.templateErrorHandling,e);return{handler:Qa.injectErrorCode(l,u,e),level:"template",matchedKey:u}}if(l=Qa.findHandler(nm,e),l){const u=this.getMatchedKey(nm,e);return{handler:Qa.injectErrorCode(l,u,e),level:"system",matchedKey:u}}return{handler:null,level:null,matchedKey:null}}async execute(e,n){if(!this.executeAction){pa.error("Action executor is not set");return}pa.log("Executing handler:",e.handler,{errorContext:n});try{return await this.executeAction(e,{error:n})}catch(r){throw pa.error("Failed to execute handler:",r),r}}async resolveAndExecute(e,n,r={}){const i=this.resolve(e,r);if(pa.log("Resolve result:",{errorCode:e,handler:i.handler?.handler,level:i.level,matchedKey:i.matchedKey}),!i.handler)return pa.warn("No handler found for error:",e),{handled:!1};try{return{handled:!0,result:await this.execute(i.handler,n)}}catch(l){return pa.error("Handler execution failed:",l),{handled:!1}}}getMatchedKey(e,n){return e[n]?n:e[String(n)]?String(n):"default"}clearLayoutConfig(){this.layoutErrorHandling=null,pa.log("Layout config cleared")}clearAllConfig(){this.templateErrorHandling=null,this.layoutErrorHandling=null,pa.log("All config cleared")}getConfigStatus(){return{hasTemplate:this.templateErrorHandling!==null,hasLayout:this.layoutErrorHandling!==null,hasExecutor:this.executeAction!==null}}};$(kr,"instance",null);let Od=kr;function ma(){return Od.getInstance()}var Ld={exports:{}},uo={};var am;function dC(){if(am)return uo;am=1;var o=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function n(r,i,l){var u=null;if(l!==void 0&&(u=""+l),i.key!==void 0&&(u=""+i.key),"key"in i){l={};for(var d in i)d!=="key"&&(l[d]=i[d])}else l=i;return i=l.ref,{$$typeof:o,type:r,key:u,ref:i!==void 0?i:null,props:l}}return uo.Fragment=e,uo.jsx=n,uo.jsxs=n,uo}var rm;function fC(){return rm||(rm=1,Ld.exports=dC()),Ld.exports}var ft=fC();const hC=Ya({__proto__:null,default:Xa(ft)},[ft]),Md=dt("ParentContextProvider"),im=I.createContext(null);let Xl=null;function $d(){Xl?(Md.log("[triggerModalParentUpdate] 모달 부모 컨텍스트 업데이트 트리거"),Xl()):Md.warn("[triggerModalParentUpdate] Provider가 아직 마운트되지 않음")}const sm=({children:o})=>{const[e,n]=I.useState(0),r=I.useRef(!0),i=I.useCallback(()=>{const u=window.__g7LayoutContextStack||[];return u[u.length-1]?.dataContext},[]);I.useEffect(()=>(r.current=!0,Xl=()=>{r.current&&(n(u=>u+1),Md.log("[ParentContextProvider] 버전 업데이트됨"))},()=>{r.current=!1,Xl=null}),[]);const l={version:e,getParentDataContext:i};return ft.jsx(im.Provider,{value:l,children:o})};function gC(){return I.useContext(im)}const z=dt("ActionDispatcher"),om=new Set(["navigate","navigateBack","navigateForward","replaceUrl","refresh","logout"]),pC=new Set(["redirect"]);function qn(){try{return window.G7Core?.devTools}catch{return}}class Ut extends Error{constructor(n,r,i){super(n);$(this,"action");$(this,"originalError");$(this,"unknownHandler",!1);this.action=r,this.originalError=i,this.name="ActionError"}}const gs=class gs{constructor(e={},n,r){$(this,"bindingEngine");$(this,"translationEngine");$(this,"translationContext");$(this,"customHandlers",new Map);$(this,"defaultContext");$(this,"globalStateUpdater");$(this,"errorHandlingSetup",!1);$(this,"debounceTimers",new Map);$(this,"pendingDebounceFlushers",new Map);$(this,"debounceAccumulatedValues",new Map);$(this,"globalHeaders",[]);$(this,"namedActions",{});$(this,"previewMode",!1);$(this,"intervals",new Map);this.bindingEngine=new Rn,this.translationEngine=n,this.translationContext=r,this.defaultContext=e,this.registerDefaultHandlers(),this.setupErrorHandling()}setGlobalHeaders(e){this.globalHeaders=e||[]}setNamedActions(e){this.namedActions=e||{};const n=qn();n?.isEnabled?.()&&n.setNamedActionDefinitions?.(this.namedActions),z.log("[setNamedActions] registered:",Object.keys(this.namedActions))}getNamedActions(){return this.namedActions}setPreviewMode(e){this.previewMode=e,z.log("Preview mode:",e?"enabled":"disabled")}isPreviewMode(){return this.previewMode}static getPreviewSuppressedHandlers(){return om}static getPreviewSuppressedLayoutFeatures(){return pC}resolveActionRef(e){if(!e.actionRef)return e;const n=this.namedActions[e.actionRef];if(!n)return z.warn(`[resolveActionRef] named action not found: "${e.actionRef}"`),e;const r=qn();r?.isEnabled?.()&&r.trackNamedActionRef?.({actionRefName:e.actionRef,resolvedHandler:n.handler,timestamp:Date.now()});const{actionRef:i,type:l,key:u,event:d,...f}=e,g={...n,...Object.fromEntries(Object.entries(f).filter(([,m])=>m!==void 0)),type:l??n.type};return u!==void 0&&(g.key=u),d!==void 0&&(g.event=d),g}matchesPattern(e,n){if(n==="*")return!0;const r=n.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(e)}getMatchingGlobalHeaders(e,n){const r={};for(const i of this.globalHeaders)this.matchesPattern(e,i.pattern)&&Object.entries(i.headers).forEach(([l,u])=>{const d=Zi(u,n,{skipCache:!0});d!=null&&d!==""&&(r[l]=String(d))});return r}setupErrorHandling(){if(this.errorHandlingSetup)return;ma().setActionExecutor(async(n,r)=>{const i={type:"click",handler:n.handler,target:n.target,params:n.params,actions:n.actions},l={data:{...this.defaultContext.data,error:r.error}};return await this.dispatchAction(i,l)}),this.errorHandlingSetup=!0}registerDefaultHandlers(){this.registerHandler("refetchDataSource",async(n,r)=>{const i=n.params?.dataSourceId,l=n.params?.sync;if(!i){z.warn("refetchDataSource: dataSourceId is required");return}if(typeof window<"u"&&window.G7Core?.dataSource?.refetch){const u=window.G7Core?.state?.get?.()||{},d={...r.state?._global,...u},f=window.G7Core?.state?.getLocal?.()||{},g=r.data?._local||r.state||{},m={...f,...g},b=r.isolatedContext?.state;z.log("[refetchDataSource] localStateOverride:",m),await window.G7Core.dataSource.refetch(i,{...l?{sync:!0}:{},...d?{globalStateOverride:d}:{},...m?{localStateOverride:m}:{},...b?{isolatedStateOverride:b}:{}})}else z.warn("refetchDataSource: G7Core.dataSource.refetch is not available")}),this.registerHandler("appendDataSource",async(n,r)=>{const{dataSourceId:i,dataPath:l,newData:u}=n.params||{};if(!i){z.warn("appendDataSource: dataSourceId is required");return}if(u===void 0){z.warn("appendDataSource: newData is required");return}if(typeof window<"u"&&window.G7Core?.dataSource?.updateData){if(!Array.isArray(u)){z.warn("appendDataSource: newData must be an array, got:",typeof u,u);return}await window.G7Core.dataSource.updateData(i,l||null,u,"append")}else z.warn("appendDataSource: G7Core.dataSource.updateData is not available")}),this.registerHandler("updateDataSource",async(n,r)=>{const{dataSourceId:i,data:l,merge:u=!1}=n.params||{};if(!i){z.warn("updateDataSource: dataSourceId is required");return}if(l===void 0){z.warn("updateDataSource: data is required");return}typeof window<"u"&&window.G7Core?.dataSource?.set?(z.log(`[updateDataSource] Updating dataSource '${i}' with:`,l),window.G7Core.dataSource.set(i,l,{merge:u})):z.warn("updateDataSource: G7Core.dataSource.set is not available")}),this.registerHandler("scrollIntoView",async(n,r)=>{const{selector:i,behavior:l="smooth",block:u="nearest",inline:d="nearest",waitForElement:f=!1,timeout:g=2e3,delay:m=0,retryCount:b=0,retryInterval:v=50,scrollContainer:S}=n.params||{};if(!i){z.warn("scrollIntoView: selector is required");return}if(typeof window>"u"||typeof document>"u"){z.warn("scrollIntoView: window/document is not available");return}let _=null;if(f){if(_=await new Promise(x=>{const k=document.querySelector(i);if(k){x(k);return}const O=setTimeout(()=>{M.disconnect(),x(null)},g),M=new MutationObserver(()=>{const T=document.querySelector(i);T&&(clearTimeout(O),M.disconnect(),x(T))});M.observe(document.body,{childList:!0,subtree:!0})}),!_){z.warn(`scrollIntoView: element not found for selector "${i}" after ${g}ms timeout`);return}}else{m>0&&await new Promise(k=>setTimeout(k,m)),_=document.querySelector(i);let x=0;for(;!_&&xsetTimeout(k,v)),_=document.querySelector(i),x++;if(!_){z.warn(`scrollIntoView: element not found for selector "${i}" after ${x+1} attempts`);return}}if(S){const x=document.querySelector(S);if(!x){z.warn(`scrollIntoView: container not found for selector "${S}"`);return}const k=_.getBoundingClientRect(),O=x.getBoundingClientRect(),M=k.top-O.top+x.scrollTop,T=M+k.height;let D;switch(u){case"start":D=M;break;case"center":D=M-x.clientHeight/2+k.height/2;break;case"end":D=T-x.clientHeight;break;default:const j=k.topO.bottom;if(j)D=M;else if(H)D=T-x.clientHeight;else return;break}x.scrollTo({top:Math.max(0,D),behavior:l});return}_.scrollIntoView({behavior:l,block:u,inline:d})}),this.registerHandler("reloadExtensions",async(n,r)=>{if(typeof window>"u"){z.warn("reloadExtensions: window is not available");return}const i=window.__templateApp;if(!i){z.warn("reloadExtensions: TemplateApp not initialized");return}if(typeof i.reloadExtensionState=="function")try{await i.reloadExtensionState()}catch(d){throw z.error("reloadExtensions: reloadExtensionState failed",d),d}else z.warn("reloadExtensions: TemplateApp.reloadExtensionState unavailable");const{moduleInfo:l,pluginInfo:u}=n.params||{};if(l)try{await this.executeAction({handler:"reloadModuleHandlers",params:n.params},r)}catch(d){z.error("reloadExtensions: reloadModuleHandlers failed",d)}if(u)try{await this.executeAction({handler:"reloadPluginHandlers",params:n.params},r)}catch(d){z.error("reloadExtensions: reloadPluginHandlers failed",d)}z.log("reloadExtensions: done")}),this.registerHandler("reloadRoutes",async(n,r)=>{if(typeof window>"u"){z.warn("reloadRoutes: window is not available");return}const i=window.__templateApp;if(!i){z.warn("reloadRoutes: TemplateApp not initialized");return}if(typeof i.reloadExtensionState=="function")try{await i.reloadExtensionState(),z.log("reloadRoutes: delegated to reloadExtensionState")}catch(l){throw z.error("reloadRoutes: Failed to reload routes",l),l}else{const l=i.getRouter?.();l&&(await l.loadRoutes(),z.log("reloadRoutes: Routes reloaded (legacy fallback)"))}}),this.registerHandler("refresh",async(n,r)=>{if(typeof window>"u"){z.warn("refresh: window is not available");return}const i=Number(n.params?.delayMs??0);i>0&&await new Promise(l=>setTimeout(l,i)),window.location.reload()}),this.registerHandler("remount",async(n,r)=>{const{componentId:i}=n.params||{};if(!i){z.warn("remount: componentId parameter is required");return}if(!this.globalStateUpdater){z.warn("remount: globalStateUpdater is not set");return}const d=(window.G7Core?.state?.get()||{})._global?._remountKeys||{},f=d[i]||0;this.globalStateUpdater({_remountKeys:{...d,[i]:f+1}}),z.log(`remount: ${i} key incremented to ${f+1}`)}),this.registerHandler("reloadTranslations",async(n,r)=>{if(typeof window>"u"){z.warn("reloadTranslations: window is not available");return}const i=window.__templateApp;if(!i){z.warn("reloadTranslations: TemplateApp not initialized");return}if(typeof i.reloadExtensionState=="function")try{await i.reloadExtensionState(),z.log("reloadTranslations: delegated to reloadExtensionState")}catch(l){throw z.error("reloadTranslations: Failed to reload translations",l),l}}),this.registerHandler("reloadModuleHandlers",async(n,r)=>{if(typeof window>"u"){z.warn("reloadModuleHandlers: window is not available");return}const{moduleInfo:i,action:l}=n.params||{};if(!i){z.warn("reloadModuleHandlers: moduleInfo is required");return}const u=i.data||i;if(!u.identifier){z.warn("reloadModuleHandlers: moduleInfo with identifier is required");return}if(!l||l!=="add"&&l!=="remove"){z.warn('reloadModuleHandlers: action must be "add" or "remove"');return}const d=window.G7Config;if(!d){z.warn("reloadModuleHandlers: G7Config not available");return}const f=u.identifier;try{if(l==="add"){if(u.assets&&(d.moduleAssets=d.moduleAssets||{},d.moduleAssets[f]=u.assets,z.log(`reloadModuleHandlers: Added assets for ${f}`),u.assets.js)){const g=u.assets.js,m=`module-${f}`;if(document.getElementById(m)){z.warn(`reloadModuleHandlers: Script ${m} already loaded`);return}const b=document.createElement("script");if(b.id=m,b.src=g,b.async=!0,await new Promise((v,S)=>{b.onload=()=>{z.log(`reloadModuleHandlers: Script loaded successfully for ${f}`),v()},b.onerror=()=>{z.error(`reloadModuleHandlers: Failed to load script for ${f}`),S(new Error(`Failed to load module script: ${g}`))},document.head.appendChild(b)}),u.assets.css){const v=u.assets.css,S=`module-css-${f}`;if(!document.getElementById(S)){const _=document.createElement("link");_.id=S,_.rel="stylesheet",_.href=v,document.head.appendChild(_),z.log(`reloadModuleHandlers: CSS loaded for ${f}`)}}}}else if(l==="remove"){d.moduleAssets&&d.moduleAssets[f]&&(delete d.moduleAssets[f],z.log(`reloadModuleHandlers: Removed assets for ${f}`));const g=`module-${f}`,m=document.getElementById(g);m&&(m.remove(),z.log(`reloadModuleHandlers: Removed script for ${f}`));const b=`module-css-${f}`,v=document.getElementById(b);v&&(v.remove(),z.log(`reloadModuleHandlers: Removed CSS for ${f}`))}}catch(g){throw z.error(`reloadModuleHandlers: Failed to ${l} module assets`,g),g}}),this.registerHandler("reloadPluginHandlers",async(n,r)=>{if(typeof window>"u"){z.warn("reloadPluginHandlers: window is not available");return}const{pluginInfo:i,action:l}=n.params||{};if(!i){z.warn("reloadPluginHandlers: pluginInfo is required");return}const u=i.data||i;if(!u.identifier){z.warn("reloadPluginHandlers: pluginInfo with identifier is required");return}if(!l||l!=="add"&&l!=="remove"){z.warn('reloadPluginHandlers: action must be "add" or "remove"');return}const d=window.G7Config;if(!d){z.warn("reloadPluginHandlers: G7Config not available");return}const f=u.identifier;try{if(l==="add"){if(u.assets&&(d.pluginAssets=d.pluginAssets||{},d.pluginAssets[f]=u.assets,z.log(`reloadPluginHandlers: Added assets for ${f}`),u.assets.js)){const g=u.assets.js,m=`plugin-${f}`;if(document.getElementById(m)){z.warn(`reloadPluginHandlers: Script ${m} already loaded`);return}const b=document.createElement("script");if(b.id=m,b.src=g,b.async=!0,await new Promise((v,S)=>{b.onload=()=>{z.log(`reloadPluginHandlers: Script loaded successfully for ${f}`),v()},b.onerror=()=>{z.error(`reloadPluginHandlers: Failed to load script for ${f}`),S(new Error(`Failed to load plugin script: ${g}`))},document.head.appendChild(b)}),u.assets.css){const v=u.assets.css,S=`plugin-css-${f}`;if(!document.getElementById(S)){const _=document.createElement("link");_.id=S,_.rel="stylesheet",_.href=v,document.head.appendChild(_),z.log(`reloadPluginHandlers: CSS loaded for ${f}`)}}}}else if(l==="remove"){d.pluginAssets&&d.pluginAssets[f]&&(delete d.pluginAssets[f],z.log(`reloadPluginHandlers: Removed assets for ${f}`));const g=`plugin-${f}`,m=document.getElementById(g);m&&(m.remove(),z.log(`reloadPluginHandlers: Removed script for ${f}`));const b=`plugin-css-${f}`,v=document.getElementById(b);v&&(v.remove(),z.log(`reloadPluginHandlers: Removed CSS for ${f}`))}}catch(g){throw z.error(`reloadPluginHandlers: Failed to ${l} plugin assets`,g),g}});let e=!1;this.registerHandler("showErrorPage",async(n,r)=>{if(e){z.log("showErrorPage: Already active, skipping duplicate call");return}if(e=!0,typeof window>"u"){e=!1,z.warn("showErrorPage: window is not available");return}const i=window.__templateApp;if(!i){e=!1,z.warn("showErrorPage: TemplateApp not initialized");return}const l=i.getErrorPageHandler?.();if(!l){e=!1,z.warn("showErrorPage: ErrorPageHandler not available");return}const u=n.params?.errorCode||500,d=n.params?.target||"content";let f=n.params?.containerId;f||(f=d==="full"?"app":"main_content"),z.log("showErrorPage:",{errorCode:u,target:d,containerId:f});const g=(m,b=6e4)=>new Promise((v,S)=>{const _=document.getElementById(m);if(_){v(_);return}z.log(`showErrorPage: Waiting for container #${m}...`);let x;const k=new MutationObserver((O,M)=>{const T=document.getElementById(m);T&&(z.log(`showErrorPage: Container #${m} found`),M.disconnect(),clearTimeout(x),v(T))});k.observe(document.body,{childList:!0,subtree:!0}),x=setTimeout(()=>{k.disconnect(),S(new Error(`Container #${m} not found within ${b}ms`))},b)});try{await g(f);const m=ma(),b=m.layoutErrorHandling;m.clearLayoutConfig();try{await l.renderError(u,f)||z.warn(`showErrorPage: Failed to render error page for code ${u}`)}finally{m.setLayoutConfig(b)}}catch(m){throw z.error("showErrorPage: Error rendering error page:",m),m}finally{e=!1}}),this.registerHandler("emitEvent",async(n,r)=>{const i=n.params?.event,l=n.params?.data;if(!i){z.warn("emitEvent: event parameter is required");return}if(typeof window>"u"){z.warn("emitEvent: window is not available");return}const u=window.G7Core;if(!u?.componentEvent?.emit){z.warn("emitEvent: G7Core.componentEvent is not available");return}try{z.log(`emitEvent: Emitting "${i}"`,l);const d={...l,_context:{data:r.data,state:r.state}},f=await u.componentEvent.emit(i,d);if(!f||f.length===0?z.warn(`emitEvent: No listeners found for "${i}"`):z.log(`emitEvent: Event "${i}" completed with ${f.length} listener(s)`,f),this.globalStateUpdater){const g=(u?.state?.get()||{})._local||{},m={event:i,success:!0,data:f.length===1?f[0]:f,listeners:f.length};this.globalStateUpdater({_local:{...g,_eventResult:m}});const b=r.state&&typeof r.state=="object"&&!Array.isArray(r.state)?r.state:g;window.__g7SequenceLocalSync={...b,_eventResult:m}}}catch(d){if(z.error(`emitEvent: Event "${i}" failed`,d),this.globalStateUpdater){const f=u?.state?.get()||{};this.globalStateUpdater({_local:{...f._local,_eventResult:{event:i,success:!1,error:d instanceof Error?d.message:String(d)}}})}throw d}}),this.registerHandler("updateProductField",async(n,r)=>{const{productId:i,field:l,value:u}=n.params||{};if(!i||!l){z.warn("updateProductField: productId and field are required");return}if(typeof window>"u"){z.warn("updateProductField: window is not available");return}const d=window.G7Core;if(!d?.state?.get||!this.globalStateUpdater){z.warn("updateProductField: G7Core.state or globalStateUpdater is not available");return}try{const f=d.state.get()||{},m=(f.products?.data?.data||[]).map(v=>v.id===i?{...v,[l]:u,_modified:!0}:v),b=new Set(f._local?.modifiedProductIds||[]);b.add(i),this.globalStateUpdater({products:{...f.products,data:{...f.products?.data,data:m}},_local:{...f._local,modifiedProductIds:Array.from(b)}}),z.log(`updateProductField: Updated product ${i}, field: ${l}, value:`,u)}catch(f){throw z.error("updateProductField: Error updating product field",f),f}}),this.registerHandler("updateOptionField",async(n,r)=>{const{productId:i,optionId:l,field:u,value:d}=n.params||{};if(!i||!l||!u){z.warn("updateOptionField: productId, optionId and field are required");return}if(typeof window>"u"){z.warn("updateOptionField: window is not available");return}const f=window.G7Core;if(!f?.state?.get||!this.globalStateUpdater){z.warn("updateOptionField: G7Core.state or globalStateUpdater is not available");return}try{const g=f.state.get()||{},b=(g.products?.data?.data||[]).map(S=>{if(S.id===i&&S.options){const _=S.options.map(x=>x.id===l?{...x,[u]:d,_modified:!0}:x);return{...S,options:_,_modified:!0}}return S}),v=new Set(g._local?.modifiedProductIds||[]);v.add(i),this.globalStateUpdater({products:{...g.products,data:{...g.products?.data,data:b}},_local:{...g._local,modifiedProductIds:Array.from(v)}}),z.log(`updateOptionField: Updated product ${i} option ${l}, field: ${u}, value:`,d)}catch(g){throw z.error("updateOptionField: Error updating option field",g),g}}),this.registerHandler("setLocale",async(n,r)=>{const i=n.target;if(!i||typeof i!="string"){z.warn("setLocale: Invalid locale:",i);return}const l=window.__templateApp;if(l&&typeof l.changeLocale=="function")try{await l.changeLocale(i),z.log("setLocale: Locale changed to",i)}catch(u){z.error("setLocale: Failed to change locale:",u),window.location.reload()}else{z.warn("setLocale: TemplateApp not found, falling back to page reload");try{localStorage.setItem("g7_locale",i)}catch{}window.location.reload()}}),this.registerHandler("suppress",async()=>{z.log("suppress: Error intentionally suppressed")}),this.registerBuiltInHandlerMetadata()}registerBuiltInHandlerMetadata(){const e=qn();if(!e?.isEnabled())return;const n=[{name:"refetchDataSource",description:"데이터 소스를 다시 fetch합니다"},{name:"appendDataSource",description:"데이터 소스에 새 데이터를 병합합니다 (무한 스크롤용)"},{name:"updateDataSource",description:"API 응답으로 데이터 소스를 직접 업데이트합니다 (refetch 대체)"},{name:"reloadRoutes",description:"라우트를 다시 로드합니다"},{name:"refresh",description:"현재 페이지를 새로고침합니다"},{name:"remount",description:"컴포넌트를 리마운트합니다"},{name:"reloadTranslations",description:"다국어 파일을 다시 로드합니다"},{name:"showErrorPage",description:"에러 페이지를 표시합니다"},{name:"emitEvent",description:"이벤트를 발생시킵니다"},{name:"updateProductField",description:"상품 필드를 인라인 수정합니다"},{name:"updateOptionField",description:"상품 옵션 필드를 인라인 수정합니다"},{name:"setLocale",description:"언어를 변경합니다 (DB 저장 + UI 리렌더링)"}];for(const r of n)e.trackHandlerRegistration(r.name,"built-in",r.description)}createHandler(e,n,r){z.log("createHandler called for:",e.handler,e.type);const i=window.__g7DevTools,l=Date.now(),u=r?.state?{...r.state}:null,d=`handler_${e.handler}_${l}`;return async f=>{if(z.log("Handler invoked for:",e.handler,"event:",f.type),i?.isEnabled?.()&&u){const m=window.G7Core?.state?.getLocal?.()??r?.state??{},b=Date.now()-l;for(const v of Object.keys(u)){const S=u[v],_=m[v];S!==_&&b>100&&(i.trackStaleClosureWarning?.({type:"event-handler-stale",location:`createHandler(${e.handler})`,capturedPath:`_local.${v}`,capturedValue:S,capturedAt:l,currentValue:_,actionId:d,stackTrace:new Error().stack}),z.warn(`[Stale Closure] _local.${v} changed after handler creation:`,`captured="${S}" → current="${_}" (${b}ms ago)`))}}try{f.type!=="change"&&f.preventDefault();let g={};if(f.type==="submit"&&f.target instanceof HTMLFormElement){const v=f.target;new FormData(v).forEach((_,x)=>{g[x]=_})}const m={...this.defaultContext,data:{...n,form:g,_local:r?.state||{},$event:f},event:f,...r&&{state:r.state,setState:r.setState},isolatedContext:r?.isolatedContext};if(e.confirm){let v=this.resolveValue(e.confirm,m.data);if(this.translationEngine&&this.translationContext&&v.startsWith("$t:")&&(v=this.translationEngine.resolveTranslations(v,this.translationContext,m.data)),!confirm(v))return}const b=window.__g7ActionContext;window.__g7ActionContext={...r,data:m.data};try{await this.executeAction(e,m)}finally{window.__g7ActionContext=b}}catch(g){if(z.error("Action execution failed:",g),e.onError){const m=g instanceof Ut&&g.originalError?g.originalError:g,b={...this.defaultContext,data:{...n,error:m,_local:r?.state||{},$event:f},event:f,...r&&{state:r.state,setState:r.setState}},v=Array.isArray(e.onError)?e.onError:[e.onError];for(const S of v)await this.executeAction(S,b)}}}}generateActionId(e,n){const r=e.handler,i=n||"no-target",l=Date.now(),u=Math.random().toString(36).substring(2,9);return`${r}_${i.replace(/[^a-zA-Z0-9]/g,"_")}_${l}_${u}`}async executeAction(e,n){if(e=this.resolveActionRef(e),typeof e.handler=="string"&&e.handler.includes("{{")){const f=this.evaluateExpression(e.handler,n.data);e={...e,handler:f==null?"":String(f)}}const r=qn(),i=r?.isEnabled()?`action_${Date.now()}_${Math.random().toString(36).substring(2,11)}`:void 0,l=performance.now();let u;if(i&&r&&r.logAction({id:i,type:e.handler,params:this.sanitizeForDevTools(e.params),context:this.sanitizeForDevTools({hasState:!!n.state,hasSetState:!!n.setState,dataKeys:n.data?Object.keys(n.data):[]}),startTime:l,status:"started"}),e.if!==void 0)try{const f=this.resolveValue(e.if,n.data),g=f===!0||f==="true"||f&&f!=="false"&&f!=="0"&&f!==!1;if(z.log("[executeAction] if condition result:",e.handler,g),!g)return i&&r&&r.logAction({id:i,type:e.handler,startTime:l,endTime:performance.now(),duration:performance.now()-l,status:"success",result:{skipped:!0,reason:"if condition false"}}),{success:!0,data:void 0}}catch(f){return z.error("[executeAction] if condition error:",e.handler,f),i&&r&&r.logAction({id:i,type:e.handler,startTime:l,endTime:performance.now(),duration:performance.now()-l,status:"error",error:{name:"ConditionEvaluationError",message:f instanceof Error?f.message:String(f),stack:f instanceof Error?f.stack:void 0}}),{success:!0,data:void 0}}let d;try{const f=this.resolveParams(e.params,n.data);i&&(u=this.sanitizeForDevTools(f));const g=e.target?this.resolveValue(e.target,n.data):void 0;if(e.handler==="apiCall"&&n.setState){d=this.generateActionId(e,g);const b=n.state?.loadingActions||{};n.setState({loadingActions:{...b,[d]:!0}})}if(this.previewMode&&om.has(e.handler))return z.warn(`Preview mode: "${e.handler}" suppressed`,g||f),i&&r&&r.logAction({id:i,type:e.handler,startTime:l,endTime:performance.now(),duration:performance.now()-l,status:"skipped",metadata:{reason:"preview_mode_suppressed"}}),{success:!0,data:void 0};let m;switch(e.handler){case"ensureIdentityVerified":m=await this.handleEnsureIdentityVerified(f);break;case"resolveIdentityChallenge":m=this.handleResolveIdentityChallenge(f);break;case"navigate":const b=f.path||g;m=await this.handleNavigate(b,f,n);break;case"navigateBack":m=await this.handleNavigateBack();break;case"navigateForward":m=await this.handleNavigateForward();break;case"openWindow":{const _=f.path||g;m=await this.handleOpenWindow(_,f);break}case"replaceUrl":{const _=f.path||g||window.location.pathname;m=await this.handleReplaceUrl(_,f);break}case"apiCall":if(e.onSuccess&&r?.isEnabled()&&i){const _=window.G7Core,x={};if(_?.state?.get){const k=_.state.get();x._global=k}n.state&&(x._local=n.state),r.registerStateCaptureForHandler?.(i,["_global","_local"],x)}const v=e.auth_mode??(e.auth_required?"required":"none"),S=e.identity_target?this.resolveParams(e.identity_target,n.data):void 0;m=await this.handleApiCall(g,f,n,v,S);break;case"login":m=await this.handleLogin(g,f,n);break;case"logout":m=await this.handleLogout(g,n);break;case"setState":z.log("[executeAction] setState resolvedParams:",f),m=await this.handleSetState(e.render!==void 0?{...f,__render:e.render}:f,n);break;case"setError":m=await this.handleSetError(g,f,n);break;case"openModal":m=await this.handleOpenModal(g,n);break;case"closeModal":m=await this.handleCloseModal(n);break;case"showAlert":m=await this.handleShowAlert(g,n);break;case"toast":m=await this.handleToast(f,n);break;case"switch":m=await this.handleSwitch(e,n);break;case"conditions":m=await this.handleConditions(e,n);break;case"sequence":m=await this.handleSequence(e,n);break;case"parallel":m=await this.handleParallel(e,n);break;case"startInterval":m=this.handleStartInterval(f,n);break;case"stopInterval":m=this.handleStopInterval(f);break;case"loadScript":m=await this.handleLoadScript(f,e,n);break;case"callExternal":m=await this.handleCallExternal(f,e,n);break;case"callExternalEmbed":m=await this.handleCallExternalEmbed(f,e,n);break;case"saveToLocalStorage":m=await this.handleSaveToLocalStorage(f,n);break;case"loadFromLocalStorage":m=await this.handleLoadFromLocalStorage(f,n);break;default:m=await this.handleCustomAction({...e,target:g,params:f},n);break}if(e.resultTo&&m!==void 0){const{target:b,key:v,merge:S}=e.resultTo,_=this.resolveValue(v,n.data),x=S==="replace"?"replace":S==="shallow"?"shallow":"deep";if(b==="_local"&&n.setState){const k=this.buildNestedUpdate(_,m),O=x!=="deep"?{...k,__mergeMode:x}:k;n.setState(O),z.log(`[resultTo] Saved to _local.${_} (merge=${x}):`,m)}else if(b==="_local"&&this.globalStateUpdater){const M=(window.G7Core?.state?.get()||{})._local||{},T=this.buildNestedUpdate(_,m);let D;x==="replace"?D=T:x==="shallow"?D={...M,...T}:D=this.deepMergeWithState(T,M),this.globalStateUpdater({_local:D}),z.log(`[resultTo] Saved to _local.${_} via globalStateUpdater (merge=${x}):`,m)}else if(b==="_global"&&this.globalStateUpdater){const k=this.buildNestedUpdate(_,m);this.globalStateUpdater(k),z.log(`[resultTo] Saved to _global.${_}:`,m)}else if(b==="_isolated"&&n.isolatedContext){const k=this.buildNestedUpdate(_,m);n.isolatedContext.mergeState(k,x),z.log(`[resultTo] Saved to _isolated.${_} (merge=${x}):`,m)}else z.warn(`[resultTo] Cannot save result: target=${b}, setState=${!!n.setState}, globalStateUpdater=${!!this.globalStateUpdater}, isolatedContext=${!!n.isolatedContext}`)}if(e.onSuccess){if(r?.isEnabled()&&i&&e.handler==="apiCall"){const S=window.G7Core,_={};S?.state?.get&&(_._global=S.state.get()),n.state&&(_._local=n.state),r.detectStaleClosure?.(i,`${e.handler} → onSuccess`,_,"callback-state-capture",i)}const b={...n,data:{...n.data,result:m,response:m}},v=Array.isArray(e.onSuccess)?e.onSuccess:[e.onSuccess];v.length>1?await this.handleSequence({handler:"sequence",type:"click",actions:v},b):v.length===1&&await this.executeAction(v[0],b)}return i&&r&&r.logAction({id:i,type:e.handler,params:this.sanitizeForDevTools(e.params),resolvedParams:u,startTime:l,endTime:performance.now(),duration:performance.now()-l,status:"success",result:this.sanitizeForDevTools(m)}),{success:!0,data:m}}catch(f){const g=f instanceof Ut?f:new Ut(`Failed to execute action: ${e.handler}`,e,f instanceof Error?f:void 0),m=g.originalError?.response||{},b=m.data||{},v=g.originalError?.status||m.status||500,S=b.message||g.message,_={status:v,message:S,errors:b.errors||m.errors,data:b,statusText:g.originalError?.statusText,error_code:b.error_code??m.error_code};if(g.unknownHandler)throw z.warn(`Unknown action handler "${e.handler}" — skipped (extension not loaded?). Not surfaced to the user.`),g;const k=ma().resolve(v,{errorHandling:e.errorHandling,onError:e.onError});if(k.handler){if(r?.isEnabled()&&i&&e.handler==="apiCall"){const M=window.G7Core,T={};M?.state?.get&&(T._global=M.state.get()),n.state&&(T._local=n.state),r.detectStaleClosure?.(i,`${e.handler} → onError`,T,"callback-state-capture",i)}const O={...n,data:{...n.data,error:_}};try{const M={type:"click",handler:k.handler.handler,target:k.handler.target,params:k.handler.params,actions:k.handler.actions};return await this.executeAction(M,O),{success:!1,error:g}}catch(M){return z.error("Error executing error handler:",M),{success:!1,error:g}}}throw i&&r&&r.logAction({id:i,type:e.handler,params:this.sanitizeForDevTools(e.params),resolvedParams:u,startTime:l,endTime:performance.now(),duration:performance.now()-l,status:"error",error:{name:g.name,message:g.message,stack:g.stack}}),g}finally{if(e.handler==="apiCall"&&n.setState&&d){const f=n.state?.loadingActions||{},{[d]:g,...m}=f;n.setState({loadingActions:m})}}}async handleNavigate(e,n,r){let i=e;if(n.query||n.mergeQuery===!0)if(n.mergeQuery===!0)i=this.buildMergedQueryPath(e,n.query??{});else{const u=new URLSearchParams;for(const[f,g]of Object.entries(n.query))if(g!=null&&g!=="")if(Array.isArray(g)){const m=f.endsWith("[]")?f:`${f}[]`;for(const b of g)b!=null&&b!==""&&u.append(m,String(b))}else u.set(f,String(g));const d=u.toString();d&&(i=`${e}?${d}`)}if(z.log("handleNavigate:",{target:e,params:n,finalPath:i,replace:n.replace,windowLocationSearch:window.location.search}),n.replace===!0){const u=window.G7Core;if(u?.updateQueryParams){const d=typeof n.transition_overlay_target=="string"?n.transition_overlay_target:void 0;await u.updateQueryParams(i,d?{transitionOverlayTarget:d}:void 0),z.log("handleNavigate: Used updateQueryParams for replace mode",d?{transitionOverlayTarget:d}:void 0),this.applyScrollOption(n.scroll,n.scrollBehavior,"top");return}z.warn("handleNavigate: G7Core.updateQueryParams not available, falling back to React Router")}const l=this.resolveNavigateFallbackAction(i,n);if(l){z.warn(`handleNavigate: No route matched, falling back to "${l.handler}"`),await this.dispatchAction({type:"click",handler:l.handler,params:l.params},r),this.applyScrollOption(n.scroll,n.scrollBehavior,"top");return}if(!r.navigate)throw new Ut("Navigate function is not provided in context");r.navigate(i,{replace:n.replace===!0}),this.applyScrollOption(n.scroll,n.scrollBehavior,"top")}resolveNavigateFallbackAction(e,n){const r=n.fallback;if(r===!1||n.replace===!0)return null;const l=window.__templateApp?.getRouter?.();if(!l||typeof l.match!="function"||typeof l.getRoutes=="function"&&l.getRoutes().length===0)return null;const u=e.split("?")[0];return l.match(u)?null:this.resolveNavigateFallback(r,e,n)}resolveNavigateFallback(e,n,r){return e==null?{handler:"openWindow",params:{path:n,target:"_self"}}:typeof e=="string"?{handler:e,params:{path:n}}:typeof e=="object"&&typeof e.handler=="string"?{handler:e.handler,params:{path:n,...e.params||{}}}:(z.warn("resolveNavigateFallback: unrecognized fallback option, using openWindow",e),{handler:"openWindow",params:{path:n,target:"_blank"}})}applyScrollOption(e,n,r){const i=e===void 0?r:e;if(i==="preserve")return;const l=n==="smooth"?"smooth":"instant",u=b=>{if(typeof b!="object"||b===null)return!1;const v=b;return"container"in v||"to"in v||"block"in v||"offset"in v},d=(b,v,S=0)=>{b===window?window.scrollTo({top:v,left:S,behavior:l}):b.scrollTo({top:v,left:S,behavior:l})},f=(b,v,S,_)=>{if(v===window){b.scrollIntoView({behavior:l,block:S}),_&&window.scrollBy({top:-_,left:0,behavior:l});return}const x=v,k=b.getBoundingClientRect(),O=x.getBoundingClientRect(),M=x.scrollTop+(k.top-O.top);let T;S==="center"?T=M-(x.clientHeight-b.clientHeight)/2:S==="end"?T=M-(x.clientHeight-b.clientHeight):T=M,T-=_,x.scrollTo({top:Math.max(0,T),left:0,behavior:l})},g=()=>{window.scrollTo({top:0,left:0,behavior:l});const b=document.getElementById("app")??document.body;if(!b)return;b.querySelectorAll("*").forEach(S=>{if(S.scrollTop===0&&S.scrollLeft===0)return;const _=window.getComputedStyle(S),x=_.overflowY,k=_.overflowX;(x==="auto"||x==="scroll"||k==="auto"||k==="scroll")&&S.scrollTo({top:0,left:0,behavior:l})})},m=()=>{try{if(u(i)){const b=i,v=b.block??"start",S=typeof b.offset=="number"?b.offset:0;let _=window;if(typeof b.container=="string"&&b.container.length>0){const k=document.querySelector(b.container);if(!k){z.warn(`applyScrollOption: container not found: ${b.container}`);return}_=k}const x=b.to??"top";if(x==="top"){_===window?g():d(_,0);return}if(typeof x=="number"){d(_,x-S);return}if(typeof x=="object"&&x!==null&&("x"in x||"y"in x)){const{x:k=0,y:O=0}=x;d(_,O-S,k);return}if(typeof x=="string"&&(x.startsWith("#")||x.startsWith("."))){const k=document.querySelector(x);k?f(k,_,v,S):z.warn(`applyScrollOption: target element not found: ${x}`);return}z.warn('applyScrollOption: invalid "to" value in extended form',x);return}if(i==="top"){g();return}if(typeof i=="number"){window.scrollTo({top:i,left:0,behavior:l});return}if(typeof i=="object"&&i!==null&&("x"in i||"y"in i)){const{x:b=0,y:v=0}=i;window.scrollTo({top:v,left:b,behavior:l});return}if(typeof i=="string"&&(i.startsWith("#")||i.startsWith("."))){const b=document.querySelector(i);b&&b.scrollIntoView({behavior:l,block:"start"});return}}catch(b){z.warn("applyScrollOption: failed to apply scroll",b)}};typeof window.requestAnimationFrame=="function"?window.requestAnimationFrame(m):m()}async handleOpenWindow(e,n){let r=e;if(n.query){const l=new URLSearchParams;for(const[d,f]of Object.entries(n.query))f!=null&&f!==""&&l.set(d,String(f));const u=l.toString();u&&(r=`${e}?${u}`)}const i=n.target==="_self"?"_self":"_blank";z.log("handleOpenWindow:",{target:e,params:n,finalPath:r,windowTarget:i}),i==="_self"?window.location.assign(r):window.open(r,"_blank")}async handleNavigateBack(){z.log("handleNavigateBack"),window.history.back()}async handleNavigateForward(){z.log("handleNavigateForward"),window.history.forward()}async handleReplaceUrl(e,n){let r=e;if(n.query||n.mergeQuery===!0)if(n.mergeQuery===!0)r=this.buildMergedQueryPath(e,n.query??{});else{const i=new URLSearchParams;for(const[u,d]of Object.entries(n.query))if(d!=null&&d!=="")if(Array.isArray(d)){const f=u.endsWith("[]")?u:`${u}[]`;for(const g of d)g!=null&&g!==""&&i.append(f,String(g))}else i.set(u,String(d));const l=i.toString();l&&(r=`${e}?${l}`)}z.log("handleReplaceUrl:",{target:e,params:n,finalPath:r}),window.history.replaceState(null,"",r),this.applyScrollOption(n.scroll,n.scrollBehavior,"preserve")}buildMergedQueryPath(e,n){const r=new URLSearchParams(window.location.search);for(const[u,d]of Object.entries(n))if(d==null||d==="")r.delete(u);else if(Array.isArray(d)){const f=u.endsWith("[]")?u:`${u}[]`;r.delete(u),r.delete(f);for(const g of d)g!=null&&g!==""&&r.append(f,String(g))}else r.set(u,String(d));const i=r.toString(),l=e.split("?")[0];return i?`${l}?${i}`:l}async ensureCsrfToken(){try{await fetch("/sanctum/csrf-cookie",{credentials:"include"})}catch(e){throw new Ut("Failed to fetch CSRF token",void 0,e instanceof Error?e:void 0)}}getCsrfTokenFromCookie(){const r=`; ${document.cookie}`.split("; XSRF-TOKEN=");if(r.length===2){const i=r.pop()?.split(";").shift();return i?decodeURIComponent(i):null}return null}buildQueryString(e){const n=new URLSearchParams;for(const[r,i]of Object.entries(e))if(!(i==null||i===""))if(Array.isArray(i))for(const l of i)l!=null&&l!==""&&n.append(`${r}[]`,String(l));else typeof i=="object"?n.append(r,JSON.stringify(i)):n.append(r,String(i));return n.toString()}async handleEnsureIdentityVerified(e){const n=typeof e.purpose=="string"?e.purpose:"sensitive_action",r=e.target&&typeof e.target=="object"?e.target:void 0;return await wt.handle({success:!1,error_code:"identity_verification_required",message:"",verification:{policy_key:e.policy_key??"",purpose:n,provider_id:e.provider_id??null,render_hint:e.render_hint??null,return_request:null}},void 0,r)!==null}handleResolveIdentityChallenge(e){const n=typeof e.result=="string"?e.result:"cancelled";let r;switch(n){case"verified":{const i=typeof e.token=="string"?e.token:"";if(!i){z.warn("resolveIdentityChallenge: result=verified 인데 token 이 비어있습니다. failed 로 강등합니다."),r={status:"failed",failureCode:"MISSING_TOKEN"};break}r={status:"verified",token:i,providerData:e.providerData&&typeof e.providerData=="object"?e.providerData:void 0};break}case"pending":{const i=typeof e.pollUrl=="string"?e.pollUrl:"",l=typeof e.expiresAt=="string"?e.expiresAt:"";if(!i||!l){z.warn("resolveIdentityChallenge: result=pending 인데 pollUrl/expiresAt 누락 — failed 로 강등합니다."),r={status:"failed",failureCode:"MALFORMED_PENDING"};break}r={status:"pending",pollUrl:i,pollIntervalMs:typeof e.pollIntervalMs=="number"?e.pollIntervalMs:void 0,expiresAt:l};break}case"failed":r={status:"failed",failureCode:typeof e.failureCode=="string"?e.failureCode:"UNKNOWN",reason:typeof e.reason=="string"?e.reason:void 0};break;default:r={status:"cancelled"};break}return wt.resolveDeferred(r),!0}async handleApiCall(e,n,r,i="none",l){const{method:u="GET",body:d,headers:f,contentType:g}=n;u!=="GET"&&u!=="HEAD"&&await this.ensureCsrfToken();const m=this.getCsrfTokenFromCookie();let b={};if(i==="required"||i==="optional"){const X=Ia().getToken();X&&(b={Authorization:`Bearer ${X}`})}let v=e;const S=n.query||(u==="GET"?d:null);if(S&&typeof S=="object"){const P=this.buildQueryString(S);if(P){const X=e.includes("?")?"&":"?";v=`${e}${X}${P}`}}const _=window.G7Core?.state?.getGlobal?.()||r.state?._global||{},x=window.G7Core?.state?.getLocal?.()||r.state?._local||{},k={_global:_,_local:x},O=this.getMatchingGlobalHeaders(e,k),M={};if(typeof window<"u"){const P=localStorage.getItem("g7_locale");P&&(M["Accept-Language"]=P)}const T=g==="multipart/form-data",D={method:u,headers:{...T?{}:{"Content-Type":"application/json"},Accept:"application/json",...M,...m&&{"X-XSRF-TOKEN":m},...b,...O,...f},credentials:"include"};if(d&&u!=="GET")if(T){const P=new FormData;for(const[X,pe]of Object.entries(d))pe instanceof File||pe instanceof Blob?P.append(X,pe):pe!=null&&P.append(X,typeof pe=="object"?JSON.stringify(pe):String(pe));D.body=P}else D.body=JSON.stringify(d);const j=qn();let H=null;j?.isEnabled()&&(H=j.trackRequest(v,u));try{let P=await fetch(v,D),X;try{X=await P.json()}catch{X=null}if(wt.isIdentityRequired(P.status,X)){const pe=await wt.handle(X,{body:D.body,headers:D.headers,credentials:D.credentials},l);if(pe){P=pe;try{X=await P.json()}catch{X=null}}}if(H&&j?.isEnabled()&&(j.completeRequest(H,P.status,X),H=null),!P.ok){const pe=X||{},_e=new Error(pe.message||`API call failed: ${P.statusText}`);throw _e.response=pe,_e.status=P.status,_e.statusText=P.statusText,new Ut(pe.message||`API call failed: ${P.statusText}`,void 0,_e)}return X}catch(P){throw H&&j?.isEnabled()&&j.failRequest(H,P instanceof Error?P.message:String(P)),P}}async handleLogin(e,n,r){const{body:i}=n;if(!i||!i.email||!i.password)throw new Ut("Login requires email and password in body params");const l=e==="user"?"user":"admin",u=l==="admin"?"/api/auth/admin/login":"/api/auth/login",d=window.G7Core?.state?.getGlobal?.()||r.state?._global||{},f=window.G7Core?.state?.getLocal?.()||r.state?._local||{},g={_global:d,_local:f},m=this.getMatchingGlobalHeaders(u,g),b=ga.getInstance();try{const v=Object.keys(m).length>0?{headers:m}:void 0;return{user:await b.login(l,{email:i.email,password:i.password},v)}}catch(v){const S=v.message||"Login failed",_=new Error(S);throw _.response=v.response?.data||{},_.status=v.status||v.response?.status||500,new Ut(S,void 0,_)}}async handleLogout(e,n){await ga.getInstance().logout()}async handleSetState(e,n){z.log("[handleSetState] START, params:",e);const{target:r="component",scope:i,merge:l,__render:u,...d}=e,f=qn(),g=window.G7Core;if(typeof r=="string"&&(r.startsWith("$parent.")||r.startsWith("$root.")))return this.handleParentScopeSetState(r,d,l,n);const m=n.state&&Object.keys(n.state).length>0?n.state:g?.state?.get()||{},b=r==="global"?"_global":r.startsWith("_local.")?r:"_local",v=b==="_global"?m._global:b.startsWith("_local.")?this.getNestedProperty(m._local||{},b.slice(7)):m._local,S=f?.isEnabled()?f.startStateChange(b,v,d,{actionId:n.actionId,handlerType:"setState",source:`target=${r}`}):void 0,_=l==="replace"?"replace":l==="shallow"?"shallow":"deep",x=_!=="deep"?{...d,__mergeMode:_,...S?{__setStateId:S}:{}}:{...d,...S?{__setStateId:S}:{}};if(r==="global"){if(!this.globalStateUpdater){z.warn("Global state updater is not set"),S&&f&&f.completeStateChange(S);return}const k=g?.state?.get()||{},{__setStateId:O,__mergeMode:M,...T}=x,D=_==="deep"?this.deepMergeWithState(T,k):T,j={...D,...S?{__setStateId:S}:{},..._!=="deep"?{__mergeMode:_}:{}};return z.log("setState global:",j),this.globalStateUpdater(j,{render:u}),S&&f&&setTimeout(()=>f.completeStateChange(S),0),{__target:"global",..._!=="deep"?{__mergeMode:_}:{},...D}}else if(r==="isolated"){const k=n.isolatedContext;if(k){const{__mergeMode:O,__setStateId:M,...T}=x;return k.mergeState(T,_),z.log("[handleSetState] isolated state updated:",T,"mergeMode:",_),S&&f&&setTimeout(()=>f.completeStateChange(S),0),{__target:"isolated",...T}}else if(z.warn('[handleSetState] isolated target used but no IsolatedStateContext found. Make sure the component has "isolatedState" attribute. Falling back to local state.'),n.setState){const M=window.__g7PendingLocalState||n.state||{},T=_==="deep"?this.deepMergeWithState(x,M):x;return n.setState(T),S&&f&&setTimeout(()=>f.completeStateChange(S),0),T}else throw S&&f&&f.completeStateChange(S),new Ut("isolated target used but no IsolatedStateContext found and no setState function in context")}else if(r==="local"||r==="component"||r==="_local"){if(i==="parent"||i==="root"){const O=window.__g7LayoutContextStack||[];if(O.length>0){const M=i==="parent"?O[O.length-1]:O[0];if(M?.setState){const{__mergeMode:T,__setStateId:D,...j}=x,H=_==="deep"?this.deepMergeWithState(j,M.state||{}):j;return z.log(`[handleSetState] scope=${i}: 타겟 컨텍스트에 상태 업데이트`,H),M.setState(H),S&&f&&setTimeout(()=>f.completeStateChange(S),0),H}}z.warn(`[handleSetState] scope=${i}: 레이아웃 컨텍스트 스택이 비어있습니다. current로 폴백합니다.`)}const k=n.setState&&!n._isDispatchFallbackContext;if(z.log("[handleSetState] isRealComponentContext:",k,"context.setState:",!!n.setState,"_isDispatchFallbackContext:",n._isDispatchFallbackContext),k){z.log("[handleSetState] Using COMPONENT setState path"),z.log("[handleSetState] resolvedPayload:",x),z.log("[handleSetState] context.state:",n.state),z.log("[handleSetState] mergeMode:",_);const M=window.__g7PendingLocalState||n.state||{},T=_==="deep"?this.deepMergeWithState(x,{}):x;z.log("[handleSetState] convertedPayload (변경 필드만, dot notation 변환):",T),n.setState(T);const D=_==="deep"?this.deepMergeWithState(x,M):_==="shallow"?{...n.state||{},...x}:x,{__mergeMode:j,__setStateId:H,...P}=D;window.__g7PendingLocalState=P,z.log("[handleSetState] __g7PendingLocalState updated:",P),this.globalStateUpdater&&(this.globalStateUpdater({_local:P},{render:!1}),z.log("[handleSetState] _global._local synced (render:false):",P));const{__mergeMode:X,__setStateId:pe,..._e}=x;if(_==="replace")window.__g7ForcedLocalFields=_e;else{const we=window.__g7ForcedLocalFields||{};window.__g7ForcedLocalFields=this.deepMergeWithState(_e,we)}return z.log("[handleSetState] __g7ForcedLocalFields updated:",_e),S&&f&&setTimeout(()=>f.completeStateChange(S),0),{__target:"local",...D}}else if(this.globalStateUpdater){z.log("[handleSetState] Using GLOBAL STATE UPDATER path for _local");const M=window.__g7PendingLocalState||m._local||{};z.log("[handleSetState] currentLocal (with pending):",M);const T=_==="deep"?this.deepMergeWithState(x,M):x;return z.log("[handleSetState] finalLocal (merged):",T),this.globalStateUpdater({_local:T},{render:u}),window.__g7PendingLocalState=T,z.log("[handleSetState] __g7PendingLocalState updated for globalStateUpdater path"),S&&f&&setTimeout(()=>f.completeStateChange(S),0),{__target:"local",...T}}else throw S&&f&&f.completeStateChange(S),new Ut("setState function is not provided in context and globalStateUpdater is not set")}else if(r.startsWith("_local.")){const k=r.slice(7),{__mergeMode:O,__setStateId:M,...T}=x,D=T.value!==void 0?T.value:Object.values(T)[0];if(n.setState){const H=window.__g7PendingLocalState||n.state||{},P=this.createNestedUpdate(k,D,H),X={...H,...P};return n.setState(P),S&&f&&setTimeout(()=>f.completeStateChange(S),0),X}else throw S&&f&&f.completeStateChange(S),new Ut("setState function is not provided in context")}else{if(!n.setState)throw S&&f&&f.completeStateChange(S),new Ut("setState function is not provided in context");const O=window.__g7PendingLocalState||n.state||{},M=_==="deep"?this.deepMergeWithState(x,O):x;return n.setState(M),S&&f&&setTimeout(()=>f.completeStateChange(S),0),M}}async handleParentScopeSetState(e,n,r,i){const l=qn(),u=window.G7Core,d=r==="replace"?"replace":r==="shallow"?"shallow":"deep",f=e.startsWith("$parent."),g=f?"$parent.":"$root.",m=e.slice(g.length);let b,v;if(m==="_local"||m==="_global")b=m,v=void 0;else if(m.startsWith("_local."))b="_local",v=m.slice(7);else if(m.startsWith("_global."))b="_global",v=m.slice(8);else{z.warn(`[handleParentScopeSetState] 지원하지 않는 타겟 형식: ${e}. _local 또는 _global으로 시작해야 합니다.`);return}const S=window.__g7LayoutContextStack||[];if(S.length===0){z.warn(`[handleParentScopeSetState] 레이아웃 컨텍스트 스택이 비어있습니다. target=${e}`);return}const _=f?S[S.length-1]:S[0];if(!_){z.warn(`[handleParentScopeSetState] 타겟 컨텍스트를 찾을 수 없습니다. target=${e}`);return}const x=b==="_global"?_.state?._global:_.state?._local,k=l?.isEnabled()?l.startStateChange(e,x,n,{actionId:i.actionId,handlerType:"setState",source:`target=${e}`}):void 0,{__mergeMode:O,__setStateId:M,...T}=n;if(b==="_global"){if(!this.globalStateUpdater){z.warn("[handleParentScopeSetState] globalStateUpdater가 설정되지 않았습니다."),k&&l&&l.completeStateChange(k);return}const D=u?.state?.get()||{};if(v){const j=T.value!==void 0?T.value:Object.values(T)[0],H=this.createNestedUpdate(v,j,D),P={...D,...H};z.log(`[handleParentScopeSetState] ${e}: 전역 상태 중첩 경로 업데이트`,P),this.globalStateUpdater(P)}else{const j=d==="deep"?this.deepMergeWithState(T,D):T;z.log(`[handleParentScopeSetState] ${e}: 전역 상태 업데이트 (mergeMode=${d})`,j),this.globalStateUpdater(d!=="deep"?{...j,__mergeMode:d}:j)}return k&&l&&setTimeout(()=>l.completeStateChange(k),0),{__target:e,...T}}else{if(!_.setState){z.warn(`[handleParentScopeSetState] 타겟 컨텍스트에 setState가 없습니다. target=${e}`),k&&l&&l.completeStateChange(k);return}const D=_.state||{};if(v){const j=T.value!==void 0?T.value:Object.values(T)[0],H=this.createNestedUpdate(v,j,D),P={...D,...H};return z.log(`[handleParentScopeSetState] ${e}: 로컬 상태 중첩 경로 업데이트`,H),_.setState(H),_.state=P,_.dataContext&&(_.dataContext._local=P),$d(),k&&l&&setTimeout(()=>l.completeStateChange(k),0),P}else{const j=d!=="deep"?{...T,__mergeMode:d}:T,H=d==="replace"?T:d==="shallow"?{...D,...T}:this.deepMergeWithState(T,D);return z.log(`[handleParentScopeSetState] ${e}: 로컬 상태 업데이트 (mergeMode=${d})`,H),_.setState(j),_.state=H,_.dataContext&&(_.dataContext._local=H),$d(),k&&l&&setTimeout(()=>l.completeStateChange(k),0),H}}}deepMergeWithState(e,n){const r=["errors"];let i=e;if("..."in e){const u=e["..."];if(u&&typeof u=="object"&&!Array.isArray(u)){const{"...":d,...f}=e;i={...u,...f}}else{const{"...":d,...f}=e;i=f}}const l={...n};for(const[u,d]of Object.entries(i)){if(r.includes(u)){l[u]=d;continue}if(u.includes(".")&&u!=="..."){const f=this.createNestedUpdate(u,d,l);this.deepMergeInto(l,f,l);continue}if(d!==null&&typeof d=="object"&&!Array.isArray(d)&&Object.getPrototypeOf(d)!==Object.prototype&&Object.getPrototypeOf(d)!==null){l[u]=d;continue}d!==null&&typeof d=="object"&&!Array.isArray(d)&&n[u]!==null&&typeof n[u]=="object"&&!Array.isArray(n[u])?l[u]=this.deepMergeWithState(d,n[u]):l[u]=d}return l}deepMergeInto(e,n,r){for(const[i,l]of Object.entries(n)){if(l===null){e[i]=l;continue}if(e[i]===null){e[i]=l;continue}typeof l=="object"&&!Array.isArray(l)&&e[i]!==void 0&&e[i]!==null&&typeof e[i]=="object"&&!Array.isArray(e[i])?(e[i]===r[i]&&(e[i]={...e[i]}),this.deepMergeInto(e[i],l,r[i]||{})):typeof l=="object"&&!Array.isArray(l)&&e[i]===void 0&&r[i]!==null&&typeof r[i]=="object"&&!Array.isArray(r[i])?e[i]={...r[i],...l}:e[i]=l}}createNestedUpdate(e,n,r){const i=e.split(".");if(i.length===1)return{[i[0]]:n};const l={};let u=l,d=r;for(let f=0;f{this.globalStateUpdater({_local:S})};m.push({state:b,setState:v,dataContext:{_local:b||n.data?._local,_global:l?n.data?._global:n.data?._global||i?.state?.get?.(),_computed:n.data?._computed}}),window.__g7LayoutContextStack=m,z.log(`[handleOpenModal] 레이아웃 컨텍스트 스택에 push, 스택 크기: ${m.length}, state:`,b,l?"(direct)":"(fallback via G7Core)")}else z.warn(`[handleOpenModal] 컨텍스트 스택에 push 실패 - setState: ${!!n.setState}, state: ${n.state!==void 0}, G7Core: ${!!i?.state?.getLocal}`);const f=[...r,e];this.globalStateUpdater({modalStack:f,activeModal:e});const g=qn();if(g?.isEnabled()){const m=r.length>0?r[r.length-1]:void 0;g.trackModalOpen?.({modalId:e,modalName:e,scopeType:"isolated",parentModalId:m,initialState:n.state?{...n.state}:{}})}}async handleCloseModal(e){if(!this.globalStateUpdater){z.warn("Global state updater is not set for closeModal");return}const n=e?.data?._global?.modalStack||[],r=n.length>0?n[n.length-1]:null,i=n.slice(0,-1),l=i.length>0?i[i.length-1]:null,u=window.__g7LayoutContextStack||[];if(u.length>0){const d=u[u.length-1];d&&(d.dataContext=void 0),u.pop(),window.__g7LayoutContextStack=u,z.log(`[handleCloseModal] 레이아웃 컨텍스트 스택에서 pop, 스택 크기: ${u.length}`)}if(r){const d=qn();d?.isEnabled()&&d.trackModalClose?.(r,e?.state)}this.globalStateUpdater({modalStack:i,activeModal:l})}async handleShowAlert(e,n){let r=e;this.translationEngine&&this.translationContext&&e.startsWith("$t:")&&(r=this.translationEngine.resolveTranslations(e,this.translationContext,n.data)),alert(r)}async handleToast(e,n){const{type:r="info",message:i,icon:l,duration:u}=e;if(r==="error"){const f=n.data?.error;if((f?.error_code==="identity_verification_required"||f?.data?.error_code==="identity_verification_required")&&wt.consumeDomainNoticeShown()){z.log("[Toast] IDV 도메인 안내 표출됨 — 중복 가드 토스트 1건 skip");return}}let d=i;if(this.translationEngine&&this.translationContext&&i?.startsWith("$t:")&&(d=this.translationEngine.resolveTranslations(i,this.translationContext,n.data)),this.globalStateUpdater){const g={id:`toast_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,type:r,message:d,...l&&{icon:l},...u&&{duration:u}},S=[...window.G7Core?.state?.get()?.toasts||[],g];this.globalStateUpdater({toasts:S})}else z.log(`[Toast ${r}] ${d}`)}async handleSwitch(e,n){const{cases:r}=e;if(!r){z.warn("switch handler requires cases property");return}const i=this.resolveParams(e.params,n.data);let l;if(i?.value!==void 0?(l=i.value,z.log("switch handler: using params.value as case key:",l)):(l=n.data?.$args?.[0],z.log("switch handler: using $args[0] as case key:",l)),l==null){if(r.default)return z.log("switch handler: case key is undefined, using default case"),await this.executeAction(r.default,n);z.warn("switch handler: case key is not defined and no default case");return}const u=String(l);let d=r[u];if(!d&&r.default&&(z.log(`switch handler: no case found for key "${u}", using default case`),d=r.default),!d){z.warn(`switch handler: no case found for key "${u}" and no default case`);return}return await this.executeAction(d,n)}async handleConditions(e,n){const{conditions:r}=e;if(!r||!Array.isArray(r)){z.warn("conditions handler requires conditions array");return}const i=n.data||{},l=up(r,i,this.bindingEngine);if(!l.matched){z.log("conditions handler: no matching branch found");return}const u=r[l.branchIndex];if(z.log(`conditions handler: matched branch ${l.branchIndex}`),!u.then){z.warn('conditions handler: matched branch has no "then" action');return}return Array.isArray(u.then)?await this.handleSequence({...e,actions:u.then},n):await this.executeAction(u.then,n)}handleStartInterval(e,n){const r=typeof e.id=="string"?e.id:"",i=Number(e.intervalMs??1e3),l=Array.isArray(e.actions)?e.actions:[];if(r===""||!l.length||i<=0)return z.warn("startInterval requires non-empty id, positive intervalMs, and actions array"),{success:!1};const u=this.intervals.get(r);u&&(clearInterval(u),this.intervals.delete(r));const d=setInterval(()=>{for(const f of l)this.executeAction(f,n).catch(g=>{z.error(`[startInterval:${r}] tick action failed`,g)})},i);return this.intervals.set(r,d),{success:!0,id:r}}handleStopInterval(e){const n=typeof e.id=="string"?e.id:"";if(n==="")return z.warn("stopInterval requires id parameter"),{success:!1};const r=this.intervals.get(n);return r&&(clearInterval(r),this.intervals.delete(n)),{success:!0,id:n}}stopAllIntervals(){for(const e of this.intervals.values())clearInterval(e);this.intervals.clear()}async handleSequence(e,n){const r=e.actions||e.params?.actions;if(!r||!Array.isArray(r)||r.length===0)return z.warn("sequence handler requires non-empty actions array"),[];const i=qn(),l=i?.isEnabled()&&i.startSequenceExecution?.({eventType:e.type})||"";window.__g7SequenceLocalSync=void 0;const u=[];let d,f=n.state?{...n.state}:{},g=n.isolatedContext?.state?{...n.isolatedContext.state}:{},m=n.data?._computed||{};const b=window.G7Core,v=()=>({_global:b?.state?.get()||{},_local:{...f},_isolated:Object.keys(g).length>0?{...g}:void 0});for(let S=0;S0){const T={},D={...n.data,_local:f,_computed:T,$computed:T,_isolated:g};for(const[j,H]of Object.entries(M))if(typeof H=="string"){const P=H.trim();if(P.startsWith("{{")&&P.endsWith("}}"))try{const X=P.slice(2,-2).trim();T[j]=this.bindingEngine.evaluateExpression(X,D,{skipCache:!0})}catch{T[j]=m[j]}}m=T,z.log("[handleSequence] _computed recalculated after setState:",m)}}if(_.handler!=="setState"){const M=window.__g7SequenceLocalSync;if(M&&M!==f){f=M,window.__g7SequenceLocalSync=void 0,z.log("[handleSequence] currentState synchronized from __g7SequenceLocalSync after custom handler:",_.handler);const T=n.data?._computedDefinitions;if(T&&Object.keys(T).length>0){const D={},j={...n.data,_local:f,_computed:D,$computed:D,_isolated:g};for(const[H,P]of Object.entries(T))if(typeof P=="string"){const X=P.trim();if(X.startsWith("{{")&&X.endsWith("}}"))try{const pe=X.slice(2,-2).trim();D[H]=this.bindingEngine.evaluateExpression(pe,j,{skipCache:!0})}catch{D[H]=m[H]}}m=D,z.log("[handleSequence] _computed recalculated after custom handler:",m)}}}l&&i?.isEnabled()&&i.captureSequenceActionAfter?.(l,S,v(),Date.now()-x,O.data)}catch(O){throw l&&i?.isEnabled()&&(i.captureSequenceActionAfter?.(l,S,v(),Date.now()-x,void 0,O),i.endSequenceExecution?.(l,O)),z.error(`sequence handler: action[${S}] failed:`,O),O}}return window.__g7SequenceLocalSync=void 0,l&&i?.isEnabled()&&i.endSequenceExecution?.(l),u}async handleParallel(e,n){const r=e.actions||e.params?.actions;if(!r||!Array.isArray(r)||r.length===0)return z.warn("parallel handler requires non-empty actions array"),[];z.log(`parallel handler: executing ${r.length} actions in parallel`);const i=n.isolatedContext?{...n.isolatedContext,state:{...n.isolatedContext.state}}:null,l=r.map((f,g)=>{const m={...n,isolatedContext:i};return this.executeAction(f,m).catch(b=>{throw z.error(`parallel handler: action[${g}] failed:`,b),b})}),u=await Promise.allSettled(l),d=u.filter(f=>f.status==="rejected").length;return d>0&&z.warn(`parallel handler: ${d}/${r.length} actions failed`),u}async handleLoadScript(e,n,r){const{src:i,id:l,async:u=!0,defer:d=!1}=e;if(!i)throw new Ut('loadScript handler requires "src" parameter',n);const f=l||`script_${i.replace(/[^a-zA-Z0-9]/g,"_")}`;return gs.loadedScripts.has(f)?(z.log(`loadScript: script already loaded, skipping: ${f}`),n.onLoad&&await this.executeAction(n.onLoad,r),!0):document.getElementById(f)?(z.log(`loadScript: script element already exists: ${f}`),gs.loadedScripts.add(f),n.onLoad&&await this.executeAction(n.onLoad,r),!0):(z.log(`loadScript: loading script: ${i}`),new Promise((m,b)=>{const v=document.createElement("script");v.id=f,v.src=i,v.async=u,v.defer=d,v.onload=async()=>{if(z.log(`loadScript: script loaded successfully: ${f}`),gs.loadedScripts.add(f),n.onLoad)try{await this.executeAction(n.onLoad,r)}catch(S){z.error("loadScript: onLoad action failed:",S)}m(!0)},v.onerror=S=>{z.error(`loadScript: failed to load script: ${i}`,S),b(new Ut(`Failed to load script: ${i}`,n))},document.head.appendChild(v)}))}async handleCallExternal(e,n,r){const i=e.constructor,l=e.args||{},u=e.method,d=e.methodArgs||[],f=e.callbackEvent,g=e.embedTarget,m=e.callbackSetState,b=e.callbackAction;if(!i)throw new Ut('callExternal handler requires "constructor" parameter',n);const v=this.getNestedProperty(window,i);if(!v||typeof v!="function")throw new Ut(`Constructor not found or not a function: ${i}. Make sure the script is loaded first using loadScript handler.`,n);z.log(`callExternal: calling constructor ${i}`);const S={...l};for(const[x,k]of Object.entries(l))k===!0&&(S[x]=O=>{if(z.log(`callExternal: callback triggered for ${x}`,O),f&&typeof window<"u"&&window.G7Core?.componentEvent&&window.G7Core.componentEvent.emit(f,O),m&&r.setState){const M=j=>{const H={};for(const[P,X]of Object.entries(j))typeof X=="string"?H[P]=this.getNestedProperty(O,X):typeof X=="object"&&X!==null&&(H[P]=M(X));return H},T=M(m);z.log("callExternal: callbackSetState mapping result",T);const D=this.deepMergeWithState(T,r.state||{});z.log("callExternal: merged with existing state",D),r.setState(D)}else f&&r.setState&&r.setState({[`${f.replace(/:/g,"_")}_result`]:O});if(b){const M={...r,data:{...r.data,$event:O}},T=Array.isArray(b)?b:[b];for(const D of T)try{this.executeAction(D,M)}catch(j){z.error("callExternal: callbackAction failed:",j)}}});const _=new v(S);if(u&&typeof _[u]=="function"){if(z.log(`callExternal: calling method ${u}`),u==="embed"&&g){const x=document.querySelector(g);if(x)return _[u](x,...d);throw new Ut(`Embed target element not found: ${g}`,n)}return _[u](...d)}return _}async handleCallExternalEmbed(e,n,r){const i=e.constructor,l=e.args||{},u=e.callbackSetState,d=e.callbackEvent,f=e.layerClassName,g=e.callbackAction;if(!i)throw new Ut('callExternalEmbed handler requires "constructor" parameter',n);const m=this.getNestedProperty(window,i);if(!m||typeof m!="function")throw new Ut(`Constructor not found or not a function: ${i}. Make sure the script is loaded first.`,n);z.log(`callExternalEmbed: creating layer for ${i}`);const{layer:b,closeLayer:v}=this.createEmbedLayer(f),S={...l};for(const[x,k]of Object.entries(l))k===!0&&(S[x]=O=>{if(z.log(`callExternalEmbed: callback triggered for ${x}`,O),v(),d&&typeof window<"u"&&window.G7Core?.componentEvent&&window.G7Core.componentEvent.emit(d,O),u&&r.setState){const M=j=>{const H={};for(const[P,X]of Object.entries(j))typeof X=="string"?H[P]=this.getNestedProperty(O,X):typeof X=="object"&&X!==null&&(H[P]=M(X));return H},T=M(u);z.log("callExternalEmbed: callbackSetState mapping result",T);const D=this.deepMergeWithState(T,r.state||{});z.log("callExternalEmbed: merged with existing state",D),r.setState(D)}if(g){const M={...r,data:{...r.data,$event:O}},T=Array.isArray(g)?g:[g];for(const D of T)try{this.executeAction(D,M)}catch(j){z.error("callExternalEmbed: callbackAction failed:",j)}}});const _=new m(S);if(typeof _.embed=="function")_.embed(b),z.log("callExternalEmbed: embedded in layer");else throw v(),new Ut(`Constructor ${i} does not have embed method`,n);return _}isImeComposing(e){return e?.isComposing===!0||e?.keyCode===229}createEmbedLayer(e){const n=document.createElement("div");n.id="g7-embed-overlay",n.style.cssText=` position: fixed; inset: 0; background-color: rgba(0, 0, 0, 0.5); @@ -47,20 +47,20 @@ Error generating stack: `+c.message+` justify-content: center; color: #666; transition: background-color 0.2s; - `,i.onmouseenter=()=>{i.style.backgroundColor="rgba(0, 0, 0, 0.2)"},i.onmouseleave=()=>{i.style.backgroundColor="rgba(0, 0, 0, 0.1)"};const l=()=>{a.parentNode&&a.parentNode.removeChild(a)};i.onclick=l;const u=d=>{this.isImeComposing(d)||d.key==="Escape"&&(l(),document.removeEventListener("keydown",u))};return document.addEventListener("keydown",u),a.onclick=d=>{d.target===a&&l()},r.appendChild(i),a.appendChild(r),document.body.appendChild(a),{overlay:a,layer:r,closeLayer:l}}getNestedProperty(e,a){return a.split(".").reduce((r,i)=>r&&r[i]!==void 0?r[i]:void 0,e)}async handleSaveToLocalStorage(e,a){const{key:r,value:i}=e;if(!r)return H.error("saveToLocalStorage: key parameter is required"),!1;try{const l=typeof i=="string"?i:JSON.stringify(i);return localStorage.setItem(r,l),H.log(`saveToLocalStorage: saved ${r}`,i),!0}catch(l){return H.error("saveToLocalStorage: failed to save",{key:r,error:l}),!1}}async handleLoadFromLocalStorage(e,a){const{key:r,target:i,stateKey:l,defaultValue:u}=e;if(!r)return H.error("loadFromLocalStorage: key parameter is required"),u;try{const d=localStorage.getItem(r);if(d===null)return H.log(`loadFromLocalStorage: no value found for ${r}, using default`),l&&a.setState&&a.setState({[l]:u}),u;let f;try{f=JSON.parse(d)}catch{f=d}return H.log(`loadFromLocalStorage: loaded ${r}`,f),l&&a.setState&&a.setState({[l]:f}),f}catch(d){return H.error("loadFromLocalStorage: failed to load",{key:r,error:d}),u}}async handleCustomAction(e,a){const r=this.customHandlers.get(e.handler);if(!r){if(this.previewMode){H.warn(`[Preview] Unknown action handler "${e.handler}" — skipped (preview mode)`);return}const i=new It(`Unknown action handler: ${e.handler}`,e);throw i.unknownHandler=!0,i}return await r(e,a)}resolveParams(e,a){if(!e)return{};const r={};for(const[i,l]of Object.entries(e))i.includes("{{")&&H.warn(`[resolveParams] setState params의 키에 표현식이 포함되어 있습니다: "${i}". 키는 해석되지 않습니다. 배열 항목 수정은 .map()/.filter() 패턴을 사용하세요.`),typeof l=="string"&&l.includes("{{")?r[i]=this.evaluateExpression(l,a):typeof l=="string"?r[i]=l:Array.isArray(l)?r[i]=l.map(u=>typeof u=="string"&&u.includes("{{")?this.evaluateExpression(u,a):u):typeof l=="object"&&l!==null&&!Array.isArray(l)&&Object.getPrototypeOf(l)!==Object.prototype&&Object.getPrototypeOf(l)!==null?r[i]=l:typeof l=="object"&&l!==null?r[i]=this.resolveParams(l,a):r[i]=l;return r}resolveValue(e,a){return a?this.bindingEngine.resolveBindings(e,a,{skipCache:!0}):e}evaluateExpressions(e,a){let r={};for(const[i,l]of Object.entries(e))if(i==="..."){let u=l;typeof l=="string"&&l.includes("{{")&&(u=this.evaluateExpression(l,a)),u&&typeof u=="object"&&!Array.isArray(u)&&(r={...r,...u})}else typeof l=="string"&&l.includes("{{")?r[i]=this.evaluateExpression(l,a):typeof l=="object"&&l!==null&&!Array.isArray(l)?r[i]=this.evaluateExpressions(l,a):r[i]=l;return r}evaluateExpressionsIfNeeded(e,a){const r={};for(const[i,l]of Object.entries(e))typeof l=="string"&&l.includes("{{")?r[i]=this.evaluateExpression(l,a):r[i]=l;return r}evaluateExpression(e,a){if(!a)return e;const r=e.match(/^\{\{(.+)\}\}$/);if(!(r&&!r[1].includes("}}")&&!r[1].includes("{{"))){let d=a;if(e.includes("_global")){const g=window.G7Core?.state?.get()?._global;g&&(d={...a,_global:g})}if(e.includes("_computed")||e.includes("$computed")){const g=window.__g7ActionContext?.computedRef?.current;g&&Object.keys(g).length>0&&(d={...d,_computed:g,$computed:g})}return this.bindingEngine.resolveBindings(e,d,{skipCache:!0})}let l=r[1].trim();l=l.replace(/\$args\.(\d+)/g,"$args[$1]");let u=a;if(l.includes("_global")){const f=window.G7Core?.state?.get()?._global;f&&(u={...a,_global:f})}if(l.includes("_computed")||l.includes("$computed")){const f=window.__g7ActionContext?.computedRef?.current;f&&Object.keys(f).length>0&&(u={...u,_computed:f,$computed:f})}l.includes("_global.modules")&&(H.log("[evaluateExpression] expression:",l),H.log("[evaluateExpression] dataContext._global:",u._global),H.log("[evaluateExpression] dataContext._global?.modules:",u._global?.modules));try{const d=this.bindingEngine.evaluateExpression(l,u);return l.includes("_global.modules")&&H.log("[evaluateExpression] result:",d),typeof d=="string"&&d.startsWith("$t:")&&this.translationEngine&&this.translationContext?this.translationEngine.resolveTranslations(d,this.translationContext,a):d}catch(d){return H.error("Expression evaluation failed:",e,d),e}}setDefaultContext(e){this.defaultContext={...this.defaultContext,...e}}setGlobalStateUpdater(e){this.globalStateUpdater=e}getGlobalStateUpdater(){return this.globalStateUpdater}async dispatchAction(e,a){const r={...this.defaultContext,...a,data:{...this.defaultContext.data,...a?.data}};if(e.confirm){let i=this.resolveValue(e.confirm,r.data);if(this.translationEngine&&this.translationContext&&i.startsWith("$t:")&&(i=this.translationEngine.resolveTranslations(i,this.translationContext,r.data)),!confirm(i))return{success:!1}}try{return await this.executeAction(e,r)}catch(i){if(H.error("dispatchAction failed:",i),e.onError){const l=i instanceof It&&i.originalError?{message:i.originalError.message,response:i.originalError.response}:{message:i instanceof Error?i.message:String(i)},u={...r,data:{...r.data,error:l}},d=Array.isArray(e.onError)?e.onError:[e.onError];for(const f of d)await this.executeAction(f,u)}return{success:!1,error:i instanceof Error?i:new Error(String(i))}}}registerHandler(e,a,r){this.customHandlers.set(e,a);const i=Un();i?.isEnabled()&&i.trackHandlerRegistration(e,r?.category??"custom",r?.description,r?.source)}unregisterHandler(e){this.customHandlers.delete(e);const a=Un();a?.isEnabled()&&a.trackHandlerUnregistration(e)}getRegisteredHandlers(){return Array.from(this.customHandlers.keys())}getHandler(e){return this.customHandlers.get(e)}normalizeDebounceConfig(e){return typeof e=="number"?{delay:e,leading:!1,trailing:!0}:{delay:e.delay,leading:e.leading??!1,trailing:e.trailing??!0}}extractEventData(e){const a=e.target;if(a&&!("tagName"in a)){const l={type:e.type??"custom",target:{value:a.value,name:a.name??""}};return e._changedKeys&&(l._changedKeys=e._changedKeys),l}const i=a?{value:a.value,name:a.name??"",checked:a.checked??!1,type:a.type??"",tagName:a.tagName}:{};if(e.type==="scroll"&&a){const l=a;i.scrollHeight=l.scrollHeight??0,i.scrollTop=l.scrollTop??0,i.clientHeight=l.clientHeight??0,i.scrollLeft=l.scrollLeft??0,i.clientWidth=l.clientWidth??0,i.scrollWidth=l.scrollWidth??0}return{type:e.type,target:a?i:null}}executeDebouncedAction(e,a,r,i,l){const u={...r,$event:a,$args:l},d={type:a.type,target:a.target,preventDefault:()=>{},stopPropagation:()=>{}};this.createHandler(e,u,i)(d)}handleDebouncedAction(e,a,r,i,l,u){const d=this.normalizeDebounceConfig(e.debounce),f=l||`default-${e.handler}-${Date.now()}`,g=this.extractEventData(a),m=g._changedKeys;if(m&&Array.isArray(m)&&g?.target?.value&&typeof g.target.value=="object"&&!Array.isArray(g.target.value)){const E=this.debounceAccumulatedValues.get(f);if(E){const A={...E};for(const T of m)A[T]=g.target.value[T];g.target.value=A}this.debounceAccumulatedValues.set(f,g.target.value)}const b=this.debounceTimers.get(f);b&&(clearTimeout(b),this.debounceTimers.delete(f));const v=Un();v?.isEnabled()&&v.trackAction({handler:typeof e.handler=="string"?e.handler:String(e.handler),type:e.type,status:"pending",params:e.params,debounce:{delay:d.delay,status:"pending",scheduledAt:Date.now()}});const S=!this.debounceTimers.has(f+"_leading");if(d.leading&&S&&(this.debounceTimers.set(f+"_leading",setTimeout(()=>{},0)),this.executeDebouncedAction(e,g,r,i,u),v?.isEnabled()&&v.trackAction({handler:typeof e.handler=="string"?e.handler:String(e.handler),type:e.type,status:"success",params:e.params,debounce:{delay:d.delay,status:"executed",executedAt:Date.now(),mode:"leading"}})),d.trailing){const E=()=>{this.executeDebouncedAction(e,g,r,i,u),v?.isEnabled()&&v.trackAction({handler:typeof e.handler=="string"?e.handler:String(e.handler),type:e.type,status:"success",params:e.params,debounce:{delay:d.delay,status:"executed",executedAt:Date.now(),mode:"trailing"}})},A=setTimeout(()=>{this.debounceTimers.delete(f),this.debounceTimers.delete(f+"_leading"),this.pendingDebounceFlushers.delete(f),this.debounceAccumulatedValues.delete(f),E()},d.delay);this.debounceTimers.set(f,A),this.pendingDebounceFlushers.set(f,E)}}clearDebounceTimers(e){if(e)for(const[a,r]of this.debounceTimers)a.startsWith(e+"-")&&(clearTimeout(r),this.debounceTimers.delete(a),this.pendingDebounceFlushers.delete(a),this.debounceAccumulatedValues.delete(a));else{for(const a of this.debounceTimers.values())clearTimeout(a);this.debounceTimers.clear(),this.pendingDebounceFlushers.clear(),this.debounceAccumulatedValues.clear()}}debouncedCall(e,a,r){const i=this.debounceTimers.get(e);i&&(clearTimeout(i),this.debounceTimers.delete(e));const l=setTimeout(()=>{this.debounceTimers.delete(e),this.pendingDebounceFlushers.delete(e),r()},a);this.debounceTimers.set(e,l),this.pendingDebounceFlushers.set(e,r)}flushPendingDebounceTimers(){if(this.pendingDebounceFlushers.size===0)return;const e=new Map(this.pendingDebounceFlushers);for(const[a,r]of e){const i=this.debounceTimers.get(a);i&&(clearTimeout(i),this.debounceTimers.delete(a)),this.debounceTimers.delete(a+"_leading"),this.pendingDebounceFlushers.delete(a),r()}this.globalStateUpdater&&this.globalStateUpdater({})}bindActionsToProps(e,a,r){const i={...e};if(e.actions&&Array.isArray(e.actions)){const l=new Map;for(const m of e.actions){const b=this.resolveActionRef(m),v=b.event||this.getEventHandlerName(b.type);l.has(v)||l.set(v,[]),l.get(v).push(b)}const u=e.name||e.id||"unknown",d=l.has("onDrop"),f=l.has("onDragOver"),g=l.has("onDragEnter");d&&!f&&(i.onDragOver=m=>{m.preventDefault()}),d&&!g&&(i.onDragEnter=m=>{m.preventDefault()});for(const[m,b]of l)i[m]=(...v)=>{for(const S of b){const E=v[0],A=E&&typeof E=="object"&&"preventDefault"in E;if(A&&(m==="onDragOver"||m==="onDrop")&&E.preventDefault(),A&&S.key&&"key"in E){if(this.isImeComposing(E)){H.log("Key filter skipped (IME composing):",S.key);continue}if(E.key!==S.key){H.log("Key filter not matched:",S.key,"actual:",E.key);continue}H.log("Key filter matched:",S.key)}if(S.debounce){const T=`${u}-${S.handler}-${m}`,L=E&&typeof E=="object"&&!("preventDefault"in E)&&"target"in E&&E.target!==null;let M;if(A)M=E;else if(L){const D={type:"custom",target:E.target,preventDefault:()=>{},stopPropagation:()=>{}};E._changedKeys&&(D._changedKeys=E._changedKeys),M=D}else M=new Event("custom");const R=S.event?{...a,$args:v}:a;this.handleDebouncedAction(S,M,R,r,T,v)}else if(this.flushPendingDebounceTimers(),S.event){const T={...a,$args:v},L=A?E:new Event("custom");this.createHandler(S,T,r)(L)}else if(A)this.createHandler(S,a,r)(E);else if(E&&typeof E=="object"&&!("preventDefault"in E)&&"target"in E&&E.target!==null){const L={type:"custom",target:E.target,preventDefault:()=>{},stopPropagation:()=>{}};this.createHandler(S,a,r)(L)}}}}return i}getEventHandlerName(e){return{click:"onClick",change:"onChange",input:"onInput",submit:"onSubmit",focus:"onFocus",blur:"onBlur",keydown:"onKeyDown",keyup:"onKeyUp",keypress:"onKeyPress",mousedown:"onMouseDown",mouseup:"onMouseUp",mouseenter:"onMouseEnter",mouseleave:"onMouseLeave",scroll:"onScroll",dragstart:"onDragStart",drag:"onDrag",dragend:"onDragEnd",dragenter:"onDragEnter",dragover:"onDragOver",dragleave:"onDragLeave",drop:"onDrop"}[e]||`on${e.charAt(0).toUpperCase()}${e.slice(1)}`}sanitizeForDevTools(e,a=5){const r=new WeakSet,i=(l,u)=>{if(l==null||typeof l=="string"||typeof l=="number"||typeof l=="boolean")return l;if(u>a)return"[Max Depth Exceeded]";if(typeof l=="function")return`[Function: ${l.name||"anonymous"}]`;if(l instanceof Element)return`[Element: ${l.tagName}${l.className?"."+l.className.split(" ").join("."):""}]`;if(l instanceof Event)return`[Event: ${l.type}]`;if(Array.isArray(l)){if(r.has(l))return"[Circular Array]";r.add(l);const d=l.slice(0,10).map(f=>i(f,u+1));return l.length>10&&d.push(`... ${l.length-10} more items`),d}if(typeof l=="object"){if(r.has(l))return"[Circular Reference]";r.add(l);const d={},f=Object.keys(l),g=f.slice(0,20);for(const m of g)try{d[m]=i(l[m],u+1)}catch{d[m]="[Error accessing property]"}return f.length>20&&(d["..."]=`${f.length-20} more properties`),d}return String(l)};return i(e,0)}};$(us,"loadedScripts",new Set);let lo=us,Wl=null;function Zp(o){return Wl||(Wl=new lo(o)),Wl}function eC(o){Wl=o}const em=ct("TransitionManager");class tC{constructor(){$(this,"isPending",!1);$(this,"subscribers",new Set)}setPending(e){this.isPending!==e&&(em.log("setPending:",{from:this.isPending,to:e,stack:new Error().stack}),this.isPending=e,this.notifySubscribers())}getIsPending(){return this.isPending}subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}notifySubscribers(){em.log("notifySubscribers:",{isPending:this.isPending,subscriberCount:this.subscribers.size}),this.subscribers.forEach(e=>{e(this.isPending)})}clearSubscribers(){this.subscribers.clear()}}const Na=new tC,Yl=ct("TransitionContext"),tm=N.createContext({isTransitioning:!1}),Od=({children:o})=>{const[e,a]=N.useState(()=>{const i=Na.getIsPending();return Yl.log("Initial state:",i),i});N.useEffect(()=>{Yl.log("Subscribing to TransitionManager");const i=Na.subscribe(l=>{Yl.log("Received isPending update:",l),a(l)});return()=>{Yl.log("Unsubscribing from TransitionManager"),i()}},[]);const r=N.useMemo(()=>({isTransitioning:e}),[e]);return ut.jsx(tm.Provider,{value:r,children:o})},nm=()=>N.useContext(tm),Xl="__g7LocalInitTracking";function Ld(){const o=globalThis;return o[Xl]||(o[Xl]={hash:"",timestamp:void 0,consumed:void 0}),o[Xl]}function nC(){const o=globalThis;o[Xl]={hash:"",timestamp:void 0,consumed:void 0}}function aC(o){Ld().consumed=o}function rC(o){return Ld().consumed===o}function iC(o,e){return typeof o=="number"&&typeof e=="number"?Math.max(o,e):e??o}function sC(o,e){if(e===void 0)return o;if(!(o!==null&&typeof o=="object"&&e!==null&&typeof e=="object"&&!rC(o)))return e;const{_forceLocalInit:r,...i}=o,{_forceLocalInit:l,...u}=e,d={...i,...u},f=iC(r,l);return f!==void 0&&(d._forceLocalInit=f),d}function oC(o){return o<768?"mobile":o<1024?"tablet":"desktop"}function am(o){const e=oC(o);return{width:o,isMobile:e==="mobile",isTablet:e==="tablet",isDesktop:e==="desktop",matchedPreset:e}}const Md=N.createContext(am(1024)),Jl=({children:o,overrideWidth:e})=>{const[a,r]=N.useState(()=>ui.getWidth());N.useEffect(()=>{const u=ui.subscribe(d=>{r(d)});return()=>{u()}},[]);const i=e??a,l=N.useMemo(()=>am(i),[i]);return ut.jsx(Md.Provider,{value:l,children:o})},$d=()=>N.useContext(Md);window.G7Core?.createLogger?.("Core:State");function lC(o,e,a,r){const{syncOnControlledChange:i=!0,isEqual:l}=r??{},u=o!==void 0;N.useRef(u);const[d,f]=N.useState(o!==void 0?o:e),g=d,m=N.useRef(o),b=N.useRef(!1);N.useEffect(()=>{if(b.current){m.current=o;return}i&&u&&o!==m.current&&(l?!l(d,o):d!==o)&&f(o),m.current=o},[o,u,i,l,d]);const v=N.useCallback(S=>{const E=typeof S=="function"?S(g):S;(l?l(g,E):g===E)||(b.current=!0,f(E),a?.(E),requestAnimationFrame(()=>{b.current=!1}))},[g,u,a,l]);return[g,v]}function cC(o,e){return o===e?!0:o.length!==e.length?!1:o.every((a,r)=>a===e[r])}function rm(o,e){if(o===e)return!0;const a=Object.keys(o),r=Object.keys(e);return a.length!==r.length?!1:a.every(i=>o[i]===e[i])}const im=N.createContext({}),uC=({children:o,value:e})=>ut.jsx(im.Provider,{value:e,children:o}),dC=()=>N.useContext(im),fC=(o,e)=>{if(!o)return;const a=e.split(".");let r=o;for(const i of a){if(r==null)return;r=r[i]}return r},hC=(o,e,a)=>{const r=e.split(".");if(r.length===1)return{...o,[r[0]]:a};const i={...o};let l=i;for(let u=0;u{ns.warn("IsolatedStateContext not available: setState called outside IsolatedStateProvider")},getState:()=>{},mergeState:()=>{ns.warn("IsolatedStateContext not available: mergeState called outside IsolatedStateProvider")},stateRef:{current:{}},scopeId:""},sm=N.createContext(gC);let pC=0;function mC(){return`isolated-${++pC}-${Date.now().toString(36)}`}function om(o,e){if(e==null)return o;if(typeof e!="object"||Array.isArray(e))return e;const a={...o};for(const r of Object.keys(e)){const i=e[r],l=o?.[r];i!==null&&typeof i=="object"&&!Array.isArray(i)&&l!==null&&typeof l=="object"&&!Array.isArray(l)?a[r]=om(l,i):a[r]=i}return a}function yC(o,e){return e?e.split(".").reduce((a,r)=>a?.[r],o):o}function bC(o,e,a){const r=e.split("."),i={...o};let l=i;for(let u=0;u{const i=N.useRef(e||mC()).current,[l,u]=N.useState(o),d=N.useRef(l);d.current=l;const f=N.useCallback(S=>yC(d.current,S),[]),g=N.useCallback((S,E)=>{u(A=>{const T=bC(A,S,E);return ns.log(`[${i}] setState: ${S} =`,E),T})},[i]),m=N.useCallback((S,E="deep")=>{u(A=>{let T;return E==="replace"?T=S:E==="shallow"?T={...A,...S}:T=om(A,S),ns.log(`[${i}] mergeState (${E}):`,S),T})},[i]),b=N.useMemo(()=>({state:l,setState:g,getState:f,mergeState:m,stateRef:d,scopeId:i}),[l,g,f,m,i]),v=N.useMemo(()=>({state:d.current,setState:g,getState:f,mergeState:m}),[g,f,m]);return N.useEffect(()=>{const S=window.G7Core,E=window.__g7IsolatedStates||{};return window.__g7IsolatedStates||(window.__g7IsolatedStates=E),E[i]=v,S&&(S._isolatedStates||(S._isolatedStates={}),S._isolatedStates[i]=l),S?.devTools?.isEnabled?.()&&S.devTools.emit?.("isolated:created",{id:i,state:l}),ns.log(`[${i}] IsolatedStateProvider mounted with initial state:`,l),()=>{delete E[i],S?._isolatedStates&&delete S._isolatedStates[i],S?.devTools?.isEnabled?.()&&S.devTools.emit?.("isolated:destroyed",{id:i}),ns.log(`[${i}] IsolatedStateProvider unmounted`)}},[i,v]),N.useEffect(()=>{const S=window.G7Core,E=window.__g7IsolatedStates;E?.[i]&&(E[i].state=l),S?._isolatedStates&&(S._isolatedStates[i]=l),S?.devTools?.isEnabled?.()&&S.devTools.emit?.("isolated:updated",{id:i,state:l})},[l,i]),ut.jsx(sm.Provider,{value:b,children:a})},SC=()=>{const o=N.useContext(sm);return o.scopeId?o:null};var Ar=jg();function wC(){for(var o=arguments.length,e=new Array(o),a=0;ar=>{e.forEach(i=>i(r))},e)}const Ql=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function as(o){const e=Object.prototype.toString.call(o);return e==="[object Window]"||e==="[object global]"}function Nd(o){return"nodeType"in o}function Tn(o){var e,a;return o?as(o)?o:Nd(o)&&(e=(a=o.ownerDocument)==null?void 0:a.defaultView)!=null?e:window:window}function Id(o){const{Document:e}=Tn(o);return o instanceof e}function co(o){return as(o)?!1:o instanceof Tn(o).HTMLElement}function lm(o){return o instanceof Tn(o).SVGElement}function rs(o){return o?as(o)?o.document:Nd(o)?Id(o)?o:co(o)||lm(o)?o.ownerDocument:document:document:document}const Ia=Ql?N.useLayoutEffect:N.useEffect;function Hd(o){const e=N.useRef(o);return Ia(()=>{e.current=o}),N.useCallback(function(){for(var a=arguments.length,r=new Array(a),i=0;i{o.current=setInterval(r,i)},[]),a=N.useCallback(()=>{o.current!==null&&(clearInterval(o.current),o.current=null)},[]);return[e,a]}function uo(o,e){e===void 0&&(e=[o]);const a=N.useRef(o);return Ia(()=>{a.current!==o&&(a.current=o)},e),a}function fo(o,e){const a=N.useRef();return N.useMemo(()=>{const r=o(a.current);return a.current=r,r},[...e])}function Zl(o){const e=Hd(o),a=N.useRef(null),r=N.useCallback(i=>{i!==a.current&&e?.(i,a.current),a.current=i},[]);return[a,r]}function zd(o){const e=N.useRef();return N.useEffect(()=>{e.current=o},[o]),e.current}let jd={};function ho(o,e){return N.useMemo(()=>{if(e)return e;const a=jd[o]==null?0:jd[o]+1;return jd[o]=a,o+"-"+a},[o,e])}function cm(o){return function(e){for(var a=arguments.length,r=new Array(a>1?a-1:0),i=1;i{const d=Object.entries(u);for(const[f,g]of d){const m=l[f];m!=null&&(l[f]=m+o*g)}return l},{...e})}}const is=cm(1),go=cm(-1);function EC(o){return"clientX"in o&&"clientY"in o}function Ud(o){if(!o)return!1;const{KeyboardEvent:e}=Tn(o.target);return e&&o instanceof e}function _C(o){if(!o)return!1;const{TouchEvent:e}=Tn(o.target);return e&&o instanceof e}function Bd(o){if(_C(o)){if(o.touches&&o.touches.length){const{clientX:e,clientY:a}=o.touches[0];return{x:e,y:a}}else if(o.changedTouches&&o.changedTouches.length){const{clientX:e,clientY:a}=o.changedTouches[0];return{x:e,y:a}}}return EC(o)?{x:o.clientX,y:o.clientY}:null}const po=Object.freeze({Translate:{toString(o){if(!o)return;const{x:e,y:a}=o;return"translate3d("+(e?Math.round(e):0)+"px, "+(a?Math.round(a):0)+"px, 0)"}},Scale:{toString(o){if(!o)return;const{scaleX:e,scaleY:a}=o;return"scaleX("+e+") scaleY("+a+")"}},Transform:{toString(o){if(o)return[po.Translate.toString(o),po.Scale.toString(o)].join(" ")}},Transition:{toString(o){let{property:e,duration:a,easing:r}=o;return e+" "+a+"ms "+r}}}),um="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function AC(o){return o.matches(um)?o:o.querySelector(um)}const xC={display:"none"};function TC(o){let{id:e,value:a}=o;return Ye.createElement("div",{id:e,style:xC},a)}function RC(o){let{id:e,announcement:a,ariaLiveType:r="assertive"}=o;const i={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return Ye.createElement("div",{id:e,style:i,role:"status","aria-live":r,"aria-atomic":!0},a)}function kC(){const[o,e]=N.useState("");return{announce:N.useCallback(r=>{r!=null&&e(r)},[]),announcement:o}}const dm=N.createContext(null);function DC(o){const e=N.useContext(dm);N.useEffect(()=>{if(!e)throw new Error("useDndMonitor must be used within a children of ");return e(o)},[o,e])}function OC(){const[o]=N.useState(()=>new Set),e=N.useCallback(r=>(o.add(r),()=>o.delete(r)),[o]);return[N.useCallback(r=>{let{type:i,event:l}=r;o.forEach(u=>{var d;return(d=u[i])==null?void 0:d.call(u,l)})},[o]),e]}const LC={draggable:` + `,i.onmouseenter=()=>{i.style.backgroundColor="rgba(0, 0, 0, 0.2)"},i.onmouseleave=()=>{i.style.backgroundColor="rgba(0, 0, 0, 0.1)"};const l=()=>{n.parentNode&&n.parentNode.removeChild(n)};i.onclick=l;const u=d=>{this.isImeComposing(d)||d.key==="Escape"&&(l(),document.removeEventListener("keydown",u))};return document.addEventListener("keydown",u),n.onclick=d=>{d.target===n&&l()},r.appendChild(i),n.appendChild(r),document.body.appendChild(n),{overlay:n,layer:r,closeLayer:l}}getNestedProperty(e,n){return n.split(".").reduce((r,i)=>r&&r[i]!==void 0?r[i]:void 0,e)}async handleSaveToLocalStorage(e,n){const{key:r,value:i}=e;if(!r)return z.error("saveToLocalStorage: key parameter is required"),!1;try{const l=typeof i=="string"?i:JSON.stringify(i);return localStorage.setItem(r,l),z.log(`saveToLocalStorage: saved ${r}`,i),!0}catch(l){return z.error("saveToLocalStorage: failed to save",{key:r,error:l}),!1}}async handleLoadFromLocalStorage(e,n){const{key:r,target:i,stateKey:l,defaultValue:u}=e;if(!r)return z.error("loadFromLocalStorage: key parameter is required"),u;try{const d=localStorage.getItem(r);if(d===null)return z.log(`loadFromLocalStorage: no value found for ${r}, using default`),l&&n.setState&&n.setState({[l]:u}),u;let f;try{f=JSON.parse(d)}catch{f=d}return z.log(`loadFromLocalStorage: loaded ${r}`,f),l&&n.setState&&n.setState({[l]:f}),f}catch(d){return z.error("loadFromLocalStorage: failed to load",{key:r,error:d}),u}}async handleCustomAction(e,n){const r=this.customHandlers.get(e.handler);if(!r){if(this.previewMode){z.warn(`[Preview] Unknown action handler "${e.handler}" — skipped (preview mode)`);return}const i=new Ut(`Unknown action handler: ${e.handler}`,e);throw i.unknownHandler=!0,i}return await r(e,n)}resolveParams(e,n){if(!e)return{};const r={};for(const[i,l]of Object.entries(e))i.includes("{{")&&z.warn(`[resolveParams] setState params의 키에 표현식이 포함되어 있습니다: "${i}". 키는 해석되지 않습니다. 배열 항목 수정은 .map()/.filter() 패턴을 사용하세요.`),typeof l=="string"&&l.includes("{{")?r[i]=this.evaluateExpression(l,n):typeof l=="string"?r[i]=l:Array.isArray(l)?r[i]=l.map(u=>typeof u=="string"&&u.includes("{{")?this.evaluateExpression(u,n):u):typeof l=="object"&&l!==null&&!Array.isArray(l)&&Object.getPrototypeOf(l)!==Object.prototype&&Object.getPrototypeOf(l)!==null?r[i]=l:typeof l=="object"&&l!==null?r[i]=this.resolveParams(l,n):r[i]=l;return r}resolveValue(e,n){return n?this.bindingEngine.resolveBindings(e,n,{skipCache:!0}):e}evaluateExpressions(e,n){let r={};for(const[i,l]of Object.entries(e))if(i==="..."){let u=l;typeof l=="string"&&l.includes("{{")&&(u=this.evaluateExpression(l,n)),u&&typeof u=="object"&&!Array.isArray(u)&&(r={...r,...u})}else typeof l=="string"&&l.includes("{{")?r[i]=this.evaluateExpression(l,n):typeof l=="object"&&l!==null&&!Array.isArray(l)?r[i]=this.evaluateExpressions(l,n):r[i]=l;return r}evaluateExpressionsIfNeeded(e,n){const r={};for(const[i,l]of Object.entries(e))typeof l=="string"&&l.includes("{{")?r[i]=this.evaluateExpression(l,n):r[i]=l;return r}evaluateExpression(e,n){if(!n)return e;const r=e.match(/^\{\{(.+)\}\}$/);if(!(r&&!r[1].includes("}}")&&!r[1].includes("{{"))){let d=n;if(e.includes("_global")){const g=window.G7Core?.state?.get()?._global;g&&(d={...n,_global:g})}if(e.includes("_computed")||e.includes("$computed")){const g=window.__g7ActionContext?.computedRef?.current;g&&Object.keys(g).length>0&&(d={...d,_computed:g,$computed:g})}return this.bindingEngine.resolveBindings(e,d,{skipCache:!0})}let l=r[1].trim();l=l.replace(/\$args\.(\d+)/g,"$args[$1]");let u=n;if(l.includes("_global")){const f=window.G7Core?.state?.get()?._global;f&&(u={...n,_global:f})}if(l.includes("_computed")||l.includes("$computed")){const f=window.__g7ActionContext?.computedRef?.current;f&&Object.keys(f).length>0&&(u={...u,_computed:f,$computed:f})}l.includes("_global.modules")&&(z.log("[evaluateExpression] expression:",l),z.log("[evaluateExpression] dataContext._global:",u._global),z.log("[evaluateExpression] dataContext._global?.modules:",u._global?.modules));try{const d=this.bindingEngine.evaluateExpression(l,u);return l.includes("_global.modules")&&z.log("[evaluateExpression] result:",d),typeof d=="string"&&d.startsWith("$t:")&&this.translationEngine&&this.translationContext?this.translationEngine.resolveTranslations(d,this.translationContext,n):d}catch(d){return z.error("Expression evaluation failed:",e,d),e}}setDefaultContext(e){this.defaultContext={...this.defaultContext,...e}}setGlobalStateUpdater(e){this.globalStateUpdater=e}getGlobalStateUpdater(){return this.globalStateUpdater}async dispatchAction(e,n){const r={...this.defaultContext,...n,data:{...this.defaultContext.data,...n?.data}};if(e.confirm){let i=this.resolveValue(e.confirm,r.data);if(this.translationEngine&&this.translationContext&&i.startsWith("$t:")&&(i=this.translationEngine.resolveTranslations(i,this.translationContext,r.data)),!confirm(i))return{success:!1}}try{return await this.executeAction(e,r)}catch(i){if(z.error("dispatchAction failed:",i),e.onError){const l=i instanceof Ut&&i.originalError?{message:i.originalError.message,response:i.originalError.response}:{message:i instanceof Error?i.message:String(i)},u={...r,data:{...r.data,error:l}},d=Array.isArray(e.onError)?e.onError:[e.onError];for(const f of d)await this.executeAction(f,u)}return{success:!1,error:i instanceof Error?i:new Error(String(i))}}}registerHandler(e,n,r){this.customHandlers.set(e,n);const i=qn();i?.isEnabled()&&i.trackHandlerRegistration(e,r?.category??"custom",r?.description,r?.source)}unregisterHandler(e){this.customHandlers.delete(e);const n=qn();n?.isEnabled()&&n.trackHandlerUnregistration(e)}getRegisteredHandlers(){return Array.from(this.customHandlers.keys())}getHandler(e){return this.customHandlers.get(e)}normalizeDebounceConfig(e){return typeof e=="number"?{delay:e,leading:!1,trailing:!0}:{delay:e.delay,leading:e.leading??!1,trailing:e.trailing??!0}}extractEventData(e){const n=e.target;if(n&&!("tagName"in n)){const l={type:e.type??"custom",target:{value:n.value,name:n.name??""}};return e._changedKeys&&(l._changedKeys=e._changedKeys),l}const i=n?{value:n.value,name:n.name??"",checked:n.checked??!1,type:n.type??"",tagName:n.tagName}:{};if(e.type==="scroll"&&n){const l=n;i.scrollHeight=l.scrollHeight??0,i.scrollTop=l.scrollTop??0,i.clientHeight=l.clientHeight??0,i.scrollLeft=l.scrollLeft??0,i.clientWidth=l.clientWidth??0,i.scrollWidth=l.scrollWidth??0}return{type:e.type,target:n?i:null}}executeDebouncedAction(e,n,r,i,l){const u={...r,$event:n,$args:l},d={type:n.type,target:n.target,preventDefault:()=>{},stopPropagation:()=>{}};this.createHandler(e,u,i)(d)}handleDebouncedAction(e,n,r,i,l,u){const d=this.normalizeDebounceConfig(e.debounce),f=l||`default-${e.handler}-${Date.now()}`,g=this.extractEventData(n),m=g._changedKeys;if(m&&Array.isArray(m)&&g?.target?.value&&typeof g.target.value=="object"&&!Array.isArray(g.target.value)){const _=this.debounceAccumulatedValues.get(f);if(_){const x={..._};for(const k of m)x[k]=g.target.value[k];g.target.value=x}this.debounceAccumulatedValues.set(f,g.target.value)}const b=this.debounceTimers.get(f);b&&(clearTimeout(b),this.debounceTimers.delete(f));const v=qn();v?.isEnabled()&&v.trackAction({handler:typeof e.handler=="string"?e.handler:String(e.handler),type:e.type,status:"pending",params:e.params,debounce:{delay:d.delay,status:"pending",scheduledAt:Date.now()}});const S=!this.debounceTimers.has(f+"_leading");if(d.leading&&S&&(this.debounceTimers.set(f+"_leading",setTimeout(()=>{},0)),this.executeDebouncedAction(e,g,r,i,u),v?.isEnabled()&&v.trackAction({handler:typeof e.handler=="string"?e.handler:String(e.handler),type:e.type,status:"success",params:e.params,debounce:{delay:d.delay,status:"executed",executedAt:Date.now(),mode:"leading"}})),d.trailing){const _=()=>{this.executeDebouncedAction(e,g,r,i,u),v?.isEnabled()&&v.trackAction({handler:typeof e.handler=="string"?e.handler:String(e.handler),type:e.type,status:"success",params:e.params,debounce:{delay:d.delay,status:"executed",executedAt:Date.now(),mode:"trailing"}})},x=setTimeout(()=>{this.debounceTimers.delete(f),this.debounceTimers.delete(f+"_leading"),this.pendingDebounceFlushers.delete(f),this.debounceAccumulatedValues.delete(f),_()},d.delay);this.debounceTimers.set(f,x),this.pendingDebounceFlushers.set(f,_)}}clearDebounceTimers(e){if(e)for(const[n,r]of this.debounceTimers)n.startsWith(e+"-")&&(clearTimeout(r),this.debounceTimers.delete(n),this.pendingDebounceFlushers.delete(n),this.debounceAccumulatedValues.delete(n));else{for(const n of this.debounceTimers.values())clearTimeout(n);this.debounceTimers.clear(),this.pendingDebounceFlushers.clear(),this.debounceAccumulatedValues.clear()}}debouncedCall(e,n,r){const i=this.debounceTimers.get(e);i&&(clearTimeout(i),this.debounceTimers.delete(e));const l=setTimeout(()=>{this.debounceTimers.delete(e),this.pendingDebounceFlushers.delete(e),r()},n);this.debounceTimers.set(e,l),this.pendingDebounceFlushers.set(e,r)}flushPendingDebounceTimers(){if(this.pendingDebounceFlushers.size===0)return;const e=new Map(this.pendingDebounceFlushers);for(const[n,r]of e){const i=this.debounceTimers.get(n);i&&(clearTimeout(i),this.debounceTimers.delete(n)),this.debounceTimers.delete(n+"_leading"),this.pendingDebounceFlushers.delete(n),r()}this.globalStateUpdater&&this.globalStateUpdater({})}bindActionsToProps(e,n,r){const i={...e};if(e.actions&&Array.isArray(e.actions)){const l=new Map;for(const m of e.actions){const b=this.resolveActionRef(m),v=b.event||this.getEventHandlerName(b.type);l.has(v)||l.set(v,[]),l.get(v).push(b)}const u=e.name||e.id||"unknown",d=l.has("onDrop"),f=l.has("onDragOver"),g=l.has("onDragEnter");d&&!f&&(i.onDragOver=m=>{m.preventDefault()}),d&&!g&&(i.onDragEnter=m=>{m.preventDefault()});for(const[m,b]of l)i[m]=(...v)=>{for(const S of b){const _=v[0],x=_&&typeof _=="object"&&"preventDefault"in _;if(x&&(m==="onDragOver"||m==="onDrop")&&_.preventDefault(),x&&S.key&&"key"in _){if(this.isImeComposing(_)){z.log("Key filter skipped (IME composing):",S.key);continue}if(_.key!==S.key){z.log("Key filter not matched:",S.key,"actual:",_.key);continue}z.log("Key filter matched:",S.key)}if(S.debounce){const k=`${u}-${S.handler}-${m}`,O=_&&typeof _=="object"&&!("preventDefault"in _)&&"target"in _&&_.target!==null;let M;if(x)M=_;else if(O){const D={type:"custom",target:_.target,preventDefault:()=>{},stopPropagation:()=>{}};_._changedKeys&&(D._changedKeys=_._changedKeys),M=D}else M=new Event("custom");const T=S.event?{...n,$args:v}:n;this.handleDebouncedAction(S,M,T,r,k,v)}else if(this.flushPendingDebounceTimers(),S.event){const k={...n,$args:v},O=x?_:new Event("custom");this.createHandler(S,k,r)(O)}else if(x)this.createHandler(S,n,r)(_);else if(_&&typeof _=="object"&&!("preventDefault"in _)&&"target"in _&&_.target!==null){const O={type:"custom",target:_.target,preventDefault:()=>{},stopPropagation:()=>{}};this.createHandler(S,n,r)(O)}}}}return i}getEventHandlerName(e){return{click:"onClick",change:"onChange",input:"onInput",submit:"onSubmit",focus:"onFocus",blur:"onBlur",keydown:"onKeyDown",keyup:"onKeyUp",keypress:"onKeyPress",mousedown:"onMouseDown",mouseup:"onMouseUp",mouseenter:"onMouseEnter",mouseleave:"onMouseLeave",scroll:"onScroll",dragstart:"onDragStart",drag:"onDrag",dragend:"onDragEnd",dragenter:"onDragEnter",dragover:"onDragOver",dragleave:"onDragLeave",drop:"onDrop"}[e]||`on${e.charAt(0).toUpperCase()}${e.slice(1)}`}sanitizeForDevTools(e,n=5){const r=new WeakSet,i=(l,u)=>{if(l==null||typeof l=="string"||typeof l=="number"||typeof l=="boolean")return l;if(u>n)return"[Max Depth Exceeded]";if(typeof l=="function")return`[Function: ${l.name||"anonymous"}]`;if(l instanceof Element)return`[Element: ${l.tagName}${l.className?"."+l.className.split(" ").join("."):""}]`;if(l instanceof Event)return`[Event: ${l.type}]`;if(Array.isArray(l)){if(r.has(l))return"[Circular Array]";r.add(l);const d=l.slice(0,10).map(f=>i(f,u+1));return l.length>10&&d.push(`... ${l.length-10} more items`),d}if(typeof l=="object"){if(r.has(l))return"[Circular Reference]";r.add(l);const d={},f=Object.keys(l),g=f.slice(0,20);for(const m of g)try{d[m]=i(l[m],u+1)}catch{d[m]="[Error accessing property]"}return f.length>20&&(d["..."]=`${f.length-20} more properties`),d}return String(l)};return i(e,0)}};$(gs,"loadedScripts",new Set);let fo=gs,Jl=null;function lm(o){return Jl||(Jl=new fo(o)),Jl}function mC(o){Jl=o}const cm=dt("TransitionManager");class yC{constructor(){$(this,"isPending",!1);$(this,"subscribers",new Set)}setPending(e){this.isPending!==e&&(cm.log("setPending:",{from:this.isPending,to:e,stack:new Error().stack}),this.isPending=e,this.notifySubscribers())}getIsPending(){return this.isPending}subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}notifySubscribers(){cm.log("notifySubscribers:",{isPending:this.isPending,subscriberCount:this.subscribers.size}),this.subscribers.forEach(e=>{e(this.isPending)})}clearSubscribers(){this.subscribers.clear()}}const Ha=new yC,Ql=dt("TransitionContext"),um=I.createContext({isTransitioning:!1}),Nd=({children:o})=>{const[e,n]=I.useState(()=>{const i=Ha.getIsPending();return Ql.log("Initial state:",i),i});I.useEffect(()=>{Ql.log("Subscribing to TransitionManager");const i=Ha.subscribe(l=>{Ql.log("Received isPending update:",l),n(l)});return()=>{Ql.log("Unsubscribing from TransitionManager"),i()}},[]);const r=I.useMemo(()=>({isTransitioning:e}),[e]);return ft.jsx(um.Provider,{value:r,children:o})},dm=()=>I.useContext(um),Zl="__g7LocalInitTracking";function Id(){const o=globalThis;return o[Zl]||(o[Zl]={hash:"",timestamp:void 0,consumed:void 0}),o[Zl]}function bC(){const o=globalThis;o[Zl]={hash:"",timestamp:void 0,consumed:void 0}}function vC(o){Id().consumed=o}function SC(o){return Id().consumed===o}function wC(o,e){return typeof o=="number"&&typeof e=="number"?Math.max(o,e):e??o}function CC(o,e){if(e===void 0)return o;if(!(o!==null&&typeof o=="object"&&e!==null&&typeof e=="object"&&!SC(o)))return e;const{_forceLocalInit:r,...i}=o,{_forceLocalInit:l,...u}=e,d={...i,...u},f=wC(r,l);return f!==void 0&&(d._forceLocalInit=f),d}function EC(o){return o<768?"mobile":o<1024?"tablet":"desktop"}function fm(o){const e=EC(o);return{width:o,isMobile:e==="mobile",isTablet:e==="tablet",isDesktop:e==="desktop",matchedPreset:e}}const Hd=I.createContext(fm(1024)),ec=({children:o,overrideWidth:e})=>{const[n,r]=I.useState(()=>ui.getWidth());I.useEffect(()=>{const u=ui.subscribe(d=>{r(d)});return()=>{u()}},[]);const i=e??n,l=I.useMemo(()=>fm(i),[i]);return ft.jsx(Hd.Provider,{value:l,children:o})},zd=()=>I.useContext(Hd);window.G7Core?.createLogger?.("Core:State");function _C(o,e,n,r){const{syncOnControlledChange:i=!0,isEqual:l}=r??{},u=o!==void 0;I.useRef(u);const[d,f]=I.useState(o!==void 0?o:e),g=d,m=I.useRef(o),b=I.useRef(!1);I.useEffect(()=>{if(b.current){m.current=o;return}i&&u&&o!==m.current&&(l?!l(d,o):d!==o)&&f(o),m.current=o},[o,u,i,l,d]);const v=I.useCallback(S=>{const _=typeof S=="function"?S(g):S;(l?l(g,_):g===_)||(b.current=!0,f(_),n?.(_),requestAnimationFrame(()=>{b.current=!1}))},[g,u,n,l]);return[g,v]}function AC(o,e){return o===e?!0:o.length!==e.length?!1:o.every((n,r)=>n===e[r])}function hm(o,e){if(o===e)return!0;const n=Object.keys(o),r=Object.keys(e);return n.length!==r.length?!1:n.every(i=>o[i]===e[i])}const gm=I.createContext({}),xC=({children:o,value:e})=>ft.jsx(gm.Provider,{value:e,children:o}),TC=()=>I.useContext(gm),RC=(o,e)=>{if(!o)return;const n=e.split(".");let r=o;for(const i of n){if(r==null)return;r=r[i]}return r},kC=(o,e,n)=>{const r=e.split(".");if(r.length===1)return{...o,[r[0]]:n};const i={...o};let l=i;for(let u=0;u{ss.warn("IsolatedStateContext not available: setState called outside IsolatedStateProvider")},getState:()=>{},mergeState:()=>{ss.warn("IsolatedStateContext not available: mergeState called outside IsolatedStateProvider")},stateRef:{current:{}},scopeId:""},pm=I.createContext(DC);let OC=0;function LC(){return`isolated-${++OC}-${Date.now().toString(36)}`}function mm(o,e){if(e==null)return o;if(typeof e!="object"||Array.isArray(e))return e;const n={...o};for(const r of Object.keys(e)){const i=e[r],l=o?.[r];i!==null&&typeof i=="object"&&!Array.isArray(i)&&l!==null&&typeof l=="object"&&!Array.isArray(l)?n[r]=mm(l,i):n[r]=i}return n}function MC(o,e){return e?e.split(".").reduce((n,r)=>n?.[r],o):o}function $C(o,e,n){const r=e.split("."),i={...o};let l=i;for(let u=0;u{const i=I.useRef(e||LC()).current,[l,u]=I.useState(o),d=I.useRef(l);d.current=l;const f=I.useCallback(S=>MC(d.current,S),[]),g=I.useCallback((S,_)=>{u(x=>{const k=$C(x,S,_);return ss.log(`[${i}] setState: ${S} =`,_),k})},[i]),m=I.useCallback((S,_="deep")=>{u(x=>{let k;return _==="replace"?k=S:_==="shallow"?k={...x,...S}:k=mm(x,S),ss.log(`[${i}] mergeState (${_}):`,S),k})},[i]),b=I.useMemo(()=>({state:l,setState:g,getState:f,mergeState:m,stateRef:d,scopeId:i}),[l,g,f,m,i]),v=I.useMemo(()=>({state:d.current,setState:g,getState:f,mergeState:m}),[g,f,m]);return I.useEffect(()=>{const S=window.G7Core,_=window.__g7IsolatedStates||{};return window.__g7IsolatedStates||(window.__g7IsolatedStates=_),_[i]=v,S&&(S._isolatedStates||(S._isolatedStates={}),S._isolatedStates[i]=l),S?.devTools?.isEnabled?.()&&S.devTools.emit?.("isolated:created",{id:i,state:l}),ss.log(`[${i}] IsolatedStateProvider mounted with initial state:`,l),()=>{delete _[i],S?._isolatedStates&&delete S._isolatedStates[i],S?.devTools?.isEnabled?.()&&S.devTools.emit?.("isolated:destroyed",{id:i}),ss.log(`[${i}] IsolatedStateProvider unmounted`)}},[i,v]),I.useEffect(()=>{const S=window.G7Core,_=window.__g7IsolatedStates;_?.[i]&&(_[i].state=l),S?._isolatedStates&&(S._isolatedStates[i]=l),S?.devTools?.isEnabled?.()&&S.devTools.emit?.("isolated:updated",{id:i,state:l})},[l,i]),ft.jsx(pm.Provider,{value:b,children:n})},IC=()=>{const o=I.useContext(pm);return o.scopeId?o:null};var Ar=Pg();function HC(){for(var o=arguments.length,e=new Array(o),n=0;nr=>{e.forEach(i=>i(r))},e)}const tc=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function os(o){const e=Object.prototype.toString.call(o);return e==="[object Window]"||e==="[object global]"}function jd(o){return"nodeType"in o}function Mn(o){var e,n;return o?os(o)?o:jd(o)&&(e=(n=o.ownerDocument)==null?void 0:n.defaultView)!=null?e:window:window}function Ud(o){const{Document:e}=Mn(o);return o instanceof e}function ho(o){return os(o)?!1:o instanceof Mn(o).HTMLElement}function ym(o){return o instanceof Mn(o).SVGElement}function ls(o){return o?os(o)?o.document:jd(o)?Ud(o)?o:ho(o)||ym(o)?o.ownerDocument:document:document:document}const za=tc?I.useLayoutEffect:I.useEffect;function Bd(o){const e=I.useRef(o);return za(()=>{e.current=o}),I.useCallback(function(){for(var n=arguments.length,r=new Array(n),i=0;i{o.current=setInterval(r,i)},[]),n=I.useCallback(()=>{o.current!==null&&(clearInterval(o.current),o.current=null)},[]);return[e,n]}function go(o,e){e===void 0&&(e=[o]);const n=I.useRef(o);return za(()=>{n.current!==o&&(n.current=o)},e),n}function po(o,e){const n=I.useRef();return I.useMemo(()=>{const r=o(n.current);return n.current=r,r},[...e])}function nc(o){const e=Bd(o),n=I.useRef(null),r=I.useCallback(i=>{i!==n.current&&e?.(i,n.current),n.current=i},[]);return[n,r]}function Pd(o){const e=I.useRef();return I.useEffect(()=>{e.current=o},[o]),e.current}let qd={};function mo(o,e){return I.useMemo(()=>{if(e)return e;const n=qd[o]==null?0:qd[o]+1;return qd[o]=n,o+"-"+n},[o,e])}function bm(o){return function(e){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i{const d=Object.entries(u);for(const[f,g]of d){const m=l[f];m!=null&&(l[f]=m+o*g)}return l},{...e})}}const cs=bm(1),yo=bm(-1);function jC(o){return"clientX"in o&&"clientY"in o}function Gd(o){if(!o)return!1;const{KeyboardEvent:e}=Mn(o.target);return e&&o instanceof e}function UC(o){if(!o)return!1;const{TouchEvent:e}=Mn(o.target);return e&&o instanceof e}function Vd(o){if(UC(o)){if(o.touches&&o.touches.length){const{clientX:e,clientY:n}=o.touches[0];return{x:e,y:n}}else if(o.changedTouches&&o.changedTouches.length){const{clientX:e,clientY:n}=o.changedTouches[0];return{x:e,y:n}}}return jC(o)?{x:o.clientX,y:o.clientY}:null}const bo=Object.freeze({Translate:{toString(o){if(!o)return;const{x:e,y:n}=o;return"translate3d("+(e?Math.round(e):0)+"px, "+(n?Math.round(n):0)+"px, 0)"}},Scale:{toString(o){if(!o)return;const{scaleX:e,scaleY:n}=o;return"scaleX("+e+") scaleY("+n+")"}},Transform:{toString(o){if(o)return[bo.Translate.toString(o),bo.Scale.toString(o)].join(" ")}},Transition:{toString(o){let{property:e,duration:n,easing:r}=o;return e+" "+n+"ms "+r}}}),vm="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function BC(o){return o.matches(vm)?o:o.querySelector(vm)}const PC={display:"none"};function qC(o){let{id:e,value:n}=o;return Xe.createElement("div",{id:e,style:PC},n)}function GC(o){let{id:e,announcement:n,ariaLiveType:r="assertive"}=o;const i={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return Xe.createElement("div",{id:e,style:i,role:"status","aria-live":r,"aria-atomic":!0},n)}function VC(){const[o,e]=I.useState("");return{announce:I.useCallback(r=>{r!=null&&e(r)},[]),announcement:o}}const Sm=I.createContext(null);function FC(o){const e=I.useContext(Sm);I.useEffect(()=>{if(!e)throw new Error("useDndMonitor must be used within a children of ");return e(o)},[o,e])}function KC(){const[o]=I.useState(()=>new Set),e=I.useCallback(r=>(o.add(r),()=>o.delete(r)),[o]);return[I.useCallback(r=>{let{type:i,event:l}=r;o.forEach(u=>{var d;return(d=u[i])==null?void 0:d.call(u,l)})},[o]),e]}const WC={draggable:` To pick up a draggable item, press the space bar. While dragging, use the arrow keys to move the item. Press space again to drop the item in its new position, or press escape to cancel. - `},MC={onDragStart(o){let{active:e}=o;return"Picked up draggable item "+e.id+"."},onDragOver(o){let{active:e,over:a}=o;return a?"Draggable item "+e.id+" was moved over droppable area "+a.id+".":"Draggable item "+e.id+" is no longer over a droppable area."},onDragEnd(o){let{active:e,over:a}=o;return a?"Draggable item "+e.id+" was dropped over droppable area "+a.id:"Draggable item "+e.id+" was dropped."},onDragCancel(o){let{active:e}=o;return"Dragging was cancelled. Draggable item "+e.id+" was dropped."}};function $C(o){let{announcements:e=MC,container:a,hiddenTextDescribedById:r,screenReaderInstructions:i=LC}=o;const{announce:l,announcement:u}=kC(),d=ho("DndLiveRegion"),[f,g]=N.useState(!1);if(N.useEffect(()=>{g(!0)},[]),DC(N.useMemo(()=>({onDragStart(b){let{active:v}=b;l(e.onDragStart({active:v}))},onDragMove(b){let{active:v,over:S}=b;e.onDragMove&&l(e.onDragMove({active:v,over:S}))},onDragOver(b){let{active:v,over:S}=b;l(e.onDragOver({active:v,over:S}))},onDragEnd(b){let{active:v,over:S}=b;l(e.onDragEnd({active:v,over:S}))},onDragCancel(b){let{active:v,over:S}=b;l(e.onDragCancel({active:v,over:S}))}}),[l,e])),!f)return null;const m=Ye.createElement(Ye.Fragment,null,Ye.createElement(TC,{id:r,value:i.draggable}),Ye.createElement(RC,{id:d,announcement:u}));return a?Ar.createPortal(m,a):m}var en;(function(o){o.DragStart="dragStart",o.DragMove="dragMove",o.DragEnd="dragEnd",o.DragCancel="dragCancel",o.DragOver="dragOver",o.RegisterDroppable="registerDroppable",o.SetDroppableDisabled="setDroppableDisabled",o.UnregisterDroppable="unregisterDroppable"})(en||(en={}));function ec(){}function fm(o,e){return N.useMemo(()=>({sensor:o,options:e??{}}),[o,e])}function NC(){for(var o=arguments.length,e=new Array(o),a=0;a[...e].filter(r=>r!=null),[...e])}const ma=Object.freeze({x:0,y:0});function hm(o,e){return Math.sqrt(Math.pow(o.x-e.x,2)+Math.pow(o.y-e.y,2))}function gm(o,e){let{data:{value:a}}=o,{data:{value:r}}=e;return a-r}function IC(o,e){let{data:{value:a}}=o,{data:{value:r}}=e;return r-a}function pm(o){let{left:e,top:a,height:r,width:i}=o;return[{x:e,y:a},{x:e+i,y:a},{x:e,y:a+r},{x:e+i,y:a+r}]}function mm(o,e){if(!o||o.length===0)return null;const[a]=o;return a[e]}function ym(o,e,a){return e===void 0&&(e=o.left),a===void 0&&(a=o.top),{x:e+o.width*.5,y:a+o.height*.5}}const HC=o=>{let{collisionRect:e,droppableRects:a,droppableContainers:r}=o;const i=ym(e,e.left,e.top),l=[];for(const u of r){const{id:d}=u,f=a.get(d);if(f){const g=hm(ym(f),i);l.push({id:d,data:{droppableContainer:u,value:g}})}}return l.sort(gm)},zC=o=>{let{collisionRect:e,droppableRects:a,droppableContainers:r}=o;const i=pm(e),l=[];for(const u of r){const{id:d}=u,f=a.get(d);if(f){const g=pm(f),m=i.reduce((v,S,E)=>v+hm(g[E],S),0),b=Number((m/4).toFixed(4));l.push({id:d,data:{droppableContainer:u,value:b}})}}return l.sort(gm)};function jC(o,e){const a=Math.max(e.top,o.top),r=Math.max(e.left,o.left),i=Math.min(e.left+e.width,o.left+o.width),l=Math.min(e.top+e.height,o.top+o.height),u=i-r,d=l-a;if(r{let{collisionRect:e,droppableRects:a,droppableContainers:r}=o;const i=[];for(const l of r){const{id:u}=l,d=a.get(u);if(d){const f=jC(d,e);f>0&&i.push({id:u,data:{droppableContainer:l,value:f}})}}return i.sort(IC)};function BC(o,e,a){return{...o,scaleX:e&&a?e.width/a.width:1,scaleY:e&&a?e.height/a.height:1}}function bm(o,e){return o&&e?{x:o.left-e.left,y:o.top-e.top}:ma}function PC(o){return function(a){for(var r=arguments.length,i=new Array(r>1?r-1:0),l=1;l({...u,top:u.top+o*d.y,bottom:u.bottom+o*d.y,left:u.left+o*d.x,right:u.right+o*d.x}),{...a})}}const qC=PC(1);function GC(o){if(o.startsWith("matrix3d(")){const e=o.slice(9,-1).split(/, /);return{x:+e[12],y:+e[13],scaleX:+e[0],scaleY:+e[5]}}else if(o.startsWith("matrix(")){const e=o.slice(7,-1).split(/, /);return{x:+e[4],y:+e[5],scaleX:+e[0],scaleY:+e[3]}}return null}function VC(o,e,a){const r=GC(e);if(!r)return o;const{scaleX:i,scaleY:l,x:u,y:d}=r,f=o.left-u-(1-i)*parseFloat(a),g=o.top-d-(1-l)*parseFloat(a.slice(a.indexOf(" ")+1)),m=i?o.width/i:o.width,b=l?o.height/l:o.height;return{width:m,height:b,top:g,right:f+m,bottom:g+b,left:f}}const FC={ignoreTransform:!1};function ss(o,e){e===void 0&&(e=FC);let a=o.getBoundingClientRect();if(e.ignoreTransform){const{transform:g,transformOrigin:m}=Tn(o).getComputedStyle(o);g&&(a=VC(a,g,m))}const{top:r,left:i,width:l,height:u,bottom:d,right:f}=a;return{top:r,left:i,width:l,height:u,bottom:d,right:f}}function vm(o){return ss(o,{ignoreTransform:!0})}function KC(o){const e=o.innerWidth,a=o.innerHeight;return{top:0,left:0,right:e,bottom:a,width:e,height:a}}function WC(o,e){return e===void 0&&(e=Tn(o).getComputedStyle(o)),e.position==="fixed"}function YC(o,e){e===void 0&&(e=Tn(o).getComputedStyle(o));const a=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(i=>{const l=e[i];return typeof l=="string"?a.test(l):!1})}function tc(o,e){const a=[];function r(i){if(e!=null&&a.length>=e||!i)return a;if(Id(i)&&i.scrollingElement!=null&&!a.includes(i.scrollingElement))return a.push(i.scrollingElement),a;if(!co(i)||lm(i)||a.includes(i))return a;const l=Tn(o).getComputedStyle(i);return i!==o&&YC(i,l)&&a.push(i),WC(i,l)?a:r(i.parentNode)}return o?r(o):a}function Sm(o){const[e]=tc(o,1);return e??null}function Pd(o){return!Ql||!o?null:as(o)?o:Nd(o)?Id(o)||o===rs(o).scrollingElement?window:co(o)?o:null:null}function wm(o){return as(o)?o.scrollX:o.scrollLeft}function Cm(o){return as(o)?o.scrollY:o.scrollTop}function qd(o){return{x:wm(o),y:Cm(o)}}var ln;(function(o){o[o.Forward=1]="Forward",o[o.Backward=-1]="Backward"})(ln||(ln={}));function Em(o){return!Ql||!o?!1:o===document.scrollingElement}function _m(o){const e={x:0,y:0},a=Em(o)?{height:window.innerHeight,width:window.innerWidth}:{height:o.clientHeight,width:o.clientWidth},r={x:o.scrollWidth-a.width,y:o.scrollHeight-a.height},i=o.scrollTop<=e.y,l=o.scrollLeft<=e.x,u=o.scrollTop>=r.y,d=o.scrollLeft>=r.x;return{isTop:i,isLeft:l,isBottom:u,isRight:d,maxScroll:r,minScroll:e}}const XC={x:.2,y:.2};function JC(o,e,a,r,i){let{top:l,left:u,right:d,bottom:f}=a;r===void 0&&(r=10),i===void 0&&(i=XC);const{isTop:g,isBottom:m,isLeft:b,isRight:v}=_m(o),S={x:0,y:0},E={x:0,y:0},A={height:e.height*i.y,width:e.width*i.x};return!g&&l<=e.top+A.height?(S.y=ln.Backward,E.y=r*Math.abs((e.top+A.height-l)/A.height)):!m&&f>=e.bottom-A.height&&(S.y=ln.Forward,E.y=r*Math.abs((e.bottom-A.height-f)/A.height)),!v&&d>=e.right-A.width?(S.x=ln.Forward,E.x=r*Math.abs((e.right-A.width-d)/A.width)):!b&&u<=e.left+A.width&&(S.x=ln.Backward,E.x=r*Math.abs((e.left+A.width-u)/A.width)),{direction:S,speed:E}}function QC(o){if(o===document.scrollingElement){const{innerWidth:l,innerHeight:u}=window;return{top:0,left:0,right:l,bottom:u,width:l,height:u}}const{top:e,left:a,right:r,bottom:i}=o.getBoundingClientRect();return{top:e,left:a,right:r,bottom:i,width:o.clientWidth,height:o.clientHeight}}function Am(o){return o.reduce((e,a)=>is(e,qd(a)),ma)}function ZC(o){return o.reduce((e,a)=>e+wm(a),0)}function eE(o){return o.reduce((e,a)=>e+Cm(a),0)}function tE(o,e){if(e===void 0&&(e=ss),!o)return;const{top:a,left:r,bottom:i,right:l}=e(o);Sm(o)&&(i<=0||l<=0||a>=window.innerHeight||r>=window.innerWidth)&&o.scrollIntoView({block:"center",inline:"center"})}const nE=[["x",["left","right"],ZC],["y",["top","bottom"],eE]];class Gd{constructor(e,a){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;const r=tc(a),i=Am(r);this.rect={...e},this.width=e.width,this.height=e.height;for(const[l,u,d]of nE)for(const f of u)Object.defineProperty(this,f,{get:()=>{const g=d(r),m=i[l]-g;return this.rect[f]+m},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class mo{constructor(e){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(a=>{var r;return(r=this.target)==null?void 0:r.removeEventListener(...a)})},this.target=e}add(e,a,r){var i;(i=this.target)==null||i.addEventListener(e,a,r),this.listeners.push([e,a,r])}}function aE(o){const{EventTarget:e}=Tn(o);return o instanceof e?o:rs(o)}function Vd(o,e){const a=Math.abs(o.x),r=Math.abs(o.y);return typeof e=="number"?Math.sqrt(a**2+r**2)>e:"x"in e&&"y"in e?a>e.x&&r>e.y:"x"in e?a>e.x:"y"in e?r>e.y:!1}var Qn;(function(o){o.Click="click",o.DragStart="dragstart",o.Keydown="keydown",o.ContextMenu="contextmenu",o.Resize="resize",o.SelectionChange="selectionchange",o.VisibilityChange="visibilitychange"})(Qn||(Qn={}));function xm(o){o.preventDefault()}function rE(o){o.stopPropagation()}var it;(function(o){o.Space="Space",o.Down="ArrowDown",o.Right="ArrowRight",o.Left="ArrowLeft",o.Up="ArrowUp",o.Esc="Escape",o.Enter="Enter",o.Tab="Tab"})(it||(it={}));const Tm={start:[it.Space,it.Enter],cancel:[it.Esc],end:[it.Space,it.Enter,it.Tab]},iE=(o,e)=>{let{currentCoordinates:a}=e;switch(o.code){case it.Right:return{...a,x:a.x+25};case it.Left:return{...a,x:a.x-25};case it.Down:return{...a,y:a.y+25};case it.Up:return{...a,y:a.y-25}}};class Fd{constructor(e){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=e;const{event:{target:a}}=e;this.props=e,this.listeners=new mo(rs(a)),this.windowListeners=new mo(Tn(a)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(Qn.Resize,this.handleCancel),this.windowListeners.add(Qn.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(Qn.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:e,onStart:a}=this.props,r=e.node.current;r&&tE(r),a(ma)}handleKeyDown(e){if(Ud(e)){const{active:a,context:r,options:i}=this.props,{keyboardCodes:l=Tm,coordinateGetter:u=iE,scrollBehavior:d="smooth"}=i,{code:f}=e;if(l.end.includes(f)){this.handleEnd(e);return}if(l.cancel.includes(f)){this.handleCancel(e);return}const{collisionRect:g}=r.current,m=g?{x:g.left,y:g.top}:ma;this.referenceCoordinates||(this.referenceCoordinates=m);const b=u(e,{active:a,context:r.current,currentCoordinates:m});if(b){const v=go(b,m),S={x:0,y:0},{scrollableAncestors:E}=r.current;for(const A of E){const T=e.code,{isTop:L,isRight:M,isLeft:R,isBottom:D,maxScroll:U,minScroll:j}=_m(A),P=QC(A),X={x:Math.min(T===it.Right?P.right-P.width/2:P.right,Math.max(T===it.Right?P.left:P.left+P.width/2,b.x)),y:Math.min(T===it.Down?P.bottom-P.height/2:P.bottom,Math.max(T===it.Down?P.top:P.top+P.height/2,b.y))},ge=T===it.Right&&!M||T===it.Left&&!R,Ee=T===it.Down&&!D||T===it.Up&&!L;if(ge&&X.x!==b.x){const Ce=A.scrollLeft+v.x,$e=T===it.Right&&Ce<=U.x||T===it.Left&&Ce>=j.x;if($e&&!v.y){A.scrollTo({left:Ce,behavior:d});return}$e?S.x=A.scrollLeft-Ce:S.x=T===it.Right?A.scrollLeft-U.x:A.scrollLeft-j.x,S.x&&A.scrollBy({left:-S.x,behavior:d});break}else if(Ee&&X.y!==b.y){const Ce=A.scrollTop+v.y,$e=T===it.Down&&Ce<=U.y||T===it.Up&&Ce>=j.y;if($e&&!v.x){A.scrollTo({top:Ce,behavior:d});return}$e?S.y=A.scrollTop-Ce:S.y=T===it.Down?A.scrollTop-U.y:A.scrollTop-j.y,S.y&&A.scrollBy({top:-S.y,behavior:d});break}}this.handleMove(e,is(go(b,this.referenceCoordinates),S))}}}handleMove(e,a){const{onMove:r}=this.props;e.preventDefault(),r(a)}handleEnd(e){const{onEnd:a}=this.props;e.preventDefault(),this.detach(),a()}handleCancel(e){const{onCancel:a}=this.props;e.preventDefault(),this.detach(),a()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}Fd.activators=[{eventName:"onKeyDown",handler:(o,e,a)=>{let{keyboardCodes:r=Tm,onActivation:i}=e,{active:l}=a;const{code:u}=o.nativeEvent;if(r.start.includes(u)){const d=l.activatorNode.current;return d&&o.target!==d?!1:(o.preventDefault(),i?.({event:o.nativeEvent}),!0)}return!1}}];function Rm(o){return!!(o&&"distance"in o)}function km(o){return!!(o&&"delay"in o)}class Kd{constructor(e,a,r){var i;r===void 0&&(r=aE(e.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=e,this.events=a;const{event:l}=e,{target:u}=l;this.props=e,this.events=a,this.document=rs(u),this.documentListeners=new mo(this.document),this.listeners=new mo(r),this.windowListeners=new mo(Tn(u)),this.initialCoordinates=(i=Bd(l))!=null?i:ma,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){const{events:e,props:{options:{activationConstraint:a,bypassActivationConstraint:r}}}=this;if(this.listeners.add(e.move.name,this.handleMove,{passive:!1}),this.listeners.add(e.end.name,this.handleEnd),e.cancel&&this.listeners.add(e.cancel.name,this.handleCancel),this.windowListeners.add(Qn.Resize,this.handleCancel),this.windowListeners.add(Qn.DragStart,xm),this.windowListeners.add(Qn.VisibilityChange,this.handleCancel),this.windowListeners.add(Qn.ContextMenu,xm),this.documentListeners.add(Qn.Keydown,this.handleKeydown),a){if(r!=null&&r({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(km(a)){this.timeoutId=setTimeout(this.handleStart,a.delay),this.handlePending(a);return}if(Rm(a)){this.handlePending(a);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(e,a){const{active:r,onPending:i}=this.props;i(r,e,this.initialCoordinates,a)}handleStart(){const{initialCoordinates:e}=this,{onStart:a}=this.props;e&&(this.activated=!0,this.documentListeners.add(Qn.Click,rE,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(Qn.SelectionChange,this.removeTextSelection),a(e))}handleMove(e){var a;const{activated:r,initialCoordinates:i,props:l}=this,{onMove:u,options:{activationConstraint:d}}=l;if(!i)return;const f=(a=Bd(e))!=null?a:ma,g=go(i,f);if(!r&&d){if(Rm(d)){if(d.tolerance!=null&&Vd(g,d.tolerance))return this.handleCancel();if(Vd(g,d.distance))return this.handleStart()}if(km(d)&&Vd(g,d.tolerance))return this.handleCancel();this.handlePending(d,g);return}e.cancelable&&e.preventDefault(),u(f)}handleEnd(){const{onAbort:e,onEnd:a}=this.props;this.detach(),this.activated||e(this.props.active),a()}handleCancel(){const{onAbort:e,onCancel:a}=this.props;this.detach(),this.activated||e(this.props.active),a()}handleKeydown(e){e.code===it.Esc&&this.handleCancel()}removeTextSelection(){var e;(e=this.document.getSelection())==null||e.removeAllRanges()}}const sE={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class Wd extends Kd{constructor(e){const{event:a}=e,r=rs(a.target);super(e,sE,r)}}Wd.activators=[{eventName:"onPointerDown",handler:(o,e)=>{let{nativeEvent:a}=o,{onActivation:r}=e;return!a.isPrimary||a.button!==0?!1:(r?.({event:a}),!0)}}];const oE={move:{name:"mousemove"},end:{name:"mouseup"}};var Yd;(function(o){o[o.RightClick=2]="RightClick"})(Yd||(Yd={}));class lE extends Kd{constructor(e){super(e,oE,rs(e.event.target))}}lE.activators=[{eventName:"onMouseDown",handler:(o,e)=>{let{nativeEvent:a}=o,{onActivation:r}=e;return a.button===Yd.RightClick?!1:(r?.({event:a}),!0)}}];const Xd={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class cE extends Kd{constructor(e){super(e,Xd)}static setup(){return window.addEventListener(Xd.move.name,e,{capture:!1,passive:!1}),function(){window.removeEventListener(Xd.move.name,e)};function e(){}}}cE.activators=[{eventName:"onTouchStart",handler:(o,e)=>{let{nativeEvent:a}=o,{onActivation:r}=e;const{touches:i}=a;return i.length>1?!1:(r?.({event:a}),!0)}}];var yo;(function(o){o[o.Pointer=0]="Pointer",o[o.DraggableRect=1]="DraggableRect"})(yo||(yo={}));var nc;(function(o){o[o.TreeOrder=0]="TreeOrder",o[o.ReversedTreeOrder=1]="ReversedTreeOrder"})(nc||(nc={}));function uE(o){let{acceleration:e,activator:a=yo.Pointer,canScroll:r,draggingRect:i,enabled:l,interval:u=5,order:d=nc.TreeOrder,pointerCoordinates:f,scrollableAncestors:g,scrollableAncestorRects:m,delta:b,threshold:v}=o;const S=fE({delta:b,disabled:!l}),[E,A]=CC(),T=N.useRef({x:0,y:0}),L=N.useRef({x:0,y:0}),M=N.useMemo(()=>{switch(a){case yo.Pointer:return f?{top:f.y,bottom:f.y,left:f.x,right:f.x}:null;case yo.DraggableRect:return i}},[a,i,f]),R=N.useRef(null),D=N.useCallback(()=>{const j=R.current;if(!j)return;const P=T.current.x*L.current.x,X=T.current.y*L.current.y;j.scrollBy(P,X)},[]),U=N.useMemo(()=>d===nc.TreeOrder?[...g].reverse():g,[d,g]);N.useEffect(()=>{if(!l||!g.length||!M){A();return}for(const j of U){if(r?.(j)===!1)continue;const P=g.indexOf(j),X=m[P];if(!X)continue;const{direction:ge,speed:Ee}=JC(j,X,M,e,v);for(const Ce of["x","y"])S[Ce][ge[Ce]]||(Ee[Ce]=0,ge[Ce]=0);if(Ee.x>0||Ee.y>0){A(),R.current=j,E(D,u),T.current=Ee,L.current=ge;return}}T.current={x:0,y:0},L.current={x:0,y:0},A()},[e,D,r,A,l,u,JSON.stringify(M),JSON.stringify(S),E,g,U,m,JSON.stringify(v)])}const dE={x:{[ln.Backward]:!1,[ln.Forward]:!1},y:{[ln.Backward]:!1,[ln.Forward]:!1}};function fE(o){let{delta:e,disabled:a}=o;const r=zd(e);return fo(i=>{if(a||!r||!i)return dE;const l={x:Math.sign(e.x-r.x),y:Math.sign(e.y-r.y)};return{x:{[ln.Backward]:i.x[ln.Backward]||l.x===-1,[ln.Forward]:i.x[ln.Forward]||l.x===1},y:{[ln.Backward]:i.y[ln.Backward]||l.y===-1,[ln.Forward]:i.y[ln.Forward]||l.y===1}}},[a,e,r])}function hE(o,e){const a=e!=null?o.get(e):void 0,r=a?a.node.current:null;return fo(i=>{var l;return e==null?null:(l=r??i)!=null?l:null},[r,e])}function gE(o,e){return N.useMemo(()=>o.reduce((a,r)=>{const{sensor:i}=r,l=i.activators.map(u=>({eventName:u.eventName,handler:e(u.handler,r)}));return[...a,...l]},[]),[o,e])}var bo;(function(o){o[o.Always=0]="Always",o[o.BeforeDragging=1]="BeforeDragging",o[o.WhileDragging=2]="WhileDragging"})(bo||(bo={}));var Jd;(function(o){o.Optimized="optimized"})(Jd||(Jd={}));const Dm=new Map;function pE(o,e){let{dragging:a,dependencies:r,config:i}=e;const[l,u]=N.useState(null),{frequency:d,measure:f,strategy:g}=i,m=N.useRef(o),b=T(),v=uo(b),S=N.useCallback(function(L){L===void 0&&(L=[]),!v.current&&u(M=>M===null?L:M.concat(L.filter(R=>!M.includes(R))))},[v]),E=N.useRef(null),A=fo(L=>{if(b&&!a)return Dm;if(!L||L===Dm||m.current!==o||l!=null){const M=new Map;for(let R of o){if(!R)continue;if(l&&l.length>0&&!l.includes(R.id)&&R.rect.current){M.set(R.id,R.rect.current);continue}const D=R.node.current,U=D?new Gd(f(D),D):null;R.rect.current=U,U&&M.set(R.id,U)}return M}return L},[o,l,a,b,f]);return N.useEffect(()=>{m.current=o},[o]),N.useEffect(()=>{b||S()},[a,b]),N.useEffect(()=>{l&&l.length>0&&u(null)},[JSON.stringify(l)]),N.useEffect(()=>{b||typeof d!="number"||E.current!==null||(E.current=setTimeout(()=>{S(),E.current=null},d))},[d,b,S,...r]),{droppableRects:A,measureDroppableContainers:S,measuringScheduled:l!=null};function T(){switch(g){case bo.Always:return!1;case bo.BeforeDragging:return a;default:return!a}}}function Om(o,e){return fo(a=>o?a||(typeof e=="function"?e(o):o):null,[e,o])}function mE(o,e){return Om(o,e)}function yE(o){let{callback:e,disabled:a}=o;const r=Hd(e),i=N.useMemo(()=>{if(a||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:l}=window;return new l(r)},[r,a]);return N.useEffect(()=>()=>i?.disconnect(),[i]),i}function ac(o){let{callback:e,disabled:a}=o;const r=Hd(e),i=N.useMemo(()=>{if(a||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:l}=window;return new l(r)},[a]);return N.useEffect(()=>()=>i?.disconnect(),[i]),i}function bE(o){return new Gd(ss(o),o)}function Lm(o,e,a){e===void 0&&(e=bE);const[r,i]=N.useState(null);function l(){i(f=>{if(!o)return null;if(o.isConnected===!1){var g;return(g=f??a)!=null?g:null}const m=e(o);return JSON.stringify(f)===JSON.stringify(m)?f:m})}const u=yE({callback(f){if(o)for(const g of f){const{type:m,target:b}=g;if(m==="childList"&&b instanceof HTMLElement&&b.contains(o)){l();break}}}}),d=ac({callback:l});return Ia(()=>{l(),o?(d?.observe(o),u?.observe(document.body,{childList:!0,subtree:!0})):(d?.disconnect(),u?.disconnect())},[o]),r}function vE(o){const e=Om(o);return bm(o,e)}const Mm=[];function SE(o){const e=N.useRef(o),a=fo(r=>o?r&&r!==Mm&&o&&e.current&&o.parentNode===e.current.parentNode?r:tc(o):Mm,[o]);return N.useEffect(()=>{e.current=o},[o]),a}function wE(o){const[e,a]=N.useState(null),r=N.useRef(o),i=N.useCallback(l=>{const u=Pd(l.target);u&&a(d=>d?(d.set(u,qd(u)),new Map(d)):null)},[]);return N.useEffect(()=>{const l=r.current;if(o!==l){u(l);const d=o.map(f=>{const g=Pd(f);return g?(g.addEventListener("scroll",i,{passive:!0}),[g,qd(g)]):null}).filter(f=>f!=null);a(d.length?new Map(d):null),r.current=o}return()=>{u(o),u(l)};function u(d){d.forEach(f=>{const g=Pd(f);g?.removeEventListener("scroll",i)})}},[i,o]),N.useMemo(()=>o.length?e?Array.from(e.values()).reduce((l,u)=>is(l,u),ma):Am(o):ma,[o,e])}function $m(o,e){e===void 0&&(e=[]);const a=N.useRef(null);return N.useEffect(()=>{a.current=null},e),N.useEffect(()=>{const r=o!==ma;r&&!a.current&&(a.current=o),!r&&a.current&&(a.current=null)},[o]),a.current?go(o,a.current):ma}function CE(o){N.useEffect(()=>{if(!Ql)return;const e=o.map(a=>{let{sensor:r}=a;return r.setup==null?void 0:r.setup()});return()=>{for(const a of e)a?.()}},o.map(e=>{let{sensor:a}=e;return a}))}function EE(o,e){return N.useMemo(()=>o.reduce((a,r)=>{let{eventName:i,handler:l}=r;return a[i]=u=>{l(u,e)},a},{}),[o,e])}function Nm(o){return N.useMemo(()=>o?KC(o):null,[o])}const Im=[];function _E(o,e){e===void 0&&(e=ss);const[a]=o,r=Nm(a?Tn(a):null),[i,l]=N.useState(Im);function u(){l(()=>o.length?o.map(f=>Em(f)?r:new Gd(e(f),f)):Im)}const d=ac({callback:u});return Ia(()=>{d?.disconnect(),u(),o.forEach(f=>d?.observe(f))},[o]),i}function AE(o){if(!o)return null;if(o.children.length>1)return o;const e=o.children[0];return co(e)?e:o}function xE(o){let{measure:e}=o;const[a,r]=N.useState(null),i=N.useCallback(g=>{for(const{target:m}of g)if(co(m)){r(b=>{const v=e(m);return b?{...b,width:v.width,height:v.height}:v});break}},[e]),l=ac({callback:i}),u=N.useCallback(g=>{const m=AE(g);l?.disconnect(),m&&l?.observe(m),r(m?e(m):null)},[e,l]),[d,f]=Zl(u);return N.useMemo(()=>({nodeRef:d,rect:a,setRef:f}),[a,d,f])}const TE=[{sensor:Wd,options:{}},{sensor:Fd,options:{}}],RE={current:{}},rc={draggable:{measure:vm},droppable:{measure:vm,strategy:bo.WhileDragging,frequency:Jd.Optimized},dragOverlay:{measure:ss}};class vo extends Map{get(e){var a;return e!=null&&(a=super.get(e))!=null?a:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(e=>{let{disabled:a}=e;return!a})}getNodeFor(e){var a,r;return(a=(r=this.get(e))==null?void 0:r.node.current)!=null?a:void 0}}const kE={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new vo,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:ec},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:rc,measureDroppableContainers:ec,windowRect:null,measuringScheduled:!1},DE={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:ec,draggableNodes:new Map,over:null,measureDroppableContainers:ec},ic=N.createContext(DE),Hm=N.createContext(kE);function OE(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new vo}}}function LE(o,e){switch(e.type){case en.DragStart:return{...o,draggable:{...o.draggable,initialCoordinates:e.initialCoordinates,active:e.active}};case en.DragMove:return o.draggable.active==null?o:{...o,draggable:{...o.draggable,translate:{x:e.coordinates.x-o.draggable.initialCoordinates.x,y:e.coordinates.y-o.draggable.initialCoordinates.y}}};case en.DragEnd:case en.DragCancel:return{...o,draggable:{...o.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case en.RegisterDroppable:{const{element:a}=e,{id:r}=a,i=new vo(o.droppable.containers);return i.set(r,a),{...o,droppable:{...o.droppable,containers:i}}}case en.SetDroppableDisabled:{const{id:a,key:r,disabled:i}=e,l=o.droppable.containers.get(a);if(!l||r!==l.key)return o;const u=new vo(o.droppable.containers);return u.set(a,{...l,disabled:i}),{...o,droppable:{...o.droppable,containers:u}}}case en.UnregisterDroppable:{const{id:a,key:r}=e,i=o.droppable.containers.get(a);if(!i||r!==i.key)return o;const l=new vo(o.droppable.containers);return l.delete(a),{...o,droppable:{...o.droppable,containers:l}}}default:return o}}function ME(o){let{disabled:e}=o;const{active:a,activatorEvent:r,draggableNodes:i}=N.useContext(ic),l=zd(r),u=zd(a?.id);return N.useEffect(()=>{if(!e&&!r&&l&&u!=null){if(!Ud(l)||document.activeElement===l.target)return;const d=i.get(u);if(!d)return;const{activatorNode:f,node:g}=d;if(!f.current&&!g.current)return;requestAnimationFrame(()=>{for(const m of[f.current,g.current]){if(!m)continue;const b=AC(m);if(b){b.focus();break}}})}},[r,e,i,u,l]),null}function $E(o,e){let{transform:a,...r}=e;return o!=null&&o.length?o.reduce((i,l)=>l({transform:i,...r}),a):a}function NE(o){return N.useMemo(()=>({draggable:{...rc.draggable,...o?.draggable},droppable:{...rc.droppable,...o?.droppable},dragOverlay:{...rc.dragOverlay,...o?.dragOverlay}}),[o?.draggable,o?.droppable,o?.dragOverlay])}function IE(o){let{activeNode:e,measure:a,initialRect:r,config:i=!0}=o;const l=N.useRef(!1),{x:u,y:d}=typeof i=="boolean"?{x:i,y:i}:i;Ia(()=>{if(!u&&!d||!e){l.current=!1;return}if(l.current||!r)return;const g=e?.node.current;if(!g||g.isConnected===!1)return;const m=a(g),b=bm(m,r);if(u||(b.x=0),d||(b.y=0),l.current=!0,Math.abs(b.x)>0||Math.abs(b.y)>0){const v=Sm(g);v&&v.scrollBy({top:b.y,left:b.x})}},[e,u,d,r,a])}const zm=N.createContext({...ma,scaleX:1,scaleY:1});var xr;(function(o){o[o.Uninitialized=0]="Uninitialized",o[o.Initializing=1]="Initializing",o[o.Initialized=2]="Initialized"})(xr||(xr={}));const HE=N.memo(function(e){var a,r,i,l;let{id:u,accessibility:d,autoScroll:f=!0,children:g,sensors:m=TE,collisionDetection:b=UC,measuring:v,modifiers:S,...E}=e;const A=N.useReducer(LE,void 0,OE),[T,L]=A,[M,R]=OC(),[D,U]=N.useState(xr.Uninitialized),j=D===xr.Initialized,{draggable:{active:P,nodes:X,translate:ge},droppable:{containers:Ee}}=T,Ce=P!=null?X.get(P):null,$e=N.useRef({initial:null,translated:null}),Pe=N.useMemo(()=>{var Re;return P!=null?{id:P,data:(Re=Ce?.data)!=null?Re:RE,rect:$e}:null},[P,Ce]),Xe=N.useRef(null),[ht,Q]=N.useState(null),[fe,ye]=N.useState(null),te=uo(E,Object.values(E)),he=ho("DndDescribedBy",u),x=N.useMemo(()=>Ee.getEnabled(),[Ee]),K=NE(v),{droppableRects:re,measureDroppableContainers:de,measuringScheduled:ie}=pE(x,{dragging:j,dependencies:[ge.x,ge.y],config:K.droppable}),me=hE(X,P),Ne=N.useMemo(()=>fe?Bd(fe):null,[fe]),Se=ve(),He=mE(me,K.draggable.measure);IE({activeNode:P!=null?X.get(P):null,config:Se.layoutShiftCompensation,initialRect:He,measure:K.draggable.measure});const Ae=Lm(me,K.draggable.measure,He),Et=Lm(me?me.parentElement:null),kt=N.useRef({activatorEvent:null,active:null,activeNode:me,collisionRect:null,collisions:null,droppableRects:re,draggableNodes:X,draggingNode:null,draggingNodeRect:null,droppableContainers:Ee,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),_t=Ee.getNodeFor((a=kt.current.over)==null?void 0:a.id),ft=xE({measure:K.dragOverlay.measure}),un=(r=ft.nodeRef.current)!=null?r:me,gt=j?(i=ft.rect)!=null?i:Ae:null,ja=!!(ft.nodeRef.current&&ft.rect),kn=vE(ja?null:Ae),Dn=Nm(un?Tn(un):null),jt=SE(j?_t??me:null),On=_E(jt),ea=$E(S,{transform:{x:ge.x-kn.x,y:ge.y-kn.y,scaleX:1,scaleY:1},activatorEvent:fe,active:Pe,activeNodeRect:Ae,containerNodeRect:Et,draggingNodeRect:gt,over:kt.current.over,overlayNodeRect:ft.rect,scrollableAncestors:jt,scrollableAncestorRects:On,windowRect:Dn}),Ua=Ne?is(Ne,ge):null,Kt=wE(jt),Dr=$m(Kt),er=$m(Kt,[Ae]),bn=is(ea,Dr),tn=gt?qC(gt,ea):null,et=Pe&&tn?b({active:Pe,collisionRect:tn,droppableRects:re,droppableContainers:x,pointerCoordinates:Ua}):null,ta=mm(et,"id"),[En,tr]=N.useState(null),Ea=ja?ea:is(ea,er),nn=BC(Ea,(l=En?.rect)!=null?l:null,Ae),_n=N.useRef(null),q=N.useCallback((Re,xe)=>{let{sensor:je,options:ze}=xe;if(Xe.current==null)return;const Le=X.get(Xe.current);if(!Le)return;const ke=Re.nativeEvent,We=new je({active:Xe.current,activeNode:Le,event:ke,options:ze,context:kt,onAbort(_e){if(!X.get(_e))return;const{onDragAbort:Ue}=te.current,st={id:_e};Ue?.(st),M({type:"onDragAbort",event:st})},onPending(_e,Te,Ue,st){if(!X.get(_e))return;const{onDragPending:Wt}=te.current,qt={id:_e,constraint:Te,initialCoordinates:Ue,offset:st};Wt?.(qt),M({type:"onDragPending",event:qt})},onStart(_e){const Te=Xe.current;if(Te==null)return;const Ue=X.get(Te);if(!Ue)return;const{onDragStart:st}=te.current,At={activatorEvent:ke,active:{id:Te,data:Ue.data,rect:$e}};Ar.unstable_batchedUpdates(()=>{st?.(At),U(xr.Initializing),L({type:en.DragStart,initialCoordinates:_e,active:Te}),M({type:"onDragStart",event:At}),Q(_n.current),ye(ke)})},onMove(_e){L({type:en.DragMove,coordinates:_e})},onEnd:Fe(en.DragEnd),onCancel:Fe(en.DragCancel)});_n.current=We;function Fe(_e){return async function(){const{active:Ue,collisions:st,over:At,scrollAdjustedTranslate:Wt}=kt.current;let qt=null;if(Ue&&Wt){const{cancelDrop:qn}=te.current;qt={activatorEvent:ke,active:Ue,collisions:st,delta:Wt,over:At},_e===en.DragEnd&&typeof qn=="function"&&await Promise.resolve(qn(qt))&&(_e=en.DragCancel)}Xe.current=null,Ar.unstable_batchedUpdates(()=>{L({type:_e}),U(xr.Uninitialized),tr(null),Q(null),ye(null),_n.current=null;const qn=_e===en.DragEnd?"onDragEnd":"onDragCancel";if(qt){const Ln=te.current[qn];Ln?.(qt),M({type:qn,event:qt})}})}}},[X]),ce=N.useCallback((Re,xe)=>(je,ze)=>{const Le=je.nativeEvent,ke=X.get(ze);if(Xe.current!==null||!ke||Le.dndKit||Le.defaultPrevented)return;const We={active:ke};Re(je,xe.options,We)===!0&&(Le.dndKit={capturedBy:xe.sensor},Xe.current=ze,q(je,xe))},[X,q]),le=gE(m,ce);CE(m),Ia(()=>{Ae&&D===xr.Initializing&&U(xr.Initialized)},[Ae,D]),N.useEffect(()=>{const{onDragMove:Re}=te.current,{active:xe,activatorEvent:je,collisions:ze,over:Le}=kt.current;if(!xe||!je)return;const ke={active:xe,activatorEvent:je,collisions:ze,delta:{x:bn.x,y:bn.y},over:Le};Ar.unstable_batchedUpdates(()=>{Re?.(ke),M({type:"onDragMove",event:ke})})},[bn.x,bn.y]),N.useEffect(()=>{const{active:Re,activatorEvent:xe,collisions:je,droppableContainers:ze,scrollAdjustedTranslate:Le}=kt.current;if(!Re||Xe.current==null||!xe||!Le)return;const{onDragOver:ke}=te.current,We=ze.get(ta),Fe=We&&We.rect.current?{id:We.id,rect:We.rect.current,data:We.data,disabled:We.disabled}:null,_e={active:Re,activatorEvent:xe,collisions:je,delta:{x:Le.x,y:Le.y},over:Fe};Ar.unstable_batchedUpdates(()=>{tr(Fe),ke?.(_e),M({type:"onDragOver",event:_e})})},[ta]),Ia(()=>{kt.current={activatorEvent:fe,active:Pe,activeNode:me,collisionRect:tn,collisions:et,droppableRects:re,draggableNodes:X,draggingNode:un,draggingNodeRect:gt,droppableContainers:Ee,over:En,scrollableAncestors:jt,scrollAdjustedTranslate:bn},$e.current={initial:gt,translated:tn}},[Pe,me,et,tn,X,un,gt,re,Ee,En,jt,bn]),uE({...Se,delta:ge,draggingRect:tn,pointerCoordinates:Ua,scrollableAncestors:jt,scrollableAncestorRects:On});const Z=N.useMemo(()=>({active:Pe,activeNode:me,activeNodeRect:Ae,activatorEvent:fe,collisions:et,containerNodeRect:Et,dragOverlay:ft,draggableNodes:X,droppableContainers:Ee,droppableRects:re,over:En,measureDroppableContainers:de,scrollableAncestors:jt,scrollableAncestorRects:On,measuringConfiguration:K,measuringScheduled:ie,windowRect:Dn}),[Pe,me,Ae,fe,et,Et,ft,X,Ee,re,En,de,jt,On,K,ie,Dn]),be=N.useMemo(()=>({activatorEvent:fe,activators:le,active:Pe,activeNodeRect:Ae,ariaDescribedById:{draggable:he},dispatch:L,draggableNodes:X,over:En,measureDroppableContainers:de}),[fe,le,Pe,Ae,L,he,X,En,de]);return Ye.createElement(dm.Provider,{value:R},Ye.createElement(ic.Provider,{value:be},Ye.createElement(Hm.Provider,{value:Z},Ye.createElement(zm.Provider,{value:nn},g)),Ye.createElement(ME,{disabled:d?.restoreFocus===!1})),Ye.createElement($C,{...d,hiddenTextDescribedById:he}));function ve(){const Re=ht?.autoScrollEnabled===!1,xe=typeof f=="object"?f.enabled===!1:f===!1,je=j&&!Re&&!xe;return typeof f=="object"?{...f,enabled:je}:{enabled:je}}}),zE=N.createContext(null),jm="button",jE="Draggable";function UE(o){let{id:e,data:a,disabled:r=!1,attributes:i}=o;const l=ho(jE),{activators:u,activatorEvent:d,active:f,activeNodeRect:g,ariaDescribedById:m,draggableNodes:b,over:v}=N.useContext(ic),{role:S=jm,roleDescription:E="draggable",tabIndex:A=0}=i??{},T=f?.id===e,L=N.useContext(T?zm:zE),[M,R]=Zl(),[D,U]=Zl(),j=EE(u,e),P=uo(a);Ia(()=>(b.set(e,{id:e,key:l,node:M,activatorNode:D,data:P}),()=>{const ge=b.get(e);ge&&ge.key===l&&b.delete(e)}),[b,e]);const X=N.useMemo(()=>({role:S,tabIndex:A,"aria-disabled":r,"aria-pressed":T&&S===jm?!0:void 0,"aria-roledescription":E,"aria-describedby":m.draggable}),[r,S,A,T,E,m.draggable]);return{active:f,activatorEvent:d,activeNodeRect:g,attributes:X,isDragging:T,listeners:r?void 0:j,node:M,over:v,setNodeRef:R,setActivatorNodeRef:U,transform:L}}function BE(){return N.useContext(Hm)}const PE="Droppable",qE={timeout:25};function GE(o){let{data:e,disabled:a=!1,id:r,resizeObserverConfig:i}=o;const l=ho(PE),{active:u,dispatch:d,over:f,measureDroppableContainers:g}=N.useContext(ic),m=N.useRef({disabled:a}),b=N.useRef(!1),v=N.useRef(null),S=N.useRef(null),{disabled:E,updateMeasurementsFor:A,timeout:T}={...qE,...i},L=uo(A??r),M=N.useCallback(()=>{if(!b.current){b.current=!0;return}S.current!=null&&clearTimeout(S.current),S.current=setTimeout(()=>{g(Array.isArray(L.current)?L.current:[L.current]),S.current=null},T)},[T]),R=ac({callback:M,disabled:E||!u}),D=N.useCallback((X,ge)=>{R&&(ge&&(R.unobserve(ge),b.current=!1),X&&R.observe(X))},[R]),[U,j]=Zl(D),P=uo(e);return N.useEffect(()=>{!R||!U.current||(R.disconnect(),b.current=!1,R.observe(U.current))},[U,R]),N.useEffect(()=>(d({type:en.RegisterDroppable,element:{id:r,key:l,disabled:a,node:U,rect:v,data:P}}),()=>d({type:en.UnregisterDroppable,key:l,id:r})),[r]),N.useEffect(()=>{a!==m.current.disabled&&(d({type:en.SetDroppableDisabled,id:r,key:l,disabled:a}),m.current.disabled=a)},[r,l,a,d]),{active:u,rect:v,isOver:f?.id===r,node:U,over:f,setNodeRef:j}}function Qd(o,e,a){const r=o.slice();return r.splice(a<0?r.length+a:a,0,r.splice(e,1)[0]),r}function VE(o,e){return o.reduce((a,r,i)=>{const l=e.get(r);return l&&(a[i]=l),a},Array(o.length))}function sc(o){return o!==null&&o>=0}function FE(o,e){if(o===e)return!0;if(o.length!==e.length)return!1;for(let a=0;a{var e;let{rects:a,activeNodeRect:r,activeIndex:i,overIndex:l,index:u}=o;const d=(e=a[i])!=null?e:r;if(!d)return null;const f=YE(a,u,i);if(u===i){const g=a[l];return g?{x:ii&&u<=l?{x:-d.width-f,y:0,...oc}:u=l?{x:d.width+f,y:0,...oc}:{x:0,y:0,...oc}};function YE(o,e,a){const r=o[e],i=o[e-1],l=o[e+1];return!r||!i&&!l?0:a{let{rects:e,activeIndex:a,overIndex:r,index:i}=o;const l=Qd(e,r,a),u=e[i],d=l[i];return!d||!u?null:{x:d.left-u.left,y:d.top-u.top,scaleX:d.width/u.width,scaleY:d.height/u.height}},lc={scaleX:1,scaleY:1},XE=o=>{var e;let{activeIndex:a,activeNodeRect:r,index:i,rects:l,overIndex:u}=o;const d=(e=l[a])!=null?e:r;if(!d)return null;if(i===a){const g=l[u];return g?{x:0,y:aa&&i<=u?{x:0,y:-d.height-f,...lc}:i=u?{x:0,y:d.height+f,...lc}:{x:0,y:0,...lc}};function JE(o,e,a){const r=o[e],i=o[e-1],l=o[e+1];return r?ar.map(j=>typeof j=="object"&&"id"in j?j.id:j),[r]),E=u!=null,A=u?S.indexOf(u.id):-1,T=g?S.indexOf(g.id):-1,L=N.useRef(S),M=!FE(S,L.current),R=T!==-1&&A===-1||M,D=KE(l);Ia(()=>{M&&E&&m(S)},[M,S,E,m]),N.useEffect(()=>{L.current=S},[S]);const U=N.useMemo(()=>({activeIndex:A,containerId:b,disabled:D,disableTransforms:R,items:S,overIndex:T,useDragOverlay:v,sortedRects:VE(S,f),strategy:i}),[A,b,D.draggable,D.droppable,R,S,T,f,v,i]);return Ye.createElement(Bm.Provider,{value:U},e)}const ZE=o=>{let{id:e,items:a,activeIndex:r,overIndex:i}=o;return Qd(a,r,i).indexOf(e)},e_=o=>{let{containerId:e,isSorting:a,wasDragging:r,index:i,items:l,newIndex:u,previousItems:d,previousContainerId:f,transition:g}=o;return!g||!r||d!==l&&i===u?!1:a?!0:u!==i&&e===f},t_={duration:200,easing:"ease"},Pm="transform",n_=po.Transition.toString({property:Pm,duration:0,easing:"linear"}),a_={roleDescription:"sortable"};function r_(o){let{disabled:e,index:a,node:r,rect:i}=o;const[l,u]=N.useState(null),d=N.useRef(a);return Ia(()=>{if(!e&&a!==d.current&&r.current){const f=i.current;if(f){const g=ss(r.current,{ignoreTransform:!0}),m={x:f.left-g.left,y:f.top-g.top,scaleX:f.width/g.width,scaleY:f.height/g.height};(m.x||m.y)&&u(m)}}a!==d.current&&(d.current=a)},[e,a,r,i]),N.useEffect(()=>{l&&u(null)},[l]),l}function i_(o){let{animateLayoutChanges:e=e_,attributes:a,disabled:r,data:i,getNewIndex:l=ZE,id:u,strategy:d,resizeObserverConfig:f,transition:g=t_}=o;const{items:m,containerId:b,activeIndex:v,disabled:S,disableTransforms:E,sortedRects:A,overIndex:T,useDragOverlay:L,strategy:M}=N.useContext(Bm),R=s_(r,S),D=m.indexOf(u),U=N.useMemo(()=>({sortable:{containerId:b,index:D,items:m},...i}),[b,i,D,m]),j=N.useMemo(()=>m.slice(m.indexOf(u)),[m,u]),{rect:P,node:X,isOver:ge,setNodeRef:Ee}=GE({id:u,data:U,disabled:R.droppable,resizeObserverConfig:{updateMeasurementsFor:j,...f}}),{active:Ce,activatorEvent:$e,activeNodeRect:Pe,attributes:Xe,setNodeRef:ht,listeners:Q,isDragging:fe,over:ye,setActivatorNodeRef:te,transform:he}=UE({id:u,data:U,attributes:{...a_,...a},disabled:R.draggable}),x=wC(Ee,ht),K=!!Ce,re=K&&!E&&sc(v)&&sc(T),de=!L&&fe,ie=de&&re?he:null,Ne=re?ie??(d??M)({rects:A,activeNodeRect:Pe,activeIndex:v,overIndex:T,index:D}):null,Se=sc(v)&&sc(T)?l({id:u,items:m,activeIndex:v,overIndex:T}):D,He=Ce?.id,Ae=N.useRef({activeId:He,items:m,newIndex:Se,containerId:b}),Et=m!==Ae.current.items,kt=e({active:Ce,containerId:b,isDragging:fe,isSorting:K,id:u,index:D,items:m,newIndex:Ae.current.newIndex,previousItems:Ae.current.items,previousContainerId:Ae.current.containerId,transition:g,wasDragging:Ae.current.activeId!=null}),_t=r_({disabled:!kt,index:D,node:X,rect:P});return N.useEffect(()=>{K&&Ae.current.newIndex!==Se&&(Ae.current.newIndex=Se),b!==Ae.current.containerId&&(Ae.current.containerId=b),m!==Ae.current.items&&(Ae.current.items=m)},[K,Se,b,m]),N.useEffect(()=>{if(He===Ae.current.activeId)return;if(He!=null&&Ae.current.activeId==null){Ae.current.activeId=He;return}const un=setTimeout(()=>{Ae.current.activeId=He},50);return()=>clearTimeout(un)},[He]),{active:Ce,activeIndex:v,attributes:Xe,data:U,rect:P,index:D,newIndex:Se,items:m,isOver:ge,isSorting:K,isDragging:fe,listeners:Q,node:X,overIndex:T,over:ye,setNodeRef:x,setActivatorNodeRef:te,setDroppableNodeRef:Ee,setDraggableNodeRef:ht,transform:_t??Ne,transition:ft()};function ft(){if(_t||Et&&Ae.current.newIndex===D)return n_;if(!(de&&!Ud($e)||!g)&&(K||kt))return po.Transition.toString({...g,property:Pm})}}function s_(o,e){var a,r;return typeof o=="boolean"?{draggable:o,droppable:!1}:{draggable:(a=o?.draggable)!=null?a:e.draggable,droppable:(r=o?.droppable)!=null?r:e.droppable}}function cc(o){if(!o)return!1;const e=o.data.current;return!!(e&&"sortable"in e&&typeof e.sortable=="object"&&"containerId"in e.sortable&&"items"in e.sortable&&"index"in e.sortable)}const o_=[it.Down,it.Right,it.Up,it.Left],l_=(o,e)=>{let{context:{active:a,collisionRect:r,droppableRects:i,droppableContainers:l,over:u,scrollableAncestors:d}}=e;if(o_.includes(o.code)){if(o.preventDefault(),!a||!r)return;const f=[];l.getEnabled().forEach(b=>{if(!b||b!=null&&b.disabled)return;const v=i.get(b.id);if(v)switch(o.code){case it.Down:r.topv.top&&f.push(b);break;case it.Left:r.left>v.left&&f.push(b);break;case it.Right:r.left1&&(m=g[1].id),m!=null){const b=l.get(a.id),v=l.get(m),S=v?i.get(v.id):null,E=v?.node.current;if(E&&S&&b&&v){const T=tc(E).some((j,P)=>d[P]!==j),L=qm(b,v),M=c_(b,v),R=T||!L?{x:0,y:0}:{x:M?r.width-S.width:0,y:M?r.height-S.height:0},D={x:S.left,y:S.top};return R.x&&R.y?D:go(D,R)}}}};function qm(o,e){return!cc(o)||!cc(e)?!1:o.data.current.sortable.containerId===e.data.current.sortable.containerId}function c_(o,e){return!cc(o)||!cc(e)||!qm(o,e)?!1:o.data.current.sortable.index{const d=N.useId(),f=N.useRef({inProgress:!1,lastSortTime:0,lastActiveId:null}),g=NC(fm(Wd,{activationConstraint:{distance:5}}),fm(Fd,{coordinateGetter:l_})),m=N.useCallback(S=>{f.current={inProgress:!0,lastSortTime:Date.now(),lastActiveId:S.active.id},l?.({activeId:S.active.id})},[l]),b=N.useCallback(S=>{const{active:E,over:A}=S,T=Date.now();if(!A||E.id===A.id){f.current.inProgress=!1;return}const{lastSortTime:L,lastActiveId:M,inProgress:R}=f.current;if(M===E.id&&T-L<500&&!R)return;f.current={inProgress:!1,lastSortTime:T,lastActiveId:E.id};const D=o.findIndex(j=>String(j[e])===String(E.id)),U=o.findIndex(j=>String(j[e])===String(A.id));if(D!==-1&&U!==-1&&D!==U){const j=Qd(o,D,U);i?.(j,{oldIndex:D,newIndex:U})}},[o,e,i]),v=o.map(S=>String(S[e]));return ut.jsx(HE,{id:d,sensors:g,collisionDetection:HC,onDragStart:m,onDragEnd:b,children:ut.jsx(QE,{items:v,strategy:u_[a],children:r})},u!==void 0?`${d}-v${u}`:d)},Gm=N.createContext(null),f_=({value:o,children:e})=>ut.jsx(Gm.Provider,{value:o,children:e}),h_=()=>N.useContext(Gm),g_=({id:o,handle:e,as:a="div",children:r})=>{const{attributes:i,listeners:l,setNodeRef:u,transform:d,transition:f,isDragging:g}=i_({id:o}),m={transform:po.Transform.toString(d),transition:f,opacity:g?.5:1,position:"relative"};return ut.jsx(a,{ref:u,style:m,...i,...e?{}:l,"data-sortable-item":!0,"data-sortable-id":String(o),"data-dragging":g,children:ut.jsx(f_,{value:{listeners:l,handle:e,isDragging:g},children:r})})},dt=ct("DynamicRenderer");function Qa(){try{return window.G7Core?.devTools}catch{return}}function ef(o,e,a,r){if(typeof o=="string"){if(/\$t:[a-zA-Z_][a-zA-Z0-9_.\-]*/.test(o))try{return e.resolveTranslations(o,a,r)}catch{return o}return o}if(Array.isArray(o))return o.map(i=>ef(i,e,a,r));if(o&&typeof o=="object"){const i={};for(const[l,u]of Object.entries(o))i[l]=ef(u,e,a,r);return i}return o}function p_(o){const e=Object.keys(o);return e.length>0&&e.every(a=>/^\d+$/.test(a))}const ya=(o,e)=>{const a=["errors"],r={...o};for(const i of Object.keys(e)){const l=e[i],u=o[i];if(l===null){r[i]=null;continue}if(a.includes(i)){r[i]=l;continue}if(Array.isArray(l)){r[i]=l;continue}if(Array.isArray(u)&&l!==null&&typeof l=="object"&&!Array.isArray(l)&&p_(l)){const d=Object.keys(l).map(g=>parseInt(g,10));if((d.length>0?Math.max(...d):0)>=u.length+d.length+10)r[i]={...l};else{const g=[...u];for(const[m,b]of Object.entries(l)){const v=parseInt(m,10);v>=0&&v=g.length&&(g[v]=b)}r[i]=g}}else l!==null&&typeof l=="object"&&u!==null&&typeof u=="object"&&!Array.isArray(u)?r[i]=ya(u,l):r[i]=l}return r},Vm=(o,e)=>{const a={...o};for(const r of Object.keys(e)){if(!(r in a))continue;const i=e[r],l=a[r];if(i!==null&&typeof i=="object"&&!Array.isArray(i)&&l!==null&&typeof l=="object"&&!Array.isArray(l)){const u=Vm(l,i);Object.keys(u).length===0?delete a[r]:a[r]=u}else delete a[r]}return a},m_=o=>{const e={},a=o.split(";").filter(r=>r.trim());for(const r of a){const i=r.indexOf(":");if(i===-1)continue;const l=r.substring(0,i).trim(),u=r.substring(i+1).trim();if(l&&u){const d=l.replace(/-([a-z])/g,(f,g)=>g.toUpperCase());e[d]=u}}return e};class y_ extends N.Component{constructor(e){super(e),this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,a){dt.error(`컴포넌트 렌더링 에러 (ID: ${this.props.componentId}, Name: ${this.props.componentName}):`,e,a)}render(){return this.state.hasError?this.props.fallback?this.props.fallback:ut.jsxs("div",{className:"p-4 my-2 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg text-red-800 dark:text-red-400",children:[ut.jsx("div",{className:"font-semibold mb-1",children:"컴포넌트 로드 실패"}),ut.jsxs("div",{className:"text-xs opacity-80",children:[this.props.componentName&&`[${this.props.componentName}] `,"데이터를 표시할 수 없습니다."]}),this.state.error&&ut.jsxs("details",{className:"mt-2",children:[ut.jsx("summary",{className:"cursor-pointer text-xs opacity-70 hover:opacity-100",children:"상세 정보"}),ut.jsx("div",{className:"mt-1 p-2 bg-red-100 dark:bg-red-900/30 rounded text-xs font-mono whitespace-pre-wrap break-all",children:this.state.error.message})]})]}):this.props.children}}const Ha=N.memo(({componentDef:o,dataContext:e,translationContext:a,registry:r,bindingEngine:i,translationEngine:l,actionDispatcher:u,parentComponentContext:d,parentFormContextProp:f,parentDataContext:g,isRootRenderer:m=!1,isInsideIteration:b=!1,isEditMode:v=!1,onComponentSelect:S,onComponentHover:E,onDragStart:A,onDragEnd:T,componentPath:L,layoutKey:M})=>{const[R,D]=N.useState({loadingActions:{}});N.useLayoutEffect(()=>{d||(i.startRenderCycle(),window.__g7SetLocalOverrideKeys||(window.__g7ForcedLocalFields=void 0),window.__g7PendingLocalState=null)});const U=N.useRef(null);N.useLayoutEffect(()=>{if(!d&&e._localInit&&typeof e._localInit=="object"){const{_forceLocalInit:q,_merge:ce,...le}=e._localInit,Z=`${JSON.stringify(le)}:${q||"no-force"}`;if(U.current!==Z){U.current=Z;const be=ce||"shallow",Re=window.G7Core?.state?.get?.()?._local||{},xe=window.__g7PendingLocalState||{},je={...Re,...xe};be==="replace"?window.__g7PendingLocalState={loadingActions:je.loadingActions||{},...le,hasChanges:!1}:be==="deep"?window.__g7PendingLocalState=ya(je,{...le,hasChanges:!1}):window.__g7PendingLocalState={...je,...le,hasChanges:!1};const ze=window.__g7SetLocalOverrideKeys;ze&&typeof ze=="object"&&(be==="replace"?window.__g7SetLocalOverrideKeys={...le,hasChanges:!1}:window.__g7SetLocalOverrideKeys=ya(ze,{...le,hasChanges:!1}))}}}),N.useLayoutEffect(()=>{if(!d){const q=window.__g7SetLocalOverrideKeys;if(q){D(be=>Vm(be,q));const ce=q,le=window.__g7ForcedLocalFields,Z=window.__g7LastSetLocalSnapshot;queueMicrotask(()=>{window.__g7SetLocalOverrideKeys===ce&&(window.__g7SetLocalOverrideKeys=void 0),window.__g7ForcedLocalFields===le&&(window.__g7ForcedLocalFields=void 0),window.__g7LastSetLocalSnapshot===Z&&(window.__g7LastSetLocalSnapshot=void 0)})}}},[e._local]);const j=N.useRef(M);N.useEffect(()=>{o._fromBase&&M&&j.current!==M&&(j.current=M,D({loadingActions:{}}))},[M,o._fromBase]);const P=N.useRef(""),X=N.useRef(!1),ge=N.useRef(null),Ee=N.useRef({}),Ce=N.useRef({}),$e=N.useRef(g),Pe=SC(),Xe=Q0(),ht=Xe?.getParentDataContext()??g;N.useEffect(()=>{if(e._localInit&&typeof e._localInit=="object"){const{_forceLocalInit:q,...ce}=e._localInit,le=JSON.stringify(ce),Z=q!==void 0,be=Ld(),ve=`${le}:${q||"no-force"}`;if(be.hash!==ve){be.hash=ve,be.timestamp=q,P.current=le,Z&&(X.current=!0);const{_merge:je,...ze}=ce,Le=je||"shallow";if(D(ke=>Le==="replace"?{loadingActions:ke.loadingActions||{},...ze,hasChanges:!1}:Le==="deep"?ya(ke,{...ze,hasChanges:!1}):{...ke,...ze,hasChanges:!1}),e._globalSetState){const ke=e._global?._local||{};let We;Le==="replace"?We={...ze,hasChanges:!1}:Le==="deep"?We=ya(ke,{...ze,hasChanges:!1}):We={...ke,...ze,hasChanges:!1},e._globalSetState({_local:We})}i.invalidateCacheByKeys(["_local"]),dt.log("_localInit applied (data changed):",Object.keys(ce))}ge.current=e._localInit,aC(e._localInit)}},[e._localInit,g,i]);const{isTransitioning:Q}=nm(),fe=dC(),ye=f??fe,{width:te}=$d(),he=h_(),x=N.useMemo(()=>{let q=o;if(o.type==="iterator"&&o.data){const{data:Z,itemName:be,indexName:ve,...Re}=o;q={...Re,iteration:{source:Z,item_var:be||"item",index_var:ve}}}if(!q.responsive)return q;const ce=ui.getMatchingKey(q.responsive,te);if(!ce)return q;const le=q.responsive[ce];return{...q,props:{...q.props,...le.props},children:le.children??q.children,text:le.text??q.text,if:le.if??q.if,iteration:le.iteration??q.iteration,__responsiveChildrenKey:le.children!==void 0?ce:void 0}},[o,te]),K=N.useCallback(q=>{const ce=q?.__setStateId;if(D(le=>{const Z=window.__g7PendingLocalState,ve=window.__g7SetLocalOverrideKeys||Z,Re=ve?ya(le,ve):le;if(typeof q=="function"){const ke=q(Re);return ya(Re,ke)}const{__mergeMode:xe,__setStateId:je,...ze}=q;let Le;if(xe==="replace"?Le=ze:xe==="shallow"?Le={...Re,...ze}:Le=ya(Re,ze),xe!==void 0){const ke=window.__g7ForcedLocalFields;ke&&(window.__g7ForcedLocalFields={...ke,...ze})}return Le}),ce){const le=Qa();if(le?.isEnabled()){const Z=x.id||"unknown",be=x.name||"Unknown";setTimeout(()=>{le.trackComponentRender?.(Z,be,0,["_local"],[]),le.completeStateChange?.(ce)},0)}}},[x.id,x.name]),re=d?.state??R,de=d?.setState??K,ie=N.useMemo(()=>{const q=e._localInit&&e._localInit!==ge.current;let ce;q&&e._local?ce=e._local:ce=e._local?ya(e._local,re):re;const le=window.__g7ForcedLocalFields;le&&(ce=ya(ce,le));const Z={...e,_local:ce},be=e._computedDefinitions;if(be&&Object.keys(be).length>0){const ve=new wn,Re={...Z,...Pe?{_isolated:Pe.state}:{}},xe={},je=Qa(),ze=je?.isEnabled()??!1;for(const[Le,ke]of Object.entries(be)){const We=ze?Date.now():0,Fe=ze?e._computed?.[Le]:void 0;let _e;try{if(typeof ke=="string")if(ke.startsWith("{{")&&ke.endsWith("}}")){const Te=ke.slice(2,-2).trim(),Ue=ve.evaluateExpression(Te,Re,{skipCache:!0});xe[Le]=Ue}else xe[Le]=ke;else if(ke&&typeof ke=="object"&&"$switch"in ke){const Te=ve.resolveSwitch(ke,Re,{skipCache:!0});xe[Le]=Te}}catch(Te){dt.warn(`Failed to recalculate computed value: ${Le}`,Te),xe[Le]=e._computed?.[Le],_e=Te instanceof Error?Te.message:String(Te)}if(ze&&(_e||Fe!==xe[Le])){const Ue=Date.now()-We;je.trackComputedProperty?.(Le,typeof ke=="string"?ke:JSON.stringify(ke),[{type:"_local",path:"_local",value:Z._local}],xe[Le],Ue,x.id,_e),Fe!==xe[Le]&&je.trackComputedRecalc?.(Le,"dependency-change",Fe,xe[Le],Ue,{type:"_local",path:"_local"},x.id)}}Z._computed=xe}if(Pe&&(Z._isolated=Pe.state),ht&&(Z.$parent=ht),o.extensionPointProps){const ve=i.resolveObject(o.extensionPointProps,Z,b?{skipCache:!0}:void 0);Z.extensionPointProps=v&&l?ef(ve,l,a,Z):ve}return o.extensionPointCallbacks&&(Z.extensionPointCallbacks=o.extensionPointCallbacks),v&&(Z.$templateId===void 0&&a?.templateId&&(Z.$templateId=a.templateId),Z.$locale===void 0&&a?.locale&&(Z.$locale=a.locale)),Z},[e,re,Pe?.state,ht,Xe?.version,o.extensionPointProps,o.extensionPointCallbacks]);Ee.current=ie._local,Ce.current=ie._computed||{},$e.current=ht,N.useEffect(()=>{const q=Qa();if(!q?.isEnabled())return;const ce=ie._local;ce&&q.updateLocalState(ce);const le=ie._computed;le&&q.updateComputedState(le),ht&&q.updateParentContext?.(ht);const Z=x.id||`comp-${Date.now()}`,be=x.name||"Unknown",ve={global:Object.keys(e._global||{}),local:Object.keys(ce||{}),context:d?Object.keys(d.state||{}):[]},Re={type:d?"componentContext":"dynamicState",hasComponentContext:!!d,parentId:d?"parent":void 0};q.trackComponentStateSource?.(Z,be,ve,Re),re&&Object.keys(re).length>0&&q.trackDynamicState?.(Z,re);const xe=!!(x.expandChildren||x.props?.expandChildren);q.trackContextFlow?.(Z,be,!!d,xe,!0)},[ie._local,e,x.id,x.name,d,re,x.expandChildren,x.props?.expandChildren,ht]);const me=N.useMemo(()=>({state:{...ie._local},setState:de,stateRef:Ee,computedRef:Ce,isolatedContext:Pe,parentDataContext:ie}),[ie._local,de,R,Pe,ie]),Ne=N.useMemo(()=>{const q=Xi({if:x.if,condition:x.condition,conditions:x.conditions},ie,i,x.id);if(x.if||x.condition!==void 0||x.conditions){const le=Qa();le?.isEnabled()&&x.if&&le.trackIfCondition(x.id||`if-${Date.now()}`,x.if,q)}return q},[x.if,x.conditions,ie,i,x.id]),Se=N.useMemo(()=>{if(!x.slot)return null;const q=x.slot;if(q.startsWith("{{")&&q.endsWith("}}")){const ce=q.slice(2,-2).trim();try{const le={componentId:x.id,componentName:x.name,propName:"slot"},Z=i.evaluateExpression(ce,ie,le);return dt.log(`[Slot] 표현식 평가: "${ce}" => "${Z}" (컴포넌트: ${x.id})`),typeof Z=="string"?Z:null}catch(le){return dt.warn(`slot 표현식 평가 실패 (컴포넌트: ${x.id}):`,le),null}}return dt.log(`[Slot] 정적 슬롯 ID: "${q}" (컴포넌트: ${x.id})`),q},[x.slot,x.id,ie,i]),He=N.useMemo(()=>!Se||!x.id?"":`${x.id}-${Se}-${JSON.stringify(x.slotOrder??0)}`,[Se,x.id,x.slotOrder]),Ae=N.useRef(null);N.useEffect(()=>{const q=window.__slotContextValue,ce=q?.isEnabled??!1;if(x.slot&&dt.log(`[Slot Registration] 컴포넌트: ${x.id}, isSlotEnabled: ${ce}, shouldRender: ${Ne}, resolvedSlotId: ${Se}`),!ce||!Ne){x.slot&&dt.log(`[Slot Registration] 등록 스킵 - isSlotEnabled: ${ce}, shouldRender: ${Ne}`),Ae.current&&x.id&&q&&(q.unregisterFromSlot(Ae.current,x.id),Ae.current=null);return}if(!Se||!x.id){x.slot&&dt.log(`[Slot Registration] 등록 스킵 - resolvedSlotId: ${Se}, id: ${x.id}`),Ae.current&&x.id&&q&&(q.unregisterFromSlot(Ae.current,x.id),Ae.current=null);return}Ae.current&&Ae.current!==Se&&q.unregisterFromSlot(Ae.current,x.id);const le={...x,slot:void 0,slotOrder:void 0};return q.registerToSlot(Se,x.id,{componentDef:le,dataContext:e,order:x.slotOrder??0,parentFormContext:f??null,getParentComponentContext:()=>me,translationContext:a,registrationKey:He}),Ae.current=Se,()=>{const Z=window.__slotContextValue;Se&&x.id&&Z&&Z.unregisterFromSlot(Se,x.id)}},[Ne,Se,x,e,f,me,a,He]);const Et=N.useCallback(q=>{if(typeof q=="string"){if(rp(q))return sp(q);if(ip(q)){const ce=[],le=q.replace(new RegExp(`${Rl}([^${Ys}]*)${Ys}`,"g"),(be,ve)=>(ce.push(ve),`${_r}${ce.length-1}${_r}`));let Z=le;return/\$t:[a-zA-Z0-9._-]+/.test(le)&&(Z=l.resolveTranslations(le,a,ie)),Z.replace(new RegExp(`${_r}(\\d+)${_r}`,"g"),(be,ve)=>ce[parseInt(ve)])}if(q.startsWith("$t:defer:"))return q;if(/\$t:[a-zA-Z0-9._-]+/.test(q)){const ce=q.trim();return ce.startsWith("{")&&ce.endsWith("}")||ce.startsWith("[")&&ce.endsWith("]")?q:l.resolveTranslations(q,a,ie)}return q}if(Array.isArray(q))return q.map(ce=>Et(ce));if(q&&typeof q=="object"){const ce={};for(const[le,Z]of Object.entries(q))ce[le]=Et(Z);return ce}return q},[l,a,ie]),kt=N.useCallback(q=>/[?:|&!+\-*/<>=()]/.test(q),[]),_t=N.useCallback(q=>{if(!q.startsWith("{{")||!q.endsWith("}}"))return null;const ce=q.slice(2,-2);let le=null,Z=0;for(let be=0;be0?ce[be-1]:"")!=="\\"&&((ve==='"'||ve==="'")&&!le?le=ve:ve===le&&(le=null),!le&&(ve==="{"&&Z++,ve==="}"&&Z--,Z<0)))return null}return Z===0?ce.trim():null},[]),ft=N.useMemo(()=>{let q={...x.props||{}};const ce=["cellChildren","expandChildren","expandContext","render"],Z=r.getMetadata(x.name)?.skipBindingKeys||[],be=[...new Set([...ce,...Z])],ve=b?{skipCache:!0}:void 0,Re=_e=>{if(ve)return ve;if(_e.startsWith("_computed")||_e.startsWith("$computed"))return{skipCache:!0}};for(const[_e,Te]of Object.entries(q))if(!be.includes(_e))if(typeof Te=="string"){const Ue=_t(Te);if(Ue!==null){let st=!1,At=Ue;Ue.startsWith(Er)&&(st=!0,At=Ue.slice(Er.length));const Wt={componentId:x.id,componentName:x.name,propName:_e};let qt;if(ci(At))qt=i.resolveBindings(`{{${At}}}`,ie,ve,Wt);else if(kt(At))try{qt=i.evaluateExpression(At,ie,Wt)}catch(qn){dt.warn(`표현식 평가 실패 (컴포넌트: ${x.id}, prop: ${_e}):`,qn),qt=void 0}else qt=i.resolve(At,ie,Re(At),Wt);q[_e]=st&&qt!=null?Js(qt):qt}else{const st={componentId:x.id,componentName:x.name,propName:_e};q[_e]=i.resolveBindings(Te,ie,ve,st)}}else Array.isArray(Te)?q[_e]=Te.map(Ue=>typeof Ue=="string"?i.resolveBindings(Ue,ie,ve):typeof Ue=="object"&&Ue!==null?i.resolveObject(Ue,ie,ve):Ue):Te&&typeof Te=="object"&&(q[_e]=i.resolveObject(Te,ie,ve));for(const[_e,Te]of Object.entries(q))q[_e]=Et(Te);if(typeof q.style=="string"&&(q.style=m_(q.style)),q=ld(q,v?void 0:x.actions,ie,{componentContext:me,actionDispatcher:u}),x.classMap){const _e=ow(x.classMap,ie,i,{skipCache:!0});if(_e){const Te=q.className||"";q.className=Te?`${Te} ${_e}`:_e}}x.style&&(q.style=x.style),x.actions&&x.actions.length>0&&x.type==="composite"&&Object.assign(q,re),x.component_layout&&(q.__componentLayoutDefs=x.component_layout);const xe=x.expandChildren||x.props?.expandChildren,je=x.props?.cellChildren,ze=x.children&&x.children.length>0,Le=x.component_layout,ke=x.slot,We=x.props?.modalId,Fe=x.type==="composite";return(xe||je||ze||Le||ke||We||Fe)&&(q.__componentContext=me),q},[x.props,x.actions,x.style,x.classMap,x.id,ie,a,i,l,me,re,Et,kt,_t,b]),un=N.useRef(null),gt=N.useMemo(()=>un.current&&rm(un.current,ft)?un.current:(un.current=ft,ft),[ft]),ja=N.useMemo(()=>{const q=x.id;if(typeof q!="string"||!q.includes("{{"))return q;const ce=i.resolveBindings(q,ie,{skipCache:!0});return typeof ce=="string"?ce:q},[x.id,ie,i]),kn=N.useMemo(()=>{const q=x.dataKey,ce=x.trackChanges,le=x.debounce;if(q){const Z=q.startsWith("_global."),be=Z?q.slice(8):q,ve=Z?e._global:ie._local;return{dataKey:be,trackChanges:ce??!1,debounce:le,setState:Z?xe=>{e._globalSetState?e._globalSetState(xe):dt.warn("_global.formData 사용 시 _globalSetState가 필요합니다.")}:de,state:ve??{},_isGlobal:Z}}if(ye.dataKey)return ye},[x.dataKey,x.trackChanges,x.debounce,x.id,de,ie._local,e._global,e._globalSetState,ye]),Dn=N.useRef(new Set);N.useEffect(()=>{Dn.current.clear()},[e._global?._remountKeys]);const jt=N.useCallback((q,ce)=>{const le=e._global?._remountKeys;return q&&le?.[q]&&!Dn.current.has(q)?(Dn.current.add(q),`${q}-remount-${le[q]}`):q||ce},[e._global?._remountKeys]),On=N.useMemo(()=>{if(x.text!==void 0){if(typeof x.text=="string"){const q=x.text;let ce=q;const le={componentId:x.id,componentName:x.name,propName:"text",skipCache:!0},Z=_t(q);if(Z!==null)if(ci(Z))ce=i.resolveBindings(q,ie,{skipCache:!0},le);else if(kt(Z))try{ce=i.evaluateExpression(Z,ie,le)}catch(be){dt.warn(`text 표현식 평가 실패 (컴포넌트: ${x.id}):`,be),ce=""}else ce=i.resolve(Z,ie,{skipCache:!0},le);else q.includes("{{")&&(ce=i.resolveBindings(q,ie,{skipCache:!0},le));return ce=Et(ce),ce??""}return x.text}return!x.children||x.children.length===0?null:x.children.map((q,ce)=>{if(typeof q=="string")return q;const le=x.__responsiveChildrenKey,Z=le?`responsive.${le}.children`:"children",be=L?`${L}.${Z}.${ce}`:`${ce}`,ve=q._fromBase?q.id||`child-${ce}`:jt(q.id,`child-${ce}`),Re=!q._fromBase&&M?`${ve}_${M}`:ve;return ut.jsx(Ha,{componentDef:q,dataContext:ie,translationContext:a,registry:r,bindingEngine:i,translationEngine:l,actionDispatcher:u,parentComponentContext:me,parentFormContextProp:kn,isInsideIteration:b,isEditMode:v,onComponentSelect:S,onComponentHover:E,componentPath:be,onDragStart:A,onDragEnd:T,layoutKey:M},Re)})},[x.text,x.children,x.id,e,ie,a,r,i,l,u,me,kn,_t,kt,Et,jt,b,v,S,E,L,A,T,M]),ea=N.useMemo(()=>{if(!x.iteration)return null;try{const q=od(x.iteration.source,ie,i);if(!Array.isArray(q))return dt.warn(`iteration source가 배열이 아닙니다 (컴포넌트: ${x.id}):`,q),null;const ce=Qa();return ce?.isEnabled()&&ce.trackIteration(x.id||`iteration-${Date.now()}`,x.iteration.source,x.iteration.item_var,x.iteration.index_var,q.length),q.map((le,Z)=>{const be={...ie,[x.iteration.item_var]:le};x.iteration.index_var&&(be[x.iteration.index_var]=Z);const ve=Z===0||Z===q.length-1;ce?.isEnabled()&&ve&&ce.trackNestedContext?.({componentId:`${x.id||"unknown"}-iter-${Z}`,componentType:"iteration",parentContext:{available:Object.keys(ie),values:{}},ownContext:{added:[x.iteration.item_var,...x.iteration.index_var?[x.iteration.index_var]:[]],values:{[x.iteration.item_var]:le,...x.iteration.index_var?{[x.iteration.index_var]:Z}:{}}},depth:1});const Re={...x,iteration:void 0,responsive:void 0},xe=L?`${L}.iteration.${Z}`:`iteration.${Z}`,je=`${jt(x.id,"item")}-${Z}`;return ut.jsx(Ha,{componentDef:Re,dataContext:be,translationContext:a,registry:r,bindingEngine:i,translationEngine:l,actionDispatcher:u,parentComponentContext:me,parentFormContextProp:kn,isInsideIteration:!0,isEditMode:v,onComponentSelect:S,onComponentHover:E,componentPath:xe,onDragStart:A,onDragEnd:T,layoutKey:M},je)})}catch(q){return dt.error(`iteration 렌더링 실패 (컴포넌트: ${x.id}):`,q),null}},[x.iteration,x.children,x.id,e,ie,a,r,i,l,u,me,kn,jt,v,S,E,L,A,T,M]),[Ua,Kt]=N.useState(0),Dr=N.useMemo(()=>{if(!x.sortable||!x.itemTemplate)return null;const{sortable:q,itemTemplate:ce}=x;try{const le=od(q.source,ie,i);if(!Array.isArray(le))return dt.warn(`sortable source가 배열이 아닙니다 (컴포넌트: ${x.id}):`,le),null;if(le.length===0)return null;const Z=q.itemKey||"id",be=q.strategy||"verticalList",ve=q.itemVar||"$item",Re=q.indexVar||"$index",xe=q.handle,je=q.wrapperElement,ze=(We,Fe)=>{const _e=x.actions?.filter(Te=>Te.event==="onSortEnd"||Te.type==="onSortEnd");if(Kt(Te=>Te+1),_e&&_e.length>0&&u){const Te={...ie,$sortedItems:We,$sortEvent:Fe};_e.forEach(Ue=>{try{const st=u.createHandler(Ue,Te,me),At=new Event("sortend");st(At)}catch(st){dt.error(`onSortEnd action failed: ${Ue.handler}`,st)}})}},Le=We=>{const Fe=x.actions?.filter(_e=>_e.event==="onSortStart"||_e.type==="onSortStart");if(Fe&&Fe.length>0&&u){const _e={...ie,$activeId:We.activeId};Fe.forEach(Te=>{try{const Ue=u.createHandler(Te,_e,me),st=new Event("sortstart");Ue(st)}catch(Ue){dt.error(`onSortStart action failed: ${Te.handler}`,Ue)}})}},ke=le.map((We,Fe)=>{const _e=String(We[Z]),Te={...ie,[ve]:We,[Re]:Fe},Ue=L?`${L}.sortable.${Fe}`:`sortable.${Fe}`,st=`${jt(x.id,"sortable-item")}-v${Ua}-${_e}`;return ut.jsx(g_,{id:_e,handle:xe,...je?{as:je}:{},children:(je&&ce.children?ce.children:[ce]).map((At,Wt)=>ut.jsx(Ha,{componentDef:At,dataContext:Te,translationContext:a,registry:r,bindingEngine:i,translationEngine:l,actionDispatcher:u,parentComponentContext:me,parentFormContextProp:void 0,isInsideIteration:!0,isEditMode:v,onComponentSelect:S,onComponentHover:E,componentPath:Ue,onDragStart:A,onDragEnd:T,layoutKey:M},`${st}-child-${Wt}`))},st)});return ut.jsx(d_,{items:le,itemKey:Z,strategy:be,onSortEnd:ze,onSortStart:Le,sortVersion:Ua,children:ke})}catch(le){return dt.error(`sortable 렌더링 실패 (컴포넌트: ${x.id}):`,le),null}},[x.sortable,x.itemTemplate,x.actions,x.id,e,ie,a,r,i,l,u,me,jt,v,S,E,L,A,T,Ua,M]),er=N.useRef(!1);N.useEffect(()=>{if(er.current)return;er.current=!0;const q=Qa();if(q?.isEnabled()&&q.trackMount(o.id,{name:o.name,type:o.type||"component",props:gt}),o.lifecycle?.onMount&&o.lifecycle.onMount.length>0)for(const le of o.lifecycle.onMount)try{const Z=u.createHandler(le,ie,me),be=new Event("mount");Z(be),dt.log(`Lifecycle onMount executed: ${le.handler} (Component: ${o.id})`)}catch(Z){dt.error(`Lifecycle onMount failed: ${le.handler} (Component: ${o.id})`,Z)}const ce=[];if(o.onComponentEvent&&o.onComponentEvent.length>0){const le=window.G7Core;if(le?.componentEvent?.on)for(const Z of o.onComponentEvent){if(!Z.event){dt.warn(`onComponentEvent: event name is required (Component: ${o.id})`);continue}const be=async Re=>{try{const xe={...ie,_eventData:Re},ze=await u.createHandler({handler:Z.handler,params:Z.params,onSuccess:Z.onSuccess,onError:Z.onError},xe,me)(new CustomEvent(Z.event,{detail:Re}));return dt.log(`onComponentEvent "${Z.event}" handled: ${Z.handler} (Component: ${o.id})`,{eventData:Re,result:ze}),ze}catch(xe){throw dt.error(`onComponentEvent "${Z.event}" failed: ${Z.handler} (Component: ${o.id})`,xe),xe}},ve=le.componentEvent.on(Z.event,be);ce.push(ve),dt.log(`onComponentEvent: Subscribed to "${Z.event}" (Component: ${o.id})`)}else dt.warn(`onComponentEvent: G7Core.componentEvent is not available (Component: ${o.id})`)}return()=>{const le=Qa();le?.isEnabled()&&le.trackUnmount(o.id);for(const Z of ce)try{Z()}catch(be){dt.error(`onComponentEvent: Failed to unsubscribe (Component: ${o.id})`,be)}if(ce.length>0&&dt.log(`onComponentEvent: Unsubscribed ${ce.length} event(s) (Component: ${o.id})`),o.lifecycle?.onUnmount&&o.lifecycle.onUnmount.length>0)for(const Z of o.lifecycle.onUnmount)try{const be=u.createHandler(Z,ie,me),ve=new Event("unmount");be(ve),dt.log(`Lifecycle onUnmount executed: ${Z.handler} (Component: ${o.id})`)}catch(be){dt.error(`Lifecycle onUnmount failed: ${Z.handler} (Component: ${o.id})`,be)}}},[]);const bn=N.useMemo(()=>{const q=gt.dataKey,ce=gt.trackChanges,le=gt.debounce;return q?{dataKey:q,trackChanges:ce??!1,debounce:le,setState:de,state:re}:null},[gt.dataKey,gt.trackChanges,gt.debounce,de,re]);N.useEffect(()=>{const q=x.dataKey||gt.dataKey;if(!q)return;const ce=Qa();if(!ce?.isEnabled())return;const le=[],Z=ve=>{if(ve)for(const Re of ve){const xe=Re?.props?.name;if(xe&&le.push({name:xe,type:Re.name||Re.type||"unknown"}),Re?.children&&Z(Re.children),Re?.slots)for(const je of Object.values(Re.slots))Array.isArray(je)&&Z(je)}};if(o.children&&Z(o.children),o.slots)for(const ve of Object.values(o.slots))Array.isArray(ve)&&Z(ve);const be=o.id||`form-${q}`;return ce.trackForm(be,q,le),()=>{ce.untrackForm(be)}},[x,gt.dataKey,o.id,o.children]);const tn=N.useRef(null),et=N.useRef(void 0);N.useEffect(()=>{const q=gt?.name;if(!q||!ye.dataKey||!ye.setState||gt?.autoBinding===!1)return;const ce=`${ye.dataKey}.${q}`,le=window.__g7AutoBindingPaths??new Map;return window.__g7AutoBindingPaths=le,le.set(ce,(le.get(ce)??0)+1),()=>{const Z=le.get(ce)??0;Z<=1?le.delete(ce):le.set(ce,Z-1)}},[gt?.name,gt?.autoBinding,ye.dataKey,ye.setState]);const ta=N.useMemo(()=>{const{dataKey:q,trackChanges:ce,debounce:le,...Z}=gt,be=Z.name;if(!be||!ye.dataKey||!ye.setState)return Z;if(Z.autoBinding===!1){const{autoBinding:_e,...Te}=Z;return Te}const ve=`${ye.dataKey}.${be}`,Re=fC(ye.state,ve),xe=Re!==void 0?Re:Z.value,ze=r.getMetadata(o.name)?.bindingType,Le=typeof xe=="boolean"&&(ze==="checked"||ze==="checkable"&&["checkbox","radio"].includes(Z?.type)),ke=ye.debounce,We=_e=>{const Te=ye.state||{},Ue=hC(Te,ve,_e);if(ye.trackChanges&&(Ue.hasChanges=!0),window.__g7PendingLocalState=Ue,ye.setState(Ue),ye._isGlobal)return;const st=window.G7Core,At={[ve]:_e};ye.trackChanges&&(At.hasChanges=!0),st?.state?.setLocal?.(At,{render:!1})},Fe=(_e,Te)=>{ke&&ke>0?(tn.current&&clearTimeout(tn.current),tn.current=setTimeout(()=>{We(_e),tn.current=null,Te&&(Te(),window.__g7PendingLocalState=null)},ke)):(We(_e),Te&&(Te(),window.__g7PendingLocalState=null))};if(Le)return{...Z,checked:xe,onChange:Te=>{const Ue=Te.target.checked;We(Ue),Z.onChange&&Z.onChange(Te)}};{const _e=Ue=>{const st=Ue?.target?.value!==void 0?Ue.target.value:Ue;ke&&ke>0&&(et.current=st);const At=Ue?.target?{target:{value:st,name:Ue.target.name,type:Ue.target.type,checked:Ue.target.checked},currentTarget:Ue.currentTarget?{value:st,name:Ue.currentTarget.name}:void 0}:Ue;Fe(st,()=>{Z.onChange&&Z.onChange(At)})};let Te;return et.current!==void 0?tn.current!==null?Te=et.current:String(xe??"")===String(et.current)?(et.current=void 0,Te=xe??""):Te=et.current:Te=xe??"",{...Z,value:Te,onChange:_e}}},[gt,ye,ye.state,ye.debounce]),En=N.useMemo(()=>{const q=Qa();if(q?.isEnabled()&&q.trackRender(o.name),!Ne)return null;if(x.sortable&&x.itemTemplate)return Dr;if(x.iteration)return ea;if(x.type==="extension_point"){const{layout:ze,columns:Le,gap:ke,className:We,...Fe}=x.props||{};let _e=We||"";return ze==="grid"&&Le?_e=`${_e} grid grid-cols-${Le} gap-${ke||4}`.trim():ze==="flex"&&(_e=`${_e} flex flex-col gap-${ke||4}`.trim()),ut.jsx("div",{id:ja,className:_e||void 0,...Fe,children:On})}const ce=r.getComponent(x.name);if(!ce)return dt.error(`컴포넌트를 찾을 수 없습니다: ${x.name} (ID: ${x.id})`,"componentDef:",JSON.stringify(x,null,2)),null;const le=e._global?._remountKeys,Z={...ta,id:ta.id??ja,...le&&Object.keys(le).length>0&&{__remountTrigger:JSON.stringify(le)}};if(he?.listeners&&he.handle&&ta["data-drag-handle"]!==void 0&&(Object.assign(Z,he.listeners),Z.style={...Z.style,cursor:he.isDragging?"grabbing":"grab"}),v){const ze=x.id||`auto_${x.name||x.type||"unknown"}_${Math.random().toString(36).substring(2,8)}`,Le=Fe=>{typeof Fe.preventDefault=="function"&&Fe.preventDefault(),S&&(Fe.stopPropagation(),S(ze,Fe))},ke={"data-editor-id":ze,"data-editor-name":x.name,"data-editor-type":x.type,onClick:Le};L&&(ke["data-editor-path"]=L);const We=x.__editorSlotName??x.slot;typeof We=="string"&&(ke["data-editor-slot"]=We),E&&(ke.onMouseMove=Fe=>{Fe.stopPropagation(),E(ze,Fe)},ke.onMouseLeave=Fe=>{E(null,Fe)}),Object.assign(Z,ke),Z.editorAttrs=ke}const be=x.type==="basic",ve=x.type==="layout",xe=be||ve?(()=>{const ze={};for(const[Le,ke]of Object.entries(Z))Le.startsWith("__")||Le==="editorAttrs"&&be||(ze[Le]=ke);return ze})():Z;let je=ut.jsx(ce,{...xe,children:On});if(kn&&(je=ut.jsx(uC,{value:kn,children:je})),x.isolatedState){const ze=typeof x.isolatedState=="object"?x.isolatedState:{},Le=e?._isolatedInit,ke=Le?{...ze,...Le}:ze;je=ut.jsx(vC,{initialState:ke,scopeId:x.isolatedScopeId,children:je})}return je},[Ne,x.iteration,x.sortable,x.itemTemplate,x.type,x.name,x.id,x.props,x.isolatedState,x.isolatedScopeId,r,ta,On,ea,Dr,he,bn,v,S,E,A,T,L,e._global?._remountKeys]),tr=N.useMemo(()=>{const q=x.blur_until_loaded;if(!q||e?._global?.__isPreview)return!1;if(typeof q=="string"){const Z=_t(q);if(Z!==null)try{const be={componentId:x.id,componentName:x.name,propName:"blur_until_loaded"};return!!i.evaluateExpression(Z,ie,be)}catch(be){return dt.warn(`blur_until_loaded 표현식 평가 실패 (컴포넌트: ${x.id}):`,be),!1}return!1}if(typeof q=="object"&&q!==null){if(!q.enabled)return!1;if(q.data_sources)return(Array.isArray(q.data_sources)?q.data_sources:[q.data_sources]).some(Re=>e[Re]===void 0);if(Q)return!0;const Z=["route","query","_global","_local","_dataSourceErrors"];return Object.keys(e).filter(ve=>!Z.includes(ve)&&!ve.startsWith("_")).some(ve=>e[ve]===void 0)}if(Q)return!0;const ce=["route","query","_global","_local","_dataSourceErrors"];return Object.keys(e).filter(Z=>!ce.includes(Z)&&!Z.startsWith("_")).some(Z=>e[Z]===void 0)},[x.blur_until_loaded,x.id,Q,e,ie,i,_t]);if(tr){const q=x.blur_until_loaded;if(typeof q=="object"&&q?.data_sources){const le=(Array.isArray(q.data_sources)?q.data_sources:[q.data_sources]).reduce((be,ve)=>(be[ve]=e[ve]===void 0?"UNDEFINED":"LOADED",be),{}),Z=Object.keys(e).filter(be=>!be.startsWith("_"));dt.log(`[BLUR APPLIED] Component: ${x.id}, data_sources status:`,le,"Available keys:",Z)}else dt.log(`[BLUR APPLIED] Component: ${x.id}, blur_until_loaded:`,q)}const Ea=N.useMemo(()=>{if(!x.blur_until_loaded)return{wrapperClasses:"",innerClasses:""};const q=ft?.className||"";if(!q)return{wrapperClasses:"",innerClasses:""};const ce=[/^(sm:|md:|lg:|xl:|2xl:)?(col-span-|row-span-|col-start-|col-end-|row-start-|row-end-)/,/^(sm:|md:|lg:|xl:|2xl:)?(self-|place-self-|order-)/,/^(sm:|md:|lg:|xl:|2xl:)?(flex-shrink|flex-grow|flex-\d|basis-)/],le=q.split(/\s+/).filter(Boolean),Z=[],be=[];for(const ve of le)ce.some(xe=>xe.test(ve))?Z.push(ve):be.push(ve);return{wrapperClasses:Z.join(" "),innerClasses:be.join(" ")}},[x.blur_until_loaded,ft?.className]),nn=window.__slotContextValue;return Se&&nn?.isEnabled?null:ut.jsx(y_,{componentId:o.id,componentName:o.name,children:x.blur_until_loaded?ut.jsx("div",{className:[Ea.wrapperClasses,tr?"opacity-50 blur-sm transition-all duration-300 pointer-events-none":void 0].filter(Boolean).join(" ")||void 0,children:En}):En})});Ha.displayName="DynamicRenderer",typeof window<"u"&&(window.__DynamicRenderer=Ha);function b_(o){const e={};try{const r=new URL(o,typeof window<"u"?window.location.origin:"http://localhost").searchParams,i=new Set;for(const l of r.keys()){if(i.has(l))continue;i.add(l);const u=r.getAll(l);u.length>1||l.endsWith("[]")?e[l]=u:e[l]=u[0]}}catch{}return e}function v_(o){try{return new URL(o,typeof window<"u"?window.location.origin:"http://localhost").pathname}catch{return o.split("?")[0]}}const yi=class yi{constructor(){$(this,"config",{enabled:!1,maxHistorySize:100,logLevel:"info",serverEndpoint:"/_boost/g7-debug/dump-state",autoCapture:!0});$(this,"stateHistory",[]);$(this,"snapshotIdCounter",0);$(this,"stateWatchers",new Map);$(this,"currentLocalState",{});$(this,"currentComputedState",{});$(this,"currentParentContext");$(this,"actionHistory",[]);$(this,"actionWatchers",new Set);$(this,"cacheStats",{hits:0,misses:0,entries:0});$(this,"cacheDecisions",[]);$(this,"cacheDecisionIdCounter",0);$(this,"maxCacheDecisions",200);$(this,"currentRenderCycleId",null);$(this,"isInActionExecution",!1);$(this,"isInIteration",!1);$(this,"mountedComponents",new Map);$(this,"eventListeners",new Map);$(this,"mountWatchers",new Set);$(this,"unmountWatchers",new Set);$(this,"renderCounts",new Map);$(this,"bindingEvalCount",0);$(this,"profilingData",[]);$(this,"isProfiling",!1);$(this,"profilingStartTime",0);$(this,"activeRequests",new Map);$(this,"requestHistory",[]);$(this,"pendingDataSources",new Set);$(this,"requestWatchers",new Set);$(this,"wsConnections",new Map);$(this,"wsMessageHistory",[]);$(this,"wsMessageWatchers",new Set);$(this,"ifConditions",new Map);$(this,"iterations",new Map);$(this,"conditionWatchers",new Set);$(this,"forms",new Map);$(this,"formWatchers",new Set);$(this,"expressionHistory",[]);$(this,"expressionWatchers",new Set);$(this,"expressionIdCounter",0);$(this,"dataSources",new Map);$(this,"dataPathTransforms",[]);$(this,"maxDataPathTransforms",100);$(this,"nestedContexts",[]);$(this,"nestedContextIdCounter",0);$(this,"maxNestedContexts",100);$(this,"formBindingIssues",[]);$(this,"formBindingValidations",[]);$(this,"formBindingIssueIdCounter",0);$(this,"maxFormBindingIssues",100);$(this,"computedProperties",new Map);$(this,"computedRecalcLogs",[]);$(this,"computedRecalcIdCounter",0);$(this,"maxComputedRecalcLogs",100);$(this,"handlers",new Map);$(this,"componentEventSubscriptions",new Map);$(this,"componentEventEmitHistory",[]);$(this,"componentEventIdCounter",0);$(this,"maxComponentEventHistory",100);$(this,"stateRenderingLogs",[]);$(this,"currentStateChangeContext",null);$(this,"stateRenderingIdCounter",0);$(this,"componentRenderCounts",new Map);$(this,"stateToComponentMap",new Map);$(this,"maxStateRenderingLogs",100);$(this,"componentStateSources",new Map);$(this,"contextFlowNodes",new Map);$(this,"dynamicStates",new Map);$(this,"styleIssues",[]);$(this,"componentStyles",new Map);$(this,"authEvents",[]);$(this,"authHeaderHistory",[]);$(this,"authEventIdCounter",0);$(this,"maxAuthEventHistory",50);$(this,"logHistory",[]);$(this,"logIdCounter",0);$(this,"maxLogHistory",500);$(this,"currentLayout",null);$(this,"layoutHistory",[]);$(this,"layoutIdCounter",0);$(this,"layoutStats",{totalLoads:0,cacheHits:0,apiLoads:0});$(this,"maxLayoutHistory",50);$(this,"executionDetails",new Map);$(this,"stateChangeHistory",[]);$(this,"dataSourceChangeHistory",[]);$(this,"changeAlerts",[]);$(this,"changeExpectations",new Map);$(this,"executionIdCounter",0);$(this,"stateChangeIdCounter",0);$(this,"alertIdCounter",0);$(this,"maxExecutionDetails",100);$(this,"maxStateChangeHistory",200);$(this,"maxChangeAlerts",100);$(this,"sequenceExecutions",[]);$(this,"sequenceExecutionStack",[]);$(this,"sequenceIdCounter",0);$(this,"maxSequenceExecutions",50);$(this,"staleClosureWarnings",[]);$(this,"staleClosureIdCounter",0);$(this,"maxStaleClosureWarnings",100);$(this,"stateCaptureRegistry",new Map);$(this,"modalStates",new Map);$(this,"modalStateIssues",[]);$(this,"modalStateRelations",[]);$(this,"modalStateChangeLogs",[]);$(this,"modalStateIssueIdCounter",0);$(this,"modalStateChangeLogIdCounter",0);$(this,"maxModalStateIssues",100);$(this,"maxModalStateChangeLogs",200);$(this,"namedActionDefinitions",{});$(this,"namedActionRefLogs",[]);$(this,"namedActionRefIdCounter",0);$(this,"maxNamedActionRefLogs",200);$(this,"debounceActionHistory",[]);$(this,"dataSourceUpdateHistory",[]);$(this,"debounceActionIdCounter",0);$(this,"dataSourceUpdateIdCounter",0)}static getInstance(){return yi.instance||(yi.instance=new yi),yi.instance}initialize(){if(this.config.enabled=this.checkDebugMode(),!this.config.enabled){console.log("[G7DevTools] 비활성화됨 (환경설정 > 고급 설정 > 디버그 모드를 켜세요)");return}console.log("[G7DevTools] 활성화됨"),this.setupGlobalErrorHandler()}checkDebugMode(){try{if(window.G7Config?.debug===!0)return!0;const r=window.G7Core?.state?.get?.();return r?.settings?.advanced?.debug_mode===!0||r?._global?.settings?.advanced?.debug_mode===!0}catch{return!1}}isEnabled(){return this.config.enabled}setupGlobalErrorHandler(){window.addEventListener("error",e=>{this.config.enabled&&this.logAction({id:this.generateId(),type:"globalError",startTime:Date.now(),status:"error",error:{name:"Error",message:e.message,stack:e.error?.stack}})}),window.addEventListener("unhandledrejection",e=>{this.config.enabled&&this.logAction({id:this.generateId(),type:"unhandledRejection",startTime:Date.now(),status:"error",error:{name:"UnhandledRejection",message:String(e.reason)}})})}captureStateSnapshot(e){if(!this.config.enabled)return;const a={id:++this.snapshotIdCounter,timestamp:Date.now(),source:e.source,prev:this.sanitizeObject(e.prev),next:this.sanitizeObject(e.next),diff:e.diff};this.stateHistory.push(a),this.stateHistory.length>this.config.maxHistorySize&&this.stateHistory.shift(),this.notifyStateWatchers(a)}getState(){try{const e=window.G7Core,a=e?.state?.get?.()||{},r={};if(e?._isolatedStates&&typeof e._isolatedStates=="object")for(const[i,l]of Object.entries(e._isolatedStates))r[i]=this.sanitizeObject(l);return{_global:a._global||a,_local:this.currentLocalState,_computed:this.currentComputedState,_isolated:Object.keys(r).length>0?r:void 0,$parent:this.currentParentContext}}catch{return{_global:{},_local:this.currentLocalState,_computed:this.currentComputedState}}}updateLocalState(e){this.config.enabled&&(this.currentLocalState=this.sanitizeObject(e))}updateComputedState(e){this.config.enabled&&(this.currentComputedState=this.sanitizeObject(e))}updateParentContext(e){this.config.enabled&&(this.currentParentContext=e?this.sanitizeObject(e):void 0)}getStateHistory(){return[...this.stateHistory]}getDualStorageMismatch(){const e=this.currentLocalState||{};let a={};try{a=(window.G7Core?.state?.get?.()||{})._local||{}}catch{a={}}const r=this.findMismatchedLeafPaths(e,a);return{hasMismatch:r.length>0,mismatchedPaths:r,storageA:e,storageB:a}}findMismatchedLeafPaths(e,a,r=""){const i=[],l=new Set([...Object.keys(e||{}),...Object.keys(a||{})]);for(const u of l){const d=r?`${r}.${u}`:u,f=e?.[u],g=a?.[u],m=f&&typeof f=="object"&&!Array.isArray(f),b=g&&typeof g=="object"&&!Array.isArray(g);if(m&&b)i.push(...this.findMismatchedLeafPaths(f,g,d));else{const v=f===void 0?"__undefined__":JSON.stringify(f),S=g===void 0?"__undefined__":JSON.stringify(g);v!==S&&i.push(d)}}return i}watchState(e,a){return this.stateWatchers.has(e)||this.stateWatchers.set(e,new Set),this.stateWatchers.get(e).add(a),()=>{this.stateWatchers.get(e)?.delete(a)}}notifyStateWatchers(e){if(this.stateWatchers.get("*")?.forEach(a=>{try{a(e.next,e.prev,"*")}catch(r){console.error("[G7DevTools] State watcher error:",r)}}),e.diff)for(const a of e.diff.changed)this.stateWatchers.get(a.path)?.forEach(r=>{try{r(a.newValue,a.oldValue,a.path)}catch(i){console.error("[G7DevTools] State watcher error:",i)}})}diffSnapshots(e,a){const r=this.stateHistory.find(l=>l.id===e),i=this.stateHistory.find(l=>l.id===a);return!r||!i?null:this.calculateDiff(r.next,i.next)}calculateDiff(e,a,r=""){const i={added:[],removed:[],changed:[]},l=new Set(Object.keys(e)),u=new Set(Object.keys(a));for(const d of u){const f=r?`${r}.${d}`:d;l.has(d)?JSON.stringify(e[d])!==JSON.stringify(a[d])&&i.changed.push({path:f,oldValue:e[d],newValue:a[d]}):i.added.push(f)}for(const d of l){const f=r?`${r}.${d}`:d;u.has(d)||i.removed.push(f)}return i}logAction(e){if(!this.config.enabled)return;const a=this.actionHistory.findIndex(r=>r.id===e.id);a>=0?this.actionHistory[a]={...this.actionHistory[a],...e}:(this.actionHistory.push(e),this.actionHistory.length>this.config.maxHistorySize&&this.actionHistory.shift()),this.isProfiling&&this.profilingData.push({type:"action",action:e.type,timestamp:performance.now(),duration:e.duration}),this.notifyActionWatchers(e)}getActionHistory(){return[...this.actionHistory]}watchActions(e){return this.actionWatchers.add(e),()=>{this.actionWatchers.delete(e)}}notifyActionWatchers(e){this.actionWatchers.forEach(a=>{try{a(e)}catch(r){console.error("[G7DevTools] Action watcher error:",r)}})}getActionMetrics(){const e=this.actionHistory.filter(l=>l.status==="success"),a=this.actionHistory.filter(l=>l.status==="error"),r={};for(const l of this.actionHistory)r[l.type]=(r[l.type]||0)+1;const i=e.reduce((l,u)=>l+(u.duration||0),0);return{totalActions:this.actionHistory.length,successCount:e.length,errorCount:a.length,averageDuration:e.length>0?i/e.length:0,actionsByType:r}}recordCacheHit(){this.config.enabled&&this.cacheStats.hits++}recordCacheMiss(){this.config.enabled&&this.cacheStats.misses++}updateCacheEntries(e){this.config.enabled&&(this.cacheStats.entries=e)}getCacheStats(){const e=this.cacheStats.hits+this.cacheStats.misses;return{...this.cacheStats,hitRate:e>0?this.cacheStats.hits/e:0}}resetCacheStats(){this.cacheStats={hits:0,misses:0,entries:0}}trackCacheDecision(e){if(!this.config.enabled)return;const a={id:`cache-${++this.cacheDecisionIdCounter}`,timestamp:Date.now(),expression:e.expression,decision:e.decision,reason:e.reason,context:{isInIteration:this.isInIteration,isInAction:this.isInActionExecution,renderCycleId:this.currentRenderCycleId||void 0,componentId:e.componentId,skipCacheOption:e.skipCacheOption},cachedValue:e.cachedValue!==void 0?this.safeClone(e.cachedValue):void 0,freshValue:e.freshValue!==void 0?this.safeClone(e.freshValue):void 0,valueMatch:e.cachedValue!==void 0&&e.freshValue!==void 0?JSON.stringify(e.cachedValue)===JSON.stringify(e.freshValue):void 0,duration:e.duration};this.cacheDecisions.push(a),this.cacheDecisions.length>this.maxCacheDecisions&&this.cacheDecisions.shift(),e.decision==="cache_hit"?this.cacheStats.hits++:(e.decision==="cache_miss"||e.decision==="skip_cache")&&this.cacheStats.misses++}startRenderCycle(e){return this.currentRenderCycleId=`render-${Date.now()}-${e||"root"}`,this.currentRenderCycleId}endRenderCycle(){this.currentRenderCycleId=null}startActionContext(){this.isInActionExecution=!0}endActionContext(){this.isInActionExecution=!1}startIterationContext(){this.isInIteration=!0}endIterationContext(){this.isInIteration=!1}getCacheDecisionTrackingInfo(){const e=this.getCacheDecisionStats();return{decisions:[...this.cacheDecisions],stats:e,timestamp:Date.now()}}getCacheDecisionStats(){const e=this.cacheDecisions;let a=0,r=0,i=0,l=0;const u={},d={};for(const g of e)g.decision==="cache_hit"?a++:g.decision==="cache_miss"?r++:g.decision==="skip_cache"?i++:g.decision==="invalidate"&&l++,u[g.reason]=(u[g.reason]||0)+1,g.context.componentId&&(d[g.context.componentId]=(d[g.context.componentId]||0)+1);const f=a+r+i;return{totalDecisions:e.length,cacheHits:a,cacheMisses:r,skipCacheCount:i,invalidateCount:l,byReason:u,byComponent:d,avgHitRate:f>0?a/f:0}}getRecentCacheDecisions(e=20,a){let r=[...this.cacheDecisions];return a&&(r=r.filter(i=>i.decision===a)),r.slice(-e)}clearCacheDecisionData(){this.cacheDecisions=[],this.cacheDecisionIdCounter=0}summarizePropsForLifecycle(e){if(!e||typeof e!="object")return e;const a={},r=["children","ref","key"];for(const[i,l]of Object.entries(e))if(!r.includes(i))if(l==null)a[i]=l;else if(Array.isArray(l))a[i]=`[Array(${l.length})]`;else if(typeof l=="object"){const u=Object.keys(l);u.length<=3?a[i]=`{${u.join(", ")}}`:a[i]=`{${u.slice(0,3).join(", ")}, ... +${u.length-3}}`}else typeof l=="string"&&l.length>50?a[i]=l.substring(0,50)+"...":typeof l=="function"?a[i]="[Function]":a[i]=l;return a}trackMount(e,a){if(!this.config.enabled)return;const r=this.summarizePropsForLifecycle(a.props),i={...a,props:r,id:e,mountTime:Date.now()};this.mountedComponents.set(e,i),this.mountWatchers.forEach(l=>{try{l({componentId:e,componentName:a.name,timestamp:i.mountTime})}catch(u){console.error("[G7DevTools] Mount watcher error:",u)}})}trackUnmount(e){if(!this.config.enabled)return;const a=this.mountedComponents.get(e),r=this.eventListeners.get(e)||[];r.length>0&&console.warn(`[G7DevTools] 컴포넌트 ${e} 언마운트 시 ${r.length}개 리스너 미정리`),a&&this.unmountWatchers.forEach(i=>{try{i({componentId:e,componentName:a.name,timestamp:Date.now(),orphanedListeners:r.length})}catch(l){console.error("[G7DevTools] Unmount watcher error:",l)}}),this.mountedComponents.delete(e)}trackListener(e,a,r){if(!this.config.enabled)return;const i=this.eventListeners.get(e)||[];i.push({type:a,target:r,addedAt:Date.now()}),this.eventListeners.set(e,i)}removeListener(e,a){if(!this.config.enabled)return;const r=this.eventListeners.get(e)||[],i=r.findIndex(l=>l.type===a);i>=0&&r.splice(i,1)}getMountedComponents(){return Array.from(this.mountedComponents.values())}getOrphanedListeners(){const e=[];for(const[a,r]of this.eventListeners)this.mountedComponents.has(a)||e.push(...r.map(i=>({...i,componentId:a})));return e}watchMount(e){return this.mountWatchers.add(e),()=>{this.mountWatchers.delete(e)}}watchUnmount(e){return this.unmountWatchers.add(e),()=>{this.unmountWatchers.delete(e)}}trackRender(e){if(!this.config.enabled)return;const a=this.renderCounts.get(e)||0;this.renderCounts.set(e,a+1),this.isProfiling&&this.profilingData.push({type:"render",component:e,timestamp:performance.now()})}trackBindingEval(e){this.config.enabled&&(this.bindingEvalCount++,this.isProfiling&&e&&this.profilingData.push({type:"binding",expression:e,timestamp:performance.now()}))}getRenderCount(){return new Map(this.renderCounts)}getBindingEvalCount(){return this.bindingEvalCount}getMemoryWarnings(){const e=[];try{const i=this.getState(),l=JSON.stringify(i).length;l>1e6&&e.push({type:"large-state",message:`상태 크기가 ${(l/1024/1024).toFixed(2)}MB입니다`,suggestion:"불필요한 데이터 정리 필요",severity:l>5e6?"error":"warning"})}catch{}this.stateHistory.length>this.config.maxHistorySize*.8&&e.push({type:"large-history",message:`상태 이력이 ${this.stateHistory.length}개입니다`,suggestion:"maxHistory 설정 조정 필요",severity:"warning"});const a=this.getOrphanedListeners().length;a>0&&e.push({type:"orphaned-listeners",message:`${a}개의 정리되지 않은 이벤트 리스너`,suggestion:"useEffect cleanup 또는 removeEventListener 확인",severity:a>10?"error":"warning"});const r=Array.from(this.renderCounts.entries()).filter(([,i])=>i>50);return r.length>0&&e.push({type:"excessive-renders",message:`${r.length}개 컴포넌트가 50회 이상 렌더링`,suggestion:"React.memo, useMemo, useCallback 사용 고려",severity:"warning"}),e}startProfiling(){this.config.enabled&&(this.isProfiling=!0,this.profilingData=[],this.profilingStartTime=performance.now(),console.log("[G7DevTools] 프로파일링 시작"))}stopProfiling(){this.isProfiling=!1;const e=performance.now()-this.profilingStartTime,a=this.analyzeProfile(e);return console.log("[G7DevTools] 프로파일링 완료",a),a}analyzeProfile(e){const a=this.profilingData.filter(g=>g.type==="render"),r=this.profilingData.filter(g=>g.type==="binding"),i=this.profilingData.filter(g=>g.type==="action"),l={};for(const g of a)g.component&&(l[g.component]||(l[g.component]={count:0,durations:[]}),l[g.component].count++,g.duration&&l[g.component].durations.push(g.duration));const u=Object.entries(l).map(([g,m])=>({name:g,renderCount:m.count,avgDuration:m.durations.length>0?m.durations.reduce((b,v)=>b+v,0)/m.durations.length:0})).sort((g,m)=>m.renderCount-g.renderCount).slice(0,10),d={};for(const g of r)g.expression&&(d[g.expression]=(d[g.expression]||0)+1);const f=Object.entries(d).sort(([,g],[,m])=>m-g).slice(0,10).map(([g])=>g);return{duration:e,entries:this.profilingData,summary:{totalRenders:a.length,totalBindings:r.length,totalActions:i.length,slowestComponents:u,hotPaths:f}}}resetPerformanceStats(){this.renderCounts.clear(),this.bindingEvalCount=0,this.profilingData=[]}trackRequest(e,a,r){if(!this.config.enabled)return"";const i=this.generateId(),l=v_(e),u=b_(e);return this.activeRequests.set(i,{id:i,url:l,fullUrl:e,queryParams:u,method:a,startTime:Date.now(),status:"pending",requestBody:r?.requestBody?this.sanitizeObject(r.requestBody):void 0,dataSourceId:r?.dataSourceId}),this.isProfiling&&this.profilingData.push({type:"network",timestamp:performance.now()}),i}completeRequest(e,a,r){if(!this.config.enabled)return;const i=this.activeRequests.get(e);if(!i)return;const l={...i,status:a>=200&&a<300?"success":"error",statusCode:a,duration:Date.now()-i.startTime,endTime:Date.now(),response:this.sanitizeObject(r)};this.requestHistory.push(l),this.activeRequests.delete(e),this.requestHistory.length>this.config.maxHistorySize&&this.requestHistory.shift(),this.notifyRequestWatchers(l)}failRequest(e,a){if(!this.config.enabled)return;const r=this.activeRequests.get(e);if(!r)return;const i={...r,status:"error",error:a,duration:Date.now()-r.startTime,endTime:Date.now()};this.requestHistory.push(i),this.activeRequests.delete(e),this.notifyRequestWatchers(i)}trackDataSource(e){this.config.enabled&&this.pendingDataSources.add(e)}completeDataSource(e){this.config.enabled&&this.pendingDataSources.delete(e)}getActiveRequests(){return Array.from(this.activeRequests.values())}getRequestHistory(){return[...this.requestHistory]}getPendingDataSources(){return Array.from(this.pendingDataSources)}watchRequest(e){return this.requestWatchers.add(e),()=>{this.requestWatchers.delete(e)}}notifyRequestWatchers(e){this.requestWatchers.forEach(a=>{try{a(e)}catch(r){console.error("[G7DevTools] Request watcher error:",r)}})}trackWebSocketConnection(e,a,r){this.config.enabled&&this.wsConnections.set(e,{id:e,url:a,state:r,connectedAt:r==="open"?Date.now():void 0})}trackWebSocketMessage(e,a,r,i){if(!this.config.enabled)return;const l={id:this.generateId(),connectionId:e,direction:a,type:r,payload:this.sanitizeObject(i),timestamp:Date.now(),sequence:this.wsMessageHistory.length};this.wsMessageHistory.push(l),this.wsMessageHistory.length>this.config.maxHistorySize&&this.wsMessageHistory.shift(),this.notifyWebSocketWatchers(l)}getWebSocketConnections(){return Array.from(this.wsConnections.values())}getWebSocketMessageHistory(){return[...this.wsMessageHistory]}getWebSocketConnectionState(){const e=Array.from(this.wsConnections.values());return e.some(a=>a.state==="open")?"connected":e.some(a=>a.state==="connecting")?"reconnecting":"disconnected"}watchWebSocketMessage(e){return this.wsMessageWatchers.add(e),()=>{this.wsMessageWatchers.delete(e)}}notifyWebSocketWatchers(e){this.wsMessageWatchers.forEach(a=>{try{a(e)}catch(r){console.error("[G7DevTools] WebSocket watcher error:",r)}})}trackIfCondition(e,a,r){if(!this.config.enabled)return;const i=this.ifConditions.get(e),l=i?.evaluatedValue;this.ifConditions.set(e,{id:e,expression:a,evaluatedValue:r,evaluationCount:(i?.evaluationCount||0)+1,lastEvaluated:Date.now()}),i&&l!==r&&this.notifyConditionWatchers({id:e,expression:a,oldValue:l,newValue:r,timestamp:Date.now()})}trackIteration(e,a){this.config.enabled&&this.iterations.set(e,{id:e,...a,lastRendered:Date.now()})}getIfConditions(){return Array.from(this.ifConditions.values())}getIterations(){return Array.from(this.iterations.values())}getScopeChain(e){const a=[],r=this.getState();return a.push({name:"_global",value:r._global,source:"global"}),a.push({name:"_local",value:r._local,source:"local"}),a.push({name:"_computed",value:r._computed,source:"computed"}),a}watchConditionChange(e){return this.conditionWatchers.add(e),()=>{this.conditionWatchers.delete(e)}}notifyConditionWatchers(e){this.conditionWatchers.forEach(a=>{try{a(e)}catch(r){console.error("[G7DevTools] Condition watcher error:",r)}})}trackForm(e,a,r){this.config.enabled&&this.forms.set(e,{id:e,dataKey:a,inputs:r,trackedAt:Date.now()})}trackFormChange(e,a,r){if(!this.config.enabled)return;const i={formId:e,inputName:a,value:r,timestamp:Date.now()};this.notifyFormWatchers(i)}untrackForm(e){this.forms.delete(e)}getForms(){return Array.from(this.forms.values())}getFormState(e){const a=this.getState();return this.getNestedValue(a,e)||{}}getBindingPath(e,a){return`${e}.${a}`}watchFormChange(e){return this.formWatchers.add(e),()=>{this.formWatchers.delete(e)}}notifyFormWatchers(e){this.formWatchers.forEach(a=>{try{a(e)}catch(r){console.error("[G7DevTools] Form watcher error:",r)}})}trackFormBindingIssue(e,a,r){if(!this.config.enabled)return;const i={id:`form-issue-${++this.formBindingIssueIdCounter}`,timestamp:Date.now(),type:e,severity:a,formId:r.formId,formDataKey:r.formDataKey,inputInfo:r.inputInfo,contextInfo:r.contextInfo,description:r.description,suggestion:r.suggestion,docLink:r.docLink};this.formBindingIssues.push(i),this.formBindingIssues.length>this.maxFormBindingIssues&&this.formBindingIssues.shift()}validateFormBinding(e,a,r,i){const l=r.map(f=>{const g=[];let m=!0;return f.name||(g.push("Input에 name 속성이 없습니다"),m=!1,this.trackFormBindingIssue("missing-input-name","error",{formId:e,formDataKey:a,inputInfo:{name:f.name,type:f.type},description:"Input에 name 속성이 없어 자동 바인딩이 동작하지 않습니다",suggestion:"Input에 name 속성을 추가하세요",docLink:"troubleshooting-components-form.md"})),a||(g.push("Form에 dataKey가 없습니다"),m=!1),{inputName:f.name||"(unnamed)",inputType:f.type,bindingPath:a&&f.name?`${a}.${f.name}`:"-",isValid:m,currentValue:f.value,issues:g}});if(a||this.trackFormBindingIssue("missing-datakey","error",{formId:e,description:"Form에 dataKey가 설정되지 않아 자동 바인딩이 동작하지 않습니다",suggestion:"Form 컴포넌트에 dataKey props를 설정하세요",docLink:"troubleshooting-components-form.md"}),i.isContextBroken){const f=i.breakReason?.includes("sortable")?"sortable-context-break":i.breakReason?.includes("modal")?"modal-context-isolation":"context-not-propagated";this.trackFormBindingIssue(f,"warning",{formId:e,formDataKey:a,contextInfo:{hasParentFormContext:i.hasParentContext,parentFormContextProp:i.parentContextProp,isInsideSortable:i.breakReason?.includes("sortable")||!1,isInsideModal:i.breakReason?.includes("modal")||!1,depth:0},description:i.breakReason||"Form 컨텍스트가 제대로 전파되지 않았습니다",suggestion:"parentFormContextProp={undefined}를 확인하거나 중첩 구조를 검토하세요",docLink:"troubleshooting-components-form.md"})}const u={formId:e,dataKey:a,timestamp:Date.now(),contextPropagation:i,inputBindings:l,isValid:l.every(f=>f.isValid)&&!!a&&!i.isContextBroken,issueCount:l.filter(f=>!f.isValid).length+(a?0:1)+(i.isContextBroken?1:0)},d=this.formBindingValidations.findIndex(f=>f.formId===e);return d>=0?this.formBindingValidations[d]=u:this.formBindingValidations.push(u),u}getFormBindingValidationTrackingInfo(){const e=this.getFormBindingValidationStats();return{issues:[...this.formBindingIssues],validations:[...this.formBindingValidations],stats:e,timestamp:Date.now()}}getFormBindingValidationStats(){const e={"missing-datakey":0,"missing-input-name":0,"context-not-propagated":0,"sortable-context-break":0,"modal-context-isolation":0,"duplicate-input-name":0,"value-type-mismatch":0,"binding-path-invalid":0},a={info:0,warning:0,error:0};for(const i of this.formBindingIssues)e[i.type]++,a[i.severity]++;const r=Object.entries(e).filter(([,i])=>i>0).sort((i,l)=>l[1]-i[1]).slice(0,5).map(([i,l])=>({type:i,count:l,description:this.getIssueTypeDescription(i)}));return{totalFormsValidated:this.formBindingValidations.length,validForms:this.formBindingValidations.filter(i=>i.isValid).length,formsWithIssues:this.formBindingValidations.filter(i=>!i.isValid).length,totalIssues:this.formBindingIssues.length,byIssueType:e,bySeverity:a,topIssues:r}}getIssueTypeDescription(e){return{"missing-datakey":"Form에 dataKey 누락","missing-input-name":"Input에 name 속성 누락","context-not-propagated":"Form 컨텍스트 전파 실패","sortable-context-break":"Sortable 컨테이너에서 컨텍스트 단절","modal-context-isolation":"모달에서 부모 Form 컨텍스트 격리","duplicate-input-name":"동일 Form 내 중복 Input name","value-type-mismatch":"값 타입과 Input 타입 불일치","binding-path-invalid":"바인딩 경로 유효하지 않음"}[e]||e}clearFormBindingIssues(){this.formBindingIssues=[],this.formBindingValidations=[],this.formBindingIssueIdCounter=0}trackComputedProperty(e,a,r,i,l,u,d){if(!this.config.enabled)return;const f=`computed-${e}-${u||"global"}`,g={id:f,name:e,expression:a,componentId:u,dependencies:r,currentValue:this.safeClone(i),lastComputedAt:Date.now(),computationTime:l,error:d};this.computedProperties.set(f,g)}trackComputedRecalc(e,a,r,i,l,u,d){if(!this.config.enabled)return;const f=`computed-${e}-${d||"global"}`,g=JSON.stringify(r)!==JSON.stringify(i),m={id:`recalc-${++this.computedRecalcIdCounter}`,computedId:f,computedName:e,timestamp:Date.now(),trigger:a,triggeredBy:u,previousValue:this.safeClone(r),newValue:this.safeClone(i),valueChanged:g,computationTime:l,cascadeCount:0};this.computedRecalcLogs.push(m),this.computedRecalcLogs.length>this.maxComputedRecalcLogs&&this.computedRecalcLogs.shift();const b=this.computedProperties.get(f);b&&(b.currentValue=this.safeClone(i),b.lastComputedAt=Date.now(),b.computationTime=l)}analyzeComputedDependencyChain(e,a){const r=new Set,i=[];let l=!1,u,d=0;const f=(m,b)=>{if(d=Math.max(d,b),r.has(m))return l=!0,u=[...i,m],{name:m,type:"computed",children:[],depth:b};r.add(m),i.push(m);const v=this.computedProperties.get(`computed-${m}-${a||"global"}`),S=[];if(v)for(const E of v.dependencies)E.type==="computed"?S.push(f(E.path,b+1)):S.push({name:E.path,type:E.type,children:[],depth:b+1});return i.pop(),r.delete(m),{name:m,type:"computed",children:S,depth:b}},g=f(e,0);return{root:e,tree:g,hasCycle:l,cyclePath:u,maxDepth:d}}getComputedDependencyTrackingInfo(){const e=Array.from(this.computedProperties.values()),a=this.getComputedDependencyStats(),r=[];for(const i of e){const l=this.analyzeComputedDependencyChain(i.name,i.componentId);r.push(l)}return{properties:e,recalcLogs:[...this.computedRecalcLogs],dependencyChains:r,stats:a,timestamp:Date.now()}}getComputedDependencyStats(){const e={"state-change":0,"datasource-update":0,"dependency-change":0,manual:0,initial:0},a={},r={};let i=0,l=0;for(const g of this.computedRecalcLogs)e[g.trigger]++,g.valueChanged||l++,a[g.computedName]=(a[g.computedName]||0)+1,r[g.computedName]||(r[g.computedName]=[]),r[g.computedName].push(g.computationTime),i+=g.computationTime;const u=Object.entries(a).sort((g,m)=>m[1]-g[1]).slice(0,5).map(([g,m])=>({name:g,count:m})),d=Object.entries(r).map(([g,m])=>({name:g,avgTime:m.reduce((b,v)=>b+v,0)/m.length})).sort((g,m)=>m.avgTime-g.avgTime).slice(0,5);let f=0;for(const g of this.computedProperties.values())this.analyzeComputedDependencyChain(g.name,g.componentId).hasCycle&&f++;return{totalComputed:this.computedProperties.size,totalRecalculations:this.computedRecalcLogs.length,unnecessaryRecalculations:l,avgComputationTime:this.computedRecalcLogs.length>0?i/this.computedRecalcLogs.length:0,topRecalculated:u,slowestComputed:d,cycleDetectionCount:f,byTrigger:e}}clearComputedTracking(){this.computedProperties.clear(),this.computedRecalcLogs=[],this.computedRecalcIdCounter=0}trackModalOpen(e){if(!this.config.enabled)return;const a={modalId:e.modalId,modalName:e.modalName,openedAt:Date.now(),closedAt:null,scopeType:e.scopeType||"isolated",parentModalId:e.parentModalId,componentId:e.componentId,initialState:e.initialState?{...e.initialState}:{},currentState:e.initialState?{...e.initialState}:{},stateChangeCount:0,isolatedStateKeys:e.isolatedStateKeys||[],sharedStateKeys:e.sharedStateKeys||[]};this.modalStates.set(e.modalId,a),this.validateModalDefinitionExists(e.modalId,e.modalName),e.parentModalId&&(this.modalStateRelations.find(i=>i.parentModalId===e.parentModalId&&i.childModalId===e.modalId)||this.modalStateRelations.push({parentModalId:e.parentModalId,childModalId:e.modalId,sharedKeys:e.sharedStateKeys||[],isolatedKeys:e.isolatedStateKeys||[],relationType:"parent-child"}))}trackModalClose(e,a){if(!this.config.enabled)return;const r=this.modalStates.get(e);r&&(r.closedAt=Date.now(),a&&(r.currentState={...a}),this.detectStateLeakage(r))}validateModalDefinitionExists(e,a){const r=this.currentLayout;if(!r?.layoutJson)return;const i=r.layoutJson.modals;if(!i){this.recordModalStateIssue({type:"missing-definition",modalId:e,modalName:a,severity:"error",description:`모달 "${e}"이(가) modalStack에 추가되었으나, 현재 레이아웃에 modals 섹션이 없습니다. 레이아웃 경로: ${r.layoutPath}`,affectedStateKeys:[],expectedValue:`modals 섹션에 id="${e}" 정의 존재`,actualValue:"modals 섹션 없음"});return}const l=Array.isArray(i)?i:Object.values(i);l.some(d=>d?.id===e||d?.props?.id===e)||this.recordModalStateIssue({type:"missing-definition",modalId:e,modalName:a,severity:"error",description:`모달 "${e}"이(가) modalStack에 추가되었으나, 렌더링된 레이아웃의 modals 섹션에 해당 ID의 정의가 없습니다. partial 로딩 실패, 레이아웃 병합 문제, extends 상속 누락 등을 확인하세요. 레이아웃 경로: ${r.layoutPath}`,affectedStateKeys:[],expectedValue:`modals 배열에 id="${e}" 항목 존재`,actualValue:`modals 배열에 ${l.length}개 모달 정의 (${l.map(d=>d?.id||"unknown").join(", ")})`})}trackModalStateChange(e){if(!this.config.enabled)return;const a=this.modalStates.get(e.modalId);if(!a)return;a.stateChangeCount++,a.currentState[e.stateKey]=e.newValue;const r=this.checkIsolationViolation(a,e.stateKey),i={id:`modal-change-${++this.modalStateChangeLogIdCounter}`,modalId:e.modalId,modalName:a.modalName,timestamp:Date.now(),stateKey:e.stateKey,previousValue:e.previousValue,newValue:e.newValue,changeSource:e.changeSource||"user-action",violatesIsolation:r};this.modalStateChangeLogs.push(i),this.modalStateChangeLogs.length>this.maxModalStateChangeLogs&&this.modalStateChangeLogs.shift(),r&&this.recordModalStateIssue({type:"isolation-violation",modalId:e.modalId,modalName:a.modalName,severity:"warning",description:`모달 '${a.modalName}'에서 격리된 상태 키 '${e.stateKey}'가 변경됨`,affectedStateKeys:[e.stateKey]})}detectStateLeakage(e){if(e.scopeType==="isolated")for(const a of e.isolatedStateKeys){const r=e.initialState[a],i=e.currentState[a];if(r!==i&&e.parentModalId){const l=this.modalStates.get(e.parentModalId);l&&l.currentState.hasOwnProperty(a)&&this.recordModalStateIssue({type:"state-leakage",modalId:e.modalId,modalName:e.modalName,severity:"error",description:`모달 닫힘 후 상태 '${a}'가 부모 모달로 유출될 수 있음`,affectedStateKeys:[a],leakedValue:i,expectedValue:r})}}}checkIsolationViolation(e,a){return e.scopeType==="isolated",!1}recordModalStateIssue(e){const a={id:`modal-issue-${++this.modalStateIssueIdCounter}`,type:e.type,modalId:e.modalId,modalName:e.modalName,timestamp:Date.now(),severity:e.severity,description:e.description,affectedStateKeys:e.affectedStateKeys,leakedValue:e.leakedValue,expectedValue:e.expectedValue,actualValue:e.actualValue,stackInfo:e.stackInfo};this.modalStateIssues.push(a),this.modalStateIssues.length>this.maxModalStateIssues&&this.modalStateIssues.shift()}getModalStateScopeTrackingInfo(){const e=Array.from(this.modalStates.values()),a=this.getModalStateScopeStats();return{modals:e,issues:[...this.modalStateIssues],relations:[...this.modalStateRelations],changeLogs:[...this.modalStateChangeLogs],stats:a,timestamp:Date.now()}}getModalStateScopeStats(){const e=Array.from(this.modalStates.values()),a={warning:0,error:0},r={"state-leakage":0,"isolation-violation":0,"parent-mutation":0,"orphaned-state":0,"scope-mismatch":0,"cleanup-failure":0,"missing-definition":0};for(const l of this.modalStateIssues)a[l.severity]++,r[l.type]++;const i={isolated:0,shared:0,inherited:0};for(const l of e)i[l.scopeType]++;return{totalModals:e.length,openModals:e.filter(l=>l.closedAt===null).length,nestedModals:e.filter(l=>l.parentModalId!==void 0).length,totalIssues:this.modalStateIssues.length,issuesBySeverity:a,issuesByType:r,byScope:i,leakageDetectionCount:r["state-leakage"],cleanupFailureCount:r["cleanup-failure"]}}clearModalStateScopeTracking(){this.modalStates.clear(),this.modalStateIssues=[],this.modalStateRelations=[],this.modalStateChangeLogs=[],this.modalStateIssueIdCounter=0,this.modalStateChangeLogIdCounter=0}setNamedActionDefinitions(e){this.config.enabled&&(this.namedActionDefinitions=e||{})}trackNamedActionRef(e){if(!this.config.enabled)return;const a={...e,id:`named_action_ref_${++this.namedActionRefIdCounter}`};this.namedActionRefLogs.push(a),this.namedActionRefLogs.length>this.maxNamedActionRefLogs&&(this.namedActionRefLogs=this.namedActionRefLogs.slice(-this.maxNamedActionRefLogs))}getNamedActionTrackingInfo(){const e={};for(const r of this.namedActionRefLogs)e[r.actionRefName]=(e[r.actionRefName]||0)+1;const a=Object.keys(this.namedActionDefinitions).filter(r=>!e[r]);return{definitions:this.namedActionDefinitions,refLogs:[...this.namedActionRefLogs],stats:{totalDefinitions:Object.keys(this.namedActionDefinitions).length,totalRefs:this.namedActionRefLogs.length,refCountByName:e,unusedDefinitions:a},timestamp:Date.now()}}clearNamedActionTracking(){this.namedActionDefinitions={},this.namedActionRefLogs=[],this.namedActionRefIdCounter=0}trackExpressionEval(e){if(!this.config.enabled)return;const a={...e,id:`expr-${++this.expressionIdCounter}`,timestamp:Date.now(),warning:this.detectExpressionWarning(e)};this.expressionHistory.push(a),this.expressionHistory.length>500&&this.expressionHistory.shift(),this.isProfiling&&this.profilingData.push({type:"binding",expression:e.expression,timestamp:performance.now(),duration:e.duration}),this.notifyExpressionWatchers(a)}detectExpressionWarning(e){const{expression:a,result:r,resultType:i,method:l,duration:u}=e;if(i==="undefined"&&!a.includes("??")&&!a.includes("||")&&/^[a-zA-Z_$][a-zA-Z0-9_$.]*$/.test(a.replace(/{{|}}/g,"").trim()))return{type:"undefined-result",message:"표현식 결과가 undefined입니다",suggestion:`데이터가 로드되었는지 확인하거나 fallback 값을 추가하세요: ${a} ?? ''`};if(i==="null")return{type:"null-result",message:"표현식 결과가 null입니다",suggestion:`nullish coalescing 연산자를 사용하세요: ${a} ?? ''`};if(l==="resolveBindings"&&i==="string"){const d=String(r);if(d.includes("[object Object]")||/^\[.*\]$/.test(d))return{type:"array-to-string",message:"배열/객체가 문자열로 변환되었습니다",suggestion:"evaluateExpression()을 사용하여 원본 타입을 유지하세요"}}if(l==="resolveBindings"&&i==="string"&&String(r).includes("[object Object]"))return{type:"object-to-string",message:"객체가 [object Object]로 변환되었습니다",suggestion:"evaluateExpression()을 사용하거나 특정 속성에 접근하세요"};if(i==="undefined"&&a.includes(".")&&!a.includes("?.")){const d=a.replace(/{{|}}/g,"").trim().split(".");if(d.length>=2)return{type:"missing-optional-chain",message:"Optional chaining(?.) 누락 가능성",suggestion:`안전한 접근을 위해 ?. 사용을 고려하세요: ${d.join("?.")}`}}if((a.includes("{{item.")||a.includes("{{index}}"))&&Array.from(this.iterations.values()).some(g=>g.itemVar!=="item"))return{type:"wrong-iteration-var",message:"'item'/'index' 대신 iteration에서 정의한 변수명을 사용해야 합니다",suggestion:"iteration의 item_var/index_var에 정의된 변수명을 확인하세요"};if(u&&u>10)return{type:"slow-evaluation",message:`표현식 평가에 ${u.toFixed(2)}ms 소요됨`,suggestion:"복잡한 표현식을 단순화하거나 computed 값으로 분리하세요"}}getExpressions(){return[...this.expressionHistory]}getExpressionWarnings(){return this.expressionHistory.filter(e=>e.warning!=null)}searchExpressions(e){const a=e.toLowerCase();return this.expressionHistory.filter(r=>r.expression.toLowerCase().includes(a)||r.componentName?.toLowerCase().includes(a)||r.propName?.toLowerCase().includes(a))}getExpressionStats(){const e=this.expressionHistory,a=new Set(e.map(f=>f.expression)),r=e.filter(f=>f.warning!=null),i=e.filter(f=>f.fromCache),l=e.filter(f=>f.duration!=null).map(f=>f.duration),u={};for(const f of e)u[f.resultType]=(u[f.resultType]||0)+1;const d={};for(const f of r)f.warning&&(d[f.warning.type]=(d[f.warning.type]||0)+1);return{totalEvaluations:e.length,uniqueExpressions:a.size,warningCount:r.length,cacheHitRate:e.length>0?i.length/e.length:0,averageDuration:l.length>0?l.reduce((f,g)=>f+g,0)/l.length:0,byType:u,byWarning:d}}clearExpressions(){this.expressionHistory=[],this.expressionIdCounter=0}watchExpressions(e){return this.expressionWatchers.add(e),()=>{this.expressionWatchers.delete(e)}}notifyExpressionWatchers(e){this.expressionWatchers.forEach(a=>{try{a(e)}catch(r){console.error("[G7DevTools] Expression watcher error:",r)}})}setLogLevel(e){this.config.logLevel=e}setMaxHistory(e){this.config.maxHistorySize=Math.max(10,Math.min(1e3,e))}setServerEndpoint(e){this.config.serverEndpoint=e}getConfig(){return{...this.config}}generateId(){return`${Date.now()}-${Math.random().toString(36).substr(2,9)}`}sanitizeObject(e,a=new WeakSet){if(e===null||typeof e!="object")return e;if(a.has(e))return"[Circular]";if(a.add(e),Array.isArray(e))return e.map(i=>this.sanitizeObject(i,a));const r={};for(const i of Object.keys(e))try{r[i]=this.sanitizeObject(e[i],a)}catch{r[i]="[Unable to serialize]"}return r}getNestedValue(e,a){if(!a)return e;const r=a.split(".");let i=e;for(const l of r){if(i==null)return;i=i[l]}return i}getLifecycleInfo(){return{mountedComponents:Array.from(this.mountedComponents.values()),orphanedListeners:this.getOrphanedListeners()}}getPerformanceInfo(){return{renderCounts:this.renderCounts,bindingEvalCount:this.bindingEvalCount,memoryWarnings:this.getMemoryWarnings()}}getNetworkInfo(){return{activeRequests:Array.from(this.activeRequests.values()),requestHistory:[...this.requestHistory],pendingDataSources:Array.from(this.pendingDataSources)}}getConditionalInfo(){return{ifConditions:Array.from(this.ifConditions.values()),iterations:Array.from(this.iterations.values())}}getFormInfo(){return Array.from(this.forms.values())}getWebSocketInfo(){return{connections:Array.from(this.wsConnections.values()),messageHistory:[...this.wsMessageHistory],connectionState:this.getWebSocketConnectionState()}}getStateAtTime(e){const a=[...this.stateHistory].reverse().find(r=>r.timestamp<=e);if(a)return{_global:a.next,_local:{}}}reset(){this.stateHistory=[],this.actionHistory=[],this.cacheStats={hits:0,misses:0,entries:0},this.cacheDecisions=[],this.cacheDecisionIdCounter=0,this.currentRenderCycleId=null,this.isInActionExecution=!1,this.isInIteration=!1,this.mountedComponents.clear(),this.eventListeners.clear(),this.renderCounts.clear(),this.bindingEvalCount=0,this.profilingData=[],this.activeRequests.clear(),this.requestHistory=[],this.pendingDataSources.clear(),this.wsConnections.clear(),this.wsMessageHistory=[],this.ifConditions.clear(),this.iterations.clear(),this.forms.clear(),this.expressionHistory=[],this.expressionIdCounter=0,this.dataSources.clear(),this.dataPathTransforms=[],this.nestedContexts=[],this.nestedContextIdCounter=0,this.formBindingIssues=[],this.formBindingValidations=[],this.formBindingIssueIdCounter=0,this.computedProperties.clear(),this.computedRecalcLogs=[],this.computedRecalcIdCounter=0,this.modalStates.clear(),this.modalStateIssues=[],this.modalStateRelations=[],this.modalStateChangeLogs=[],this.modalStateIssueIdCounter=0,this.modalStateChangeLogIdCounter=0,this.logHistory=[],this.logIdCounter=0}getExpressionInfo(){return{expressions:this.getExpressions(),stats:this.getExpressionStats()}}trackLog(e,a,r){if(!this.config.enabled)return;const i=r.map(u=>{if(typeof u=="string")return u;try{return JSON.stringify(u)}catch{return String(u)}}).join(" "),l={id:`log-${++this.logIdCounter}`,level:e,prefix:a,message:i,args:this.sanitizeObject(r),timestamp:Date.now(),stack:e==="error"?new Error().stack:void 0};this.logHistory.push(l),this.logHistory.length>this.maxLogHistory&&this.logHistory.shift()}trackAction(e){if(!this.config.enabled)return;const a={id:`debounce-action-${++this.debounceActionIdCounter}`,...e,timestamp:Date.now()};this.debounceActionHistory.push(a),this.debounceActionHistory.length>100&&this.debounceActionHistory.shift()}trackDataSourceUpdate(e){if(!this.config.enabled)return;const a={id:`ds-update-${++this.dataSourceUpdateIdCounter}`,...e};this.dataSourceUpdateHistory.push(a),this.dataSourceUpdateHistory.length>100&&this.dataSourceUpdateHistory.shift()}getDebounceActionHistory(e){let a=[...this.debounceActionHistory];return e?.handler&&(a=a.filter(r=>r.handler.includes(e.handler))),e?.status&&(a=a.filter(r=>r.status===e.status)),e?.limit&&(a=a.slice(-e.limit)),a}getDataSourceUpdateHistory(e){let a=[...this.dataSourceUpdateHistory];return e?.dataSourceId&&(a=a.filter(r=>r.dataSourceId===e.dataSourceId)),e?.updateType&&(a=a.filter(r=>r.updateType===e.updateType)),e?.limit&&(a=a.slice(-e.limit)),a}getLogs(e){let a=[...this.logHistory];if(e?.level){const r=Array.isArray(e.level)?e.level:[e.level];a=a.filter(i=>r.includes(i.level))}if(e?.prefix){const r=e.prefix.toLowerCase();a=a.filter(i=>i.prefix.toLowerCase().includes(r))}if(e?.search){const r=e.search.toLowerCase();a=a.filter(i=>i.message.toLowerCase().includes(r))}return e?.since&&(a=a.filter(r=>r.timestamp>=e.since)),e?.limit&&(a=a.slice(-e.limit)),a}getLogStats(){const a=Date.now()-6e4,r={log:0,warn:0,error:0,debug:0,info:0},i={};let l=0,u=0;for(const d of this.logHistory)r[d.level]++,i[d.prefix]=(i[d.prefix]||0)+1,d.timestamp>=a&&(d.level==="error"&&l++,d.level==="warn"&&u++);return{totalLogs:this.logHistory.length,byLevel:r,byPrefix:i,recentErrors:l,recentWarnings:u}}clearLogs(){this.logHistory=[],this.logIdCounter=0}getLogInfo(){return{entries:this.getLogs(),stats:this.getLogStats()}}trackDataSourceDefinition(e){this.config.enabled&&this.dataSources.set(e.id,{...e,status:"idle"})}trackDataSourceLoading(e){if(!this.config.enabled)return;const a=this.dataSources.get(e);a&&this.dataSources.set(e,{...a,status:"loading"})}trackDataSourceLoaded(e,a,r){if(!this.config.enabled)return;const i=this.dataSources.get(e);if(!i)return;let l,u,d=r;a&&(Array.isArray(a)?(l=a.length,u=a.length>0&&typeof a[0]=="object"?Object.keys(a[0]):void 0):typeof a=="object"&&(Array.isArray(a.data)?(d=d||"data",l=a.data.length,u=a.data.length>0&&typeof a.data[0]=="object"?Object.keys(a.data[0]):void 0):Array.isArray(a.items)?(d=d||"items",l=a.items.length,u=a.items.length>0&&typeof a.items[0]=="object"?Object.keys(a.items[0]):void 0):u=Object.keys(a))),this.dataSources.set(e,{...i,status:"loaded",dataPath:d,itemCount:l,keys:u,lastLoadedAt:Date.now(),error:void 0})}trackDataSourceError(e,a){if(!this.config.enabled)return;const r=this.dataSources.get(e);r&&this.dataSources.set(e,{...r,status:"error",error:a,lastLoadedAt:Date.now()})}untrackDataSource(e){this.dataSources.delete(e)}getDataSources(){return Array.from(this.dataSources.values())}getDataSource(e){return this.dataSources.get(e)}clearDataSources(){this.dataSources.clear()}trackDataPathTransform(e){if(!this.config.enabled)return;let a=this.dataPathTransforms.find(r=>r.dataSourceId===e.dataSourceId);a||(a={dataSourceId:e.dataSourceId,timestamp:Date.now(),transformSteps:[],warnings:[]},this.dataPathTransforms.push(a),this.dataPathTransforms.length>this.maxDataPathTransforms&&this.dataPathTransforms.shift()),a.transformSteps.push({step:e.step,inputPath:e.inputPath,inputValue:this.safeClone(e.inputValue),outputPath:e.outputPath,outputValue:this.safeClone(e.outputValue),config:e.config}),e.warning&&a.warnings.push(e.warning)}setDataPathFinalBinding(e,a){if(!this.config.enabled)return;const r=this.dataPathTransforms.find(i=>i.dataSourceId===e);r&&(r.finalBinding={expression:a.expression,resolvedPath:a.resolvedPath,value:this.safeClone(a.value)})}getDataPathTransformTrackingInfo(){const e=this.getDataPathTransformStats();return{transforms:[...this.dataPathTransforms],stats:e,timestamp:Date.now()}}getDataPathTransformStats(){const e=this.dataPathTransforms,a={};let r=0;const i={};for(const u of e){a[u.dataSourceId]=(a[u.dataSourceId]||0)+1,r+=u.warnings.length;for(const d of u.warnings)i[d]=(i[d]||0)+1}const l=Object.entries(i).map(([u,d])=>({warning:u,count:d})).sort((u,d)=>d.count-u.count).slice(0,10);return{totalTransforms:e.length,byDataSource:a,warningsCount:r,commonWarnings:l}}getDataPathTransformForDataSource(e){return this.dataPathTransforms.find(a=>a.dataSourceId===e)}clearDataPathTransforms(){this.dataPathTransforms=[]}trackNestedContext(e){if(!this.config.enabled)return"";const a=`nested-${++this.nestedContextIdCounter}`,r=[...new Set([...e.parentContext.available,...e.ownContext.added])],i={...e.parentContext.values,...e.ownContext.values},l={id:a,timestamp:Date.now(),componentId:e.componentId,componentType:e.componentType,parentContext:{available:e.parentContext.available,values:this.safeClone(e.parentContext.values)},ownContext:{added:e.ownContext.added,values:this.safeClone(e.ownContext.values)},mergedContext:{all:r,values:this.safeClone(i)},accessAttempts:[],depth:e.depth,parentId:e.parentId};return this.nestedContexts.push(l),this.nestedContexts.length>this.maxNestedContexts&&this.nestedContexts.shift(),a}trackNestedContextAccess(e,a){if(!this.config.enabled)return;const r=this.nestedContexts.find(i=>i.id===e);r&&r.accessAttempts.push({path:a.path,found:a.found,value:a.found?this.safeClone(a.value):void 0,error:a.error})}getNestedContextTrackingInfo(){const e=this.getNestedContextStats();return{contexts:[...this.nestedContexts],stats:e,timestamp:Date.now()}}getNestedContextStats(){const e=this.nestedContexts,a={expandChildren:0,cellChildren:0,iteration:0,modal:0,slot:0};let r=0,i=0;const l={};for(const d of e){a[d.componentType]++,d.depth>r&&(r=d.depth);for(const f of d.accessAttempts)f.found||(i++,l[f.path]=(l[f.path]||0)+1)}const u=Object.entries(l).map(([d,f])=>({path:d,count:f})).sort((d,f)=>f.count-d.count).slice(0,10);return{totalContexts:e.length,byType:a,maxDepth:r,failedAccessCount:i,commonFailedPaths:u}}getNestedContextForComponent(e){return this.nestedContexts.find(a=>a.componentId===e)}clearNestedContexts(){this.nestedContexts=[],this.nestedContextIdCounter=0}trackHandlerRegistration(e,a="custom",r,i){this.isEnabled&&this.handlers.set(e,{name:e,category:a,description:r,registeredAt:Date.now(),source:i})}trackHandlerUnregistration(e){this.isEnabled&&this.handlers.delete(e)}getHandlers(){return Array.from(this.handlers.values())}getHandler(e){return this.handlers.get(e)}getHandlersByCategory(e){return Array.from(this.handlers.values()).filter(a=>a.category===e)}clearHandlers(){this.handlers.clear()}trackEventSubscribe(e){if(!this.isEnabled)return;const a=this.componentEventSubscriptions.get(e),r=Date.now();a?(a.subscriberCount++,a.lastSubscribedAt=r):this.componentEventSubscriptions.set(e,{eventName:e,subscriberCount:1,firstSubscribedAt:r,lastSubscribedAt:r})}trackEventUnsubscribe(e){if(!this.isEnabled)return;const a=this.componentEventSubscriptions.get(e);a&&(a.subscriberCount--,a.subscriberCount<=0&&this.componentEventSubscriptions.delete(e))}trackEventEmit(e,a,r,i,l){if(!this.isEnabled)return;const u={id:`evt_${++this.componentEventIdCounter}`,eventName:e,data:this.sanitizeForLogging(a),timestamp:Date.now(),listenerCount:r,results:i?this.sanitizeForLogging(i):void 0,hasError:!!l,errorMessage:l?.message};this.componentEventEmitHistory.push(u),this.componentEventEmitHistory.length>this.maxComponentEventHistory&&(this.componentEventEmitHistory=this.componentEventEmitHistory.slice(-this.maxComponentEventHistory))}trackEventOff(e){this.isEnabled&&this.componentEventSubscriptions.delete(e)}trackEventClear(){this.isEnabled&&this.componentEventSubscriptions.clear()}getComponentEventInfo(){const e=Array.from(this.componentEventSubscriptions.values());return{subscriptions:e,emitHistory:[...this.componentEventEmitHistory],totalSubscribers:e.reduce((a,r)=>a+r.subscriberCount,0),totalEmits:this.componentEventEmitHistory.length}}getEventEmitHistory(){return[...this.componentEventEmitHistory]}getEventSubscriptions(){return Array.from(this.componentEventSubscriptions.values())}clearComponentEvents(){this.componentEventSubscriptions.clear(),this.componentEventEmitHistory=[],this.componentEventIdCounter=0}sanitizeForLogging(e){if(e==null||typeof e!="object")return e;try{return JSON.parse(JSON.stringify(e))}catch{return"[Circular or Non-serializable]"}}startStateChange(e,a,r,i){if(!this.config.enabled)return"";const l=`setState_${++this.stateRenderingIdCounter}`;this.currentStateChangeContext={setStateId:l,startTime:performance.now(),changedPath:e,trigger:i||{},renderedComponents:[]};const u={id:`sr_${this.stateRenderingIdCounter}`,setStateId:l,statePath:e,oldValue:this.sanitizeForLogging(a),newValue:this.sanitizeForLogging(r),timestamp:Date.now(),triggeredBy:i||{},renderedComponents:[],totalRenderDuration:0,affectedBindingsCount:0};return this.stateRenderingLogs.push(u),this.stateRenderingLogs.length>this.maxStateRenderingLogs&&this.stateRenderingLogs.shift(),l}trackComponentRender(e,a,r,i=[],l=[],u){if(!this.config.enabled)return;const d=this.componentRenderCounts.get(a)||0;this.componentRenderCounts.set(a,d+1);for(const f of i)this.stateToComponentMap.has(f)||this.stateToComponentMap.set(f,new Set),this.stateToComponentMap.get(f).add(a);if(this.currentStateChangeContext){const f={componentId:e,componentName:a,renderDuration:r,accessedStatePaths:i,evaluatedBindings:l,renderOrder:this.currentStateChangeContext.renderedComponents.length,parentId:u};this.currentStateChangeContext.renderedComponents.push(f)}this.trackRender(a)}completeStateChange(e){if(!this.config.enabled||!this.currentStateChangeContext||this.currentStateChangeContext.setStateId!==e)return;const a=this.currentStateChangeContext,i=performance.now()-a.startTime,l=this.stateRenderingLogs.findIndex(u=>u.setStateId===e);if(l>=0){const u=this.stateRenderingLogs[l];u.renderedComponents=a.renderedComponents,u.totalRenderDuration=i,u.affectedBindingsCount=a.renderedComponents.reduce((d,f)=>d+f.evaluatedBindings.length,0)}this.currentStateChangeContext=null}getCurrentStateChangeContext(){return this.currentStateChangeContext}getStateRenderingLogs(){return[...this.stateRenderingLogs]}getStateRenderingInfo(){const e=this.stateRenderingLogs,a=Object.fromEntries(this.componentRenderCounts),r={};for(const[i,l]of this.stateToComponentMap)r[i]=Array.from(l);return{logs:e,componentRenderCounts:a,stateToComponentMap:r,stats:this.calculateStateRenderingStats()}}calculateStateRenderingStats(){const e=this.stateRenderingLogs;if(e.length===0)return{totalStateChanges:0,totalRenders:0,avgRenderDuration:0,avgComponentsPerChange:0,topRenderedComponents:[],topInfluentialPaths:[]};const a=e.reduce((d,f)=>d+f.renderedComponents.length,0),r=e.reduce((d,f)=>d+f.totalRenderDuration,0)/e.length,i=a/e.length,l=Array.from(this.componentRenderCounts.entries()).sort((d,f)=>f[1]-d[1]).slice(0,5).map(([d,f])=>({name:d,count:f})),u=Array.from(this.stateToComponentMap.entries()).sort((d,f)=>f[1].size-d[1].size).slice(0,5).map(([d,f])=>({path:d,affectedComponents:f.size}));return{totalStateChanges:e.length,totalRenders:a,avgRenderDuration:r,avgComponentsPerChange:i,topRenderedComponents:l,topInfluentialPaths:u}}getComponentsAffectedByState(e){const a=this.stateToComponentMap.get(e);return a?Array.from(a):[]}getComponentRenderHistory(e){return this.stateRenderingLogs.filter(a=>a.renderedComponents.some(r=>r.componentName===e))}clearStateRenderingLogs(){this.stateRenderingLogs=[],this.componentRenderCounts.clear(),this.stateToComponentMap.clear(),this.currentStateChangeContext=null,this.stateRenderingIdCounter=0}trackComponentStateSource(e,a,r,i){this.config.enabled&&this.componentStateSources.set(e,{componentId:e,componentName:a,stateSource:r,stateProvider:i})}trackDynamicState(e,a){this.config.enabled&&this.dynamicStates.set(e,a)}trackContextFlow(e,a,r,i,l,u){if(!this.config.enabled)return;const d={component:a,componentId:e,contextReceived:r,passedToChildren:i,usedInRender:l};if(this.contextFlowNodes.set(e,d),u){const f=this.contextFlowNodes.get(u);f&&(f.children||(f.children=[]),f.children.push(d))}}getStateHierarchyInfo(e=!0){const a=this.buildStateHierarchyLayers(),r=this.detectStateConflicts(a),i=Array.from(this.componentStateSources.values());return{layers:e?a.map(u=>({...u,values:this.summarizeValues(u.values,2)})):a,conflicts:r,componentStateSources:i,timestamp:Date.now()}}summarizeValues(e,a,r=0){if(e==null)return e;if(typeof e!="object")return typeof e=="string"&&e.length>100?e.substring(0,100)+`... (${e.length}자)`:e;if(r>=a){if(Array.isArray(e))return`[Array(${e.length})]`;const u=Object.keys(e);return`{${u.slice(0,5).join(", ")}${u.length>5?`, ... +${u.length-5}`:""}}`}if(Array.isArray(e))return e.length<=3?e.map(u=>this.summarizeValues(u,a,r+1)):{__type:"array",__length:e.length,__preview:e.slice(0,3).map(u=>this.summarizeValues(u,a,r+1))};const i={},l=Object.keys(e);for(const u of l)i[u]=this.summarizeValues(e[u],a,r+1);return i}buildStateHierarchyLayers(){const e=[];try{const r=window.G7Core?.state?.get?.();if(!r)return e;r._local&&e.push({name:"Global _local",type:"global",path:"_local",values:r._local,priority:1}),r._global&&e.push({name:"Global _global",type:"global",path:"_global",values:r._global,priority:1});for(const[l,u]of this.dynamicStates)u&&Object.keys(u).length>0&&e.push({name:`DynamicState (${l})`,type:"dynamicState",componentId:l,values:u,priority:2});const i=this.computeEffectiveState(r._local||{});e.push({name:"Effective _local (merged)",type:"effective",values:i,priority:3})}catch(a){console.warn("[G7DevTools] 상태 계층 빌드 실패:",a)}return e}computeEffectiveState(e){const a={...e};for(const[,r]of this.dynamicStates)r._local&&Object.assign(a,r._local);return a}detectStateConflicts(e){const a=[],r=e.find(l=>l.type==="global"&&l.path==="_local");if(!r)return a;const i=e.filter(l=>l.type==="dynamicState");for(const l of i){const u=l.values._local||l.values;for(const[d,f]of Object.entries(u)){const g=r.values[d];if(JSON.stringify(g)!==JSON.stringify(f)){const m=[],b=[];for(const v of this.componentStateSources.values())v.stateSource.local.some(E=>E===`_local.${d}`||E===d)&&(v.stateProvider.type==="dynamicState"?m.push(v.componentName):v.stateProvider.type==="globalState"&&b.push(v.componentName));a.push({path:`_local.${d}`,globalValue:g,dynamicStateValue:f,effectiveValue:f,usedBy:m,notUsedBy:b,severity:b.length>0?"warning":"info",description:b.length>0?`${b.join(", ")}은(는) globalState._local을 읽어 dynamicState 값을 사용하지 못함`:"dynamicState 값이 globalState와 다르지만 모든 컴포넌트가 dynamicState를 사용"})}}}return a}getContextFlowInfo(){const e=[],a=new Set(this.contextFlowNodes.keys());for(const r of this.contextFlowNodes.values())if(r.children)for(const i of r.children)a.delete(i.componentId);for(const r of a){const i=this.contextFlowNodes.get(r);i&&e.push(i)}return{rootComponent:e.length>0?e[0].component:"Unknown",contextFlow:e,timestamp:Date.now()}}clearStateHierarchyData(){this.componentStateSources.clear(),this.contextFlowNodes.clear(),this.dynamicStates.clear()}trackComponentStyle(e,a,r,i){if(!this.config.enabled)return;const l=this.analyzeTailwindClasses(r),u={componentId:e,componentName:a,classes:r,computedStyles:i,tailwindAnalysis:l};this.componentStyles.set(e,u),this.detectStyleIssues(u)}analyzeTailwindClasses(e){const a=[],r=[],i=[],l=[],u=["sm:","md:","lg:","xl:","2xl:"],d=[/bg-\w+-\d+/,/text-\w+-\d+/,/border-\w+-\d+/];for(const f of e){l.push(f),f.startsWith("dark:")&&a.push(f);for(const g of u)if(f.startsWith(g)){r.push(f);break}for(const g of d)if(g.test(f)){i.push(f);break}}return{usedClasses:l,darkClasses:a,responsiveClasses:r,dynamicClasses:i}}detectStyleIssues(e){const{componentId:a,componentName:r,computedStyles:i,tailwindAnalysis:l}=e;(i.opacity==="0"||i.visibility==="hidden"||i.display==="none"||i.width==="0px"&&i.height==="0px")&&this.addStyleIssue({id:this.generateId(),type:"invisible-element",componentId:a,componentName:r,property:i.opacity==="0"?"opacity":i.visibility==="hidden"?"visibility":i.display==="none"?"display":"width/height",currentValue:i.opacity==="0"?"0":i.visibility==="hidden"?"hidden":i.display==="none"?"none":"0px",severity:"warning",description:"요소가 화면에 보이지 않습니다.",suggestion:"opacity, visibility, display, width/height 값을 확인하세요."});const u=l.usedClasses.filter(f=>f.startsWith("bg-")&&!f.startsWith("dark:")),d=l.darkClasses.filter(f=>f.includes("bg-"));u.length>0&&d.length===0&&this.addStyleIssue({id:this.generateId(),type:"dark-mode-missing",componentId:a,componentName:r,property:"background-color",currentValue:u.join(", "),expectedValue:"dark:bg-* 클래스 필요",severity:"info",description:"다크 모드 배경색 클래스가 누락되었습니다.",suggestion:`${u[0]}에 대응하는 dark: 클래스를 추가하세요.`}),l.dynamicClasses.length>0&&this.addStyleIssue({id:this.generateId(),type:"tailwind-purging",componentId:a,componentName:r,property:"class",currentValue:l.dynamicClasses.join(", "),severity:"info",description:"동적으로 생성된 Tailwind 클래스가 있습니다.",suggestion:"tailwind.config.js의 safelist에 추가하거나 전체 클래스명을 상수로 정의하세요."})}addStyleIssue(e){this.styleIssues.some(r=>r.componentId===e.componentId&&r.type===e.type&&r.property===e.property)||this.styleIssues.push(e)}getStyleValidationInfo(){const e=Array.from(this.componentStyles.values());return{issues:[...this.styleIssues],componentStyles:e,stats:{totalComponents:e.length,invisibleCount:this.styleIssues.filter(a=>a.type==="invisible-element").length,tailwindIssueCount:this.styleIssues.filter(a=>a.type==="tailwind-purging").length,darkModeIssueCount:this.styleIssues.filter(a=>a.type==="dark-mode-missing").length},timestamp:Date.now()}}clearStyleValidationData(){this.styleIssues=[],this.componentStyles.clear()}trackAuthEvent(e,a,r,i){if(!this.config.enabled)return;const l={id:`auth_${++this.authEventIdCounter}`,type:e,timestamp:Date.now(),success:a,error:r,details:i};this.authEvents.push(l),this.authEvents.length>this.maxAuthEventHistory&&(this.authEvents=this.authEvents.slice(-this.maxAuthEventHistory))}trackAuthHeader(e,a,r,i,l){if(!this.config.enabled)return;const u={url:e,hasAuthHeader:a,headerType:r,tokenValid:i??!1,responseStatus:l,timestamp:Date.now()};this.authHeaderHistory.push(u),this.authHeaderHistory.length>this.maxAuthEventHistory&&(this.authHeaderHistory=this.authHeaderHistory.slice(-this.maxAuthEventHistory)),l===401&&this.trackAuthEvent("api-unauthorized",!1,`401 Unauthorized: ${e}`,{url:e})}getAuthState(){try{const e=window.G7Core,a=e?.api;let r=e?.auth;!r&&e?.AuthManager?.getInstance&&(r=e.AuthManager.getInstance());const i=a?.getToken?.()||r?.getAccessToken?.()||localStorage.getItem("auth_token")||localStorage.getItem("access_token"),l=r?.getRefreshToken?.()||localStorage.getItem("refresh_token");let u="unknown",d=r?.getUser?.();if(d&&(u="AuthManager"),!d){const S=e?.state?.get?.();d=S?._global?.user||S?._global?.currentUser||S?.user||S?.currentUser,d&&(u="G7Core.state")}const f=r?.isAuthenticated?.()??!1;let g="memory";localStorage.getItem("auth_token")||localStorage.getItem("access_token")?g="localStorage":(sessionStorage.getItem("auth_token")||sessionStorage.getItem("access_token"))&&(g="sessionStorage");const m=!!i&&(!!d||f);let b;i&&typeof i=="string"&&i.length>20?b=`${i.substring(0,10)}...${i.substring(i.length-6)}`:i&&(b="***");const v=d?{id:d.id,email:d.email,name:d.name,roles:d.roles?.map(S=>typeof S=="string"?{name:S}:{id:S.id,name:S.name,guard_name:S.guard_name}),permissions:d.permissions?.map(S=>typeof S=="string"?{name:S}:{id:S.id,name:S.name,guard_name:S.guard_name}),avatar:d.avatar||d.profile_photo_url||d.profile_image,created_at:d.created_at,updated_at:d.updated_at,last_login_at:d.last_login_at,email_verified_at:d.email_verified_at,...d.phone&&{phone:d.phone},...d.nickname&&{nickname:d.nickname},...d.status&&{status:d.status},...d.locale&&{locale:d.locale}}:void 0;return{isAuthenticated:m,user:v,tokens:{hasAccessToken:!!i,hasRefreshToken:!!l,storage:g,accessTokenPreview:b},lastActivity:Date.now(),source:u}}catch{return{isAuthenticated:!1,tokens:{hasAccessToken:!1,hasRefreshToken:!1,storage:"memory"},source:"unknown"}}}getAuthDebugInfo(){const e=[...this.authEvents];return{state:this.getAuthState(),events:e,headerAnalysis:[...this.authHeaderHistory],stats:{loginAttempts:e.filter(a=>a.type==="login").length,successfulLogins:e.filter(a=>a.type==="login"&&a.success).length,failedLogins:e.filter(a=>a.type==="login"&&!a.success).length,tokenRefreshes:e.filter(a=>a.type==="token-refresh").length,unauthorizedResponses:e.filter(a=>a.type==="api-unauthorized").length},timestamp:Date.now()}}clearAuthData(){this.authEvents=[],this.authHeaderHistory=[],this.authEventIdCounter=0}trackLayoutLoad(e,a,r,i="api"){if(!this.config.enabled)return;const l=Date.now();this.currentLayout={layoutPath:e,templateId:a,layoutJson:this.sanitizeObject(r),loadedAt:l,version:r.version,layoutName:r.layout_name,source:i};const u={id:`layout-${++this.layoutIdCounter}`,layoutPath:e,templateId:a,loadedAt:l,source:i,version:r.version};this.layoutHistory.push(u),this.layoutHistory.length>this.maxLayoutHistory&&this.layoutHistory.shift(),this.layoutStats.totalLoads++,i==="cache"?this.layoutStats.cacheHits++:this.layoutStats.apiLoads++}getCurrentLayout(){return this.currentLayout}getLayoutHistory(){return[...this.layoutHistory]}getLayoutDebugInfo(){return{current:this.currentLayout,history:[...this.layoutHistory],stats:{...this.layoutStats}}}clearLayoutData(){this.currentLayout=null,this.layoutHistory=[],this.layoutIdCounter=0,this.layoutStats={totalLoads:0,cacheHits:0,apiLoads:0}}startHandlerExecution(e){if(!this.config.enabled)return"";const a=`exec_${++this.executionIdCounter}_${Date.now()}`,r={handlerName:e,executionId:a,startTime:Date.now(),stateChanges:[],dataSourceChanges:[],alerts:[]};if(this.executionDetails.set(a,r),this.executionDetails.size>this.maxExecutionDetails){const i=Array.from(this.executionDetails.keys());i.slice(0,i.length-this.maxExecutionDetails).forEach(u=>this.executionDetails.delete(u))}return a}endHandlerExecution(e,a,r,i){if(!this.config.enabled||!e)return;const l=this.executionDetails.get(e);if(!l)return;l.endTime=Date.now(),l.duration=l.endTime-l.startTime,l.exitReason=a,l.exitLocation=r,l.exitDescription=i;const u=this.changeExpectations.get(e);u&&(l.expectedChanges=u,this.checkExpectations(e,l,u),this.changeExpectations.delete(e)),a==="normal"&&l.stateChanges.length===0&&l.dataSourceChanges.length===0&&this.addChangeAlert(e,{type:"no-state-change",severity:"warning",message:`핸들러 "${l.handlerName}"이(가) 상태 변경 없이 완료됨`,description:"핸들러가 성공적으로 완료되었지만 상태나 데이터소스 변경이 없습니다. 의도한 동작인지 확인하세요.",handlerName:l.handlerName,suggestion:'핸들러 내부 조건문을 확인하거나 DevTools의 "변경감지" 탭에서 exitLocation을 확인하세요.',docLink:"troubleshooting-state.md"}),(a==="early-return-condition"||a==="early-return-validation")&&this.addChangeAlert(e,{type:"early-return-detected",severity:"info",message:`핸들러 "${l.handlerName}"이(가) early return으로 종료됨`,description:i||`종료 위치: ${r||"알 수 없음"}`,handlerName:l.handlerName,suggestion:a==="early-return-validation"?"검증 실패로 인한 early return입니다. 입력 데이터를 확인하세요.":"조건부 early return입니다. 조건문의 평가 결과를 확인하세요."})}recordExitReason(e,a,r,i){if(!this.config.enabled||!e)return;const l=this.executionDetails.get(e);l&&(l.exitReason=a,l.exitLocation=r,l.exitDescription=i)}recordStateChange(e,a,r,i,l){if(!this.config.enabled)return;const u={id:`sc_${++this.stateChangeIdCounter}`,path:a,changeType:r,oldValue:this.safeClone(i),newValue:this.safeClone(l),timestamp:Date.now(),comparison:this.compareValues(i,l),executionId:e};if(this.stateChangeHistory.push(u),e){const d=this.executionDetails.get(e);d&&d.stateChanges.push(u)}this.stateChangeHistory.length>this.maxStateChangeHistory&&this.stateChangeHistory.splice(0,this.stateChangeHistory.length-this.maxStateChangeHistory),u.comparison.isDeepEqual&&typeof i=="object"&&i!==null&&this.addChangeAlert(e||"",{type:"object-reference-same",severity:"warning",message:`상태 "${a}"가 변경되었으나 값이 동일함`,description:"객체 참조가 동일하거나 깊은 비교 결과 변경이 없습니다. 변경 감지가 실패할 수 있습니다.",handlerName:e&&this.executionDetails.get(e)?.handlerName||"unknown",statePath:a,suggestion:"불변성을 유지하여 새 객체를 생성하세요. 예: { ...oldObject, newField: value }",docLink:"troubleshooting-state.md#object-mutation"})}recordDataSourceChange(e,a,r,i,l){if(!this.config.enabled)return;const u={dataSourceId:a,changeType:r,timestamp:Date.now(),previousStatus:i,newStatus:l,executionId:e};if(this.dataSourceChangeHistory.push(u),e){const d=this.executionDetails.get(e);d&&d.dataSourceChanges.push(u)}this.dataSourceChangeHistory.length>this.maxStateChangeHistory&&this.dataSourceChangeHistory.splice(0,this.dataSourceChangeHistory.length-this.maxStateChangeHistory)}expectChange(e,a,r){if(!this.config.enabled||!e)return;const i=this.executionDetails.get(e);if(!i)return;const l={expectedStatePaths:a,expectedDataSources:r,setAt:Date.now(),source:i.handlerName};this.changeExpectations.set(e,l)}checkExpectations(e,a,r){const i=new Set(a.stateChanges.map(u=>u.path)),l=new Set(a.dataSourceChanges.map(u=>u.dataSourceId));for(const u of r.expectedStatePaths)i.has(u)||this.addChangeAlert(e,{type:"expected-not-fulfilled",severity:"error",message:`기대한 상태 변경 "${u}"가 발생하지 않음`,description:`핸들러 "${a.handlerName}"이(가) "${u}" 변경을 예고했지만 실제로 변경되지 않았습니다.`,handlerName:a.handlerName,statePath:u,suggestion:"핸들러 내부 로직을 확인하세요. early return이나 조건부 분기로 인해 변경이 생략되었을 수 있습니다.",docLink:"troubleshooting-state.md"});for(const u of r.expectedDataSources)l.has(u)||this.addChangeAlert(e,{type:"expected-not-fulfilled",severity:"error",message:`기대한 데이터소스 갱신 "${u}"가 발생하지 않음`,description:`핸들러 "${a.handlerName}"이(가) "${u}" 갱신을 예고했지만 실제로 갱신되지 않았습니다.`,handlerName:a.handlerName,dataSourceId:u,suggestion:"refetchDataSource 호출이 실행되었는지 확인하세요.",docLink:"data-sources.md"})}addChangeAlert(e,a){const r={...a,id:`alert_${++this.alertIdCounter}`,timestamp:Date.now()};if(this.changeAlerts.push(r),e){const i=this.executionDetails.get(e);i&&i.alerts.push(r)}this.changeAlerts.length>this.maxChangeAlerts&&this.changeAlerts.splice(0,this.changeAlerts.length-this.maxChangeAlerts)}compareValues(e,a){const r=this.getValueType(e),i=this.getValueType(a),l=r!==i;let u=!1,d;return!l&&(r==="object"||r==="array")?(u=this.deepEqual(e,a),!u&&r==="object"&&(d=this.getChangedKeys(e,a))):u=e===a,{typeChanged:l,oldType:r,newType:i,isDeepEqual:u,changedKeys:d}}getValueType(e){return e===null?"null":e===void 0?"undefined":Array.isArray(e)?"array":typeof e}deepEqual(e,a){if(e===a)return!0;if(typeof e!=typeof a)return!1;if(e===null||a===null||typeof e!="object")return e===a;if(Array.isArray(e)!==Array.isArray(a))return!1;const r=Object.keys(e),i=Object.keys(a);if(r.length!==i.length)return!1;for(const l of r)if(!i.includes(l)||!this.deepEqual(e[l],a[l]))return!1;return!0}getChangedKeys(e,a){const r=[],i=new Set([...Object.keys(e),...Object.keys(a)]);for(const l of i)this.deepEqual(e[l],a[l])||r.push(l);return r}getChangeDetectionInfo(){const e=Array.from(this.executionDetails.values()),a={totalExecutions:e.length,executionsWithStateChange:e.filter(r=>r.stateChanges.length>0).length,executionsWithoutStateChange:e.filter(r=>r.stateChanges.length===0&&r.exitReason==="normal").length,earlyReturnCount:e.filter(r=>r.exitReason==="early-return-condition"||r.exitReason==="early-return-validation").length,alertCount:this.changeAlerts.length,alertsByType:this.getAlertsByType()};return{executionDetails:e,stateChangeHistory:[...this.stateChangeHistory],dataSourceChangeHistory:[...this.dataSourceChangeHistory],alerts:[...this.changeAlerts],stats:a,timestamp:Date.now()}}getAlertsByType(){const e={"no-state-change":0,"no-datasource-change":0,"expected-not-fulfilled":0,"object-reference-same":0,"early-return-detected":0,"async-timing-issue":0};for(const a of this.changeAlerts)e[a.type]++;return e}clearChangeDetectionData(){this.executionDetails.clear(),this.stateChangeHistory=[],this.dataSourceChangeHistory=[],this.changeAlerts=[],this.changeExpectations.clear(),this.executionIdCounter=0,this.stateChangeIdCounter=0,this.alertIdCounter=0}getRecentAlerts(e=10,a){let r=[...this.changeAlerts];return a&&(r=r.filter(i=>i.severity===a)),r.slice(-e)}getHandlerExecutions(e,a=10){return Array.from(this.executionDetails.values()).filter(i=>i.handlerName===e).slice(-a)}findExecutionInStack(e){return this.sequenceExecutionStack.find(a=>a.sequenceId===e)}startSequenceExecution(e){if(!this.config.enabled)return"";const a=`seq_${++this.sequenceIdCounter}_${Date.now()}`,r={sequenceId:a,startTime:Date.now(),totalDuration:0,trigger:e,actions:[],status:"running"};return this.sequenceExecutionStack.push(r),a}captureSequenceActionBefore(e,a,r,i,l){if(!this.config.enabled)return;const u=this.findExecutionInStack(e);if(!u)return;const d={index:a,handler:r,params:this.safeClone(i),stateBeforeAction:{_global:this.safeClone(l._global),_local:this.safeClone(l._local),_isolated:l._isolated?this.safeClone(l._isolated):void 0},stateAfterAction:{_global:{},_local:{}},duration:0,status:"success"};u.actions.push(d)}captureSequenceActionAfter(e,a,r,i,l,u){if(!this.config.enabled)return;const d=this.findExecutionInStack(e);if(!d)return;const f=d.actions.find(m=>m.index===a);if(!f)return;f.stateAfterAction={_global:this.safeClone(r._global),_local:this.safeClone(r._local),_isolated:r._isolated?this.safeClone(r._isolated):void 0},f.duration=i,f.result=this.safeClone(l),f.stateDiff={global:this.computeStateDiff(f.stateBeforeAction._global,f.stateAfterAction._global),local:this.computeStateDiff(f.stateBeforeAction._local,f.stateAfterAction._local)},f.stateBeforeAction._isolated&&f.stateAfterAction._isolated&&(f.stateDiff.isolated=this.computeStateDiff(f.stateBeforeAction._isolated,f.stateAfterAction._isolated));const g=window.__g7PendingLocalState;g&&(f.pendingState=this.safeClone(g)),u&&(f.status="error",f.error={name:u.name,message:u.message,stack:u.stack})}endSequenceExecution(e,a){if(!this.config.enabled)return;const r=this.sequenceExecutionStack.findIndex(l=>l.sequenceId===e);if(r===-1)return;const i=this.sequenceExecutionStack[r];if(i.endTime=Date.now(),i.totalDuration=i.endTime-i.startTime,a){i.status="error",i.error={name:a.name,message:a.message,stack:a.stack};const l=i.actions.find(u=>u.status==="error");l&&(i.failedAtIndex=l.index)}else i.status="success";this.sequenceExecutions.push(i),this.sequenceExecutions.length>this.maxSequenceExecutions&&this.sequenceExecutions.shift(),this.sequenceExecutionStack.splice(r,1)}computeStateDiff(e,a){const r=[],i=[],l=[],u=new Set(Object.keys(e)),d=new Set(Object.keys(a));for(const f of d)u.has(f)||r.push(f);for(const f of u)d.has(f)||i.push(f);for(const f of u)if(d.has(f)){const g=e[f],m=a[f];JSON.stringify(g)!==JSON.stringify(m)&&l.push({path:f,oldValue:g,newValue:m})}return{added:r,removed:i,changed:l}}getSequenceTrackingInfo(){const e=this.getSequenceStats(),a=this.sequenceExecutionStack.length>0?this.sequenceExecutionStack[this.sequenceExecutionStack.length-1]:void 0;return{executions:[...this.sequenceExecutions],currentExecution:a,stats:e}}getSequenceStats(){const e=this.sequenceExecutions,a=e.length,r=e.filter(g=>g.status==="success").length,i=e.filter(g=>g.status==="error").length,l=e.reduce((g,m)=>g+m.actions.length,0),u=a>0?e.reduce((g,m)=>g+m.totalDuration,0)/a:0,d={};for(const g of e)for(const m of g.actions)d[m.handler]=(d[m.handler]||0)+1;const f=Object.entries(d).sort(([,g],[,m])=>m-g).slice(0,5).map(([g,m])=>({handler:g,count:m}));return{totalExecutions:a,successCount:r,errorCount:i,totalActions:l,avgDuration:u,topHandlers:f}}clearSequenceData(){this.sequenceExecutions=[],this.sequenceExecutionStack=[],this.sequenceIdCounter=0}getSequenceExecution(e){const a=this.findExecutionInStack(e);return a||this.sequenceExecutions.find(r=>r.sequenceId===e)}getRecentSequences(e=10){return this.sequenceExecutions.slice(-e)}registerStateCaptureForHandler(e,a,r){if(!this.config.enabled)return;const i=new Map,l=Date.now();for(const u of a)i.set(u,{value:this.safeClone(r[u]),capturedAt:l});this.stateCaptureRegistry.set(e,i)}detectStaleClosure(e,a,r,i,l){if(!this.config.enabled)return[];const u=this.stateCaptureRegistry.get(e);if(!u)return[];const d=Date.now(),f=[];for(const[g,m]of u){const b=this.getValueByPath(r,g),v=d-m.capturedAt;if(!this.isDeepEqual(m.value,b)&&v>0){const S=this.createStaleClosureWarning(i,a,g,m.value,m.capturedAt,b,d,v,l);f.push(S),this.addStaleClosureWarning(S)}}return this.stateCaptureRegistry.delete(e),f}trackStaleClosureWarning(e){if(!this.config.enabled)return;const a=Date.now(),r=this.createStaleClosureWarning(e.type,e.location,e.capturedPath,e.capturedValue,e.capturedAt,e.currentValue,a,a-e.capturedAt,e.actionId,e.stackTrace);this.addStaleClosureWarning(r)}createStaleClosureWarning(e,a,r,i,l,u,d,f,g,m){const b=this.getStaleClosureSeverity(e,f),{description:v,suggestion:S,docLink:E}=this.getStaleClosureMessages(e,r,f);return{id:`stale_${++this.staleClosureIdCounter}_${Date.now()}`,timestamp:Date.now(),type:e,location:a,capturedState:{path:r,capturedValue:this.safeClone(i),capturedAt:l},currentState:{path:r,currentValue:this.safeClone(u),retrievedAt:d},timeDiff:f,severity:b,description:v,suggestion:S,docLink:E,actionId:g,stackTrace:m}}getStaleClosureSeverity(e,a){if(a>5e3)return"error";if(a>1e3)return"warning";switch(e){case"async-state-capture":case"sequence-state-mismatch":return"warning";case"callback-state-capture":case"timeout-state-capture":return"info";case"event-handler-stale":return"warning";default:return"info"}}getStaleClosureMessages(e,a,r){const i=r<1e3?`${r}ms`:`${(r/1e3).toFixed(1)}s`;switch(e){case"async-state-capture":return{description:`await 후 ${i} 경과 시점에 '${a}' 상태가 변경됨. 캡처된 상태 대신 최신 상태를 사용해야 함`,suggestion:"await 이후에는 G7Core.state.get()으로 최신 상태를 다시 조회하거나, useRef + getter 패턴을 사용하세요",docLink:"troubleshooting-state-closure.md"};case"callback-state-capture":return{description:`콜백에서 ${i} 전에 캡처된 '${a}' 상태를 사용 중. 최신 상태와 다름`,suggestion:"콜백에서 상태를 참조할 때는 stateRef.current 패턴 또는 G7Core.state.get()를 사용하세요",docLink:"troubleshooting-state-closure.md"};case"timeout-state-capture":return{description:`setTimeout/setInterval 콜백에서 '${a}' 상태가 ${i} 전 값 사용 중`,suggestion:"타이머 콜백 내에서는 G7Core.state.get()으로 최신 상태를 조회하세요",docLink:"troubleshooting-state-closure.md"};case"sequence-state-mismatch":return{description:`sequence 내 '${a}' 상태가 이전 액션 결과와 불일치. context.state 대신 캡처된 값 사용 의심`,suggestion:"sequence 내에서는 context.state 또는 $prev를 사용하여 최신 상태를 참조하세요",docLink:"troubleshooting-state-setstate.md"};case"event-handler-stale":return{description:`이벤트 핸들러에서 ${i} 전에 바인딩된 '${a}' 상태 사용 중`,suggestion:"이벤트 핸들러에서 상태를 참조할 때는 useRef 패턴 또는 G7Core.state.get()를 사용하세요",docLink:"troubleshooting-state-closure.md"};default:return{description:`'${a}' 상태에서 stale closure 감지됨 (${i} 경과)`,suggestion:"상태 참조 시 최신 값을 사용하는지 확인하세요"}}}addStaleClosureWarning(e){this.staleClosureWarnings.push(e),this.staleClosureWarnings.length>this.maxStaleClosureWarnings&&this.staleClosureWarnings.shift()}getValueByPath(e,a){const r=a.split(".");let i=e;for(const l of r){if(i==null)return;i=i[l]}return i}isDeepEqual(e,a){if(e===a)return!0;if(e===null||a===null)return e===a;if(typeof e!=typeof a)return!1;if(typeof e!="object")return e===a;try{return JSON.stringify(e)===JSON.stringify(a)}catch{return!1}}getStaleClosureTrackingInfo(){const e=this.getStaleClosureStats();return{warnings:[...this.staleClosureWarnings],stats:e,timestamp:Date.now()}}getStaleClosureStats(){const e=this.staleClosureWarnings,a={"async-state-capture":0,"callback-state-capture":0,"timeout-state-capture":0,"sequence-state-mismatch":0,"event-handler-stale":0};for(const f of e)a[f.type]++;const r={info:0,warning:0,error:0};for(const f of e)r[f.severity]++;const i={};for(const f of e)i[f.location]=(i[f.location]||0)+1;const l=Object.entries(i).sort(([,f],[,g])=>g-f).slice(0,5).map(([f,g])=>({location:f,count:g})),u={};for(const f of e)u[f.capturedState.path]=(u[f.capturedState.path]||0)+1;const d=Object.entries(u).sort(([,f],[,g])=>g-f).slice(0,5).map(([f,g])=>({path:f,count:g}));return{totalWarnings:e.length,warningsByType:a,warningsBySeverity:r,topLocations:l,topAffectedPaths:d}}clearStaleClosureData(){this.staleClosureWarnings=[],this.staleClosureIdCounter=0,this.stateCaptureRegistry.clear()}getRecentStaleClosureWarnings(e=10,a){let r=[...this.staleClosureWarnings];return a&&(r=r.filter(i=>i.severity===a)),r.slice(-e)}safeClone(e){if(e==null||typeof e!="object")return e;try{return JSON.parse(JSON.stringify(e))}catch{if(Array.isArray(e))return e.map(r=>{try{return JSON.parse(JSON.stringify(r))}catch{return"[Unserializable]"}});const a={};for(const r of Object.keys(e))try{a[r]=JSON.parse(JSON.stringify(e[r]))}catch{a[r]="[Unserializable]"}return a}}};$(yi,"instance");let Tr=yi;const Bn=ct("LayoutLoader");class ba extends Error{constructor(a,r,i){super(a);$(this,"code");$(this,"details");this.code=r,this.details=i,this.name="LayoutLoaderError"}}class tf{constructor(e){$(this,"componentRegistry");$(this,"currentLayout",null);$(this,"layoutCache",new Map);$(this,"cacheVersion",0);this.componentRegistry=e}setCacheVersion(e){this.cacheVersion!==e&&(Bn.log("Cache version updated:",this.cacheVersion,"->",e),this.cacheVersion=e,this.layoutCache.clear())}getCacheVersion(){return this.cacheVersion}async loadLayout(e,a){const r=`${e}:${a}`;if(this.layoutCache.has(r)){Bn.log("Loading layout from cache:",a);const l=await this.layoutCache.get(r),u=JSON.parse(JSON.stringify(l));return this.currentLayout=u,Tr.getInstance().trackLayoutLoad(a,e,u,"cache"),u}const i=this.fetchLayout(e,a);return this.layoutCache.set(r,i),i.catch(()=>{this.layoutCache.get(r)===i&&this.layoutCache.delete(r)}),i}async fetchLayout(e,a,r=!1){try{const i=this.cacheVersion>0?this.cacheVersion:null;let l;if(a.startsWith("__preview__/")){const v=a.replace("__preview__/","");l=La(`/api/layouts/preview/${v}`,"json",i)}else l=La(`/api/layouts/${e}/${a}`,"json",i);Bn.log("Fetching layout from API:",l);const u=$a(),d=r?null:u.getToken(),f={Accept:"application/json"};d&&(f.Authorization=`Bearer ${d}`);const g=await xl(l,{init:{headers:f},label:`layout: ${a}`});let m;try{m=await g.json()}catch{m=null}if(!g.ok){if(g.status===401&&!r&&d){Bn.log("Token invalid, removing and retrying without token"),u.removeToken();try{return await this.fetchLayout(e,a,!0)}catch(S){throw S instanceof ba&&S.details?.status===401?new ba(S.message,S.code,{...S.details,hadToken:!0}):S}}const v=m?.message||m?.error;throw new ba(`Failed to fetch layout: ${g.status} ${g.statusText}`,"FETCH_FAILED",{status:g.status,statusText:g.statusText,url:l,apiMessage:v})}const b=m.data||m;return this.validateLayoutData(b),this.currentLayout=b,Tr.getInstance().trackLayoutLoad(a,e,b,"api"),Bn.log("Layout fetched and cached successfully:",b.layout_name),b}catch(i){const l=`${e}:${a}`;throw this.layoutCache.delete(l),i instanceof ba?i:new ba("Failed to load layout","LOAD_FAILED",{originalError:i})}}prefetchLayout(e,a){return this.loadLayout(e,a)}validateLayoutData(e){if(!e.version)throw new ba("Layout data missing required field: version","VALIDATION_FAILED",{field:"version"});if(!e.layout_name)throw new ba("Layout data missing required field: layout_name","VALIDATION_FAILED",{field:"layout_name"});if(!Array.isArray(e.components))throw new ba('Layout data field "components" must be an array',"VALIDATION_FAILED",{field:"components",value:e.components});Bn.log("Layout data validation passed")}renderLayout(e,a){try{const r=a||this.currentLayout;if(!r)throw new ba("No layout data to render","NO_LAYOUT_DATA");Bn.log("Rendering layout:",r.layout_name),e.innerHTML="",this.renderComponents(e,r.components),Bn.log("Layout rendered successfully")}catch(r){Bn.error("Render error:",r),this.renderErrorState(e,r)}}renderComponents(e,a){for(const r of a){const i=this.renderComponent(r);i&&e.appendChild(i)}}renderComponent(e){try{if(!this.componentRegistry.getComponent(e.type))return Bn.warn(`Component not found: ${e.type}`),this.createPlaceholderElement(e.type);const r=document.createElement("div");return r.setAttribute("data-component",e.type),e.props&&Object.entries(e.props).forEach(([i,l])=>{r.setAttribute(`data-prop-${i}`,JSON.stringify(l))}),e.children&&e.children.length>0?this.renderComponents(r,e.children):e.text&&(r.textContent=e.text),r}catch(a){return Bn.error(`Error rendering component ${e.type}:`,a),this.createErrorElement(e.type,a)}}createPlaceholderElement(e){const a=document.createElement("div");return a.className="component-placeholder",a.setAttribute("data-component-type",e),a.innerHTML=` + `},YC={onDragStart(o){let{active:e}=o;return"Picked up draggable item "+e.id+"."},onDragOver(o){let{active:e,over:n}=o;return n?"Draggable item "+e.id+" was moved over droppable area "+n.id+".":"Draggable item "+e.id+" is no longer over a droppable area."},onDragEnd(o){let{active:e,over:n}=o;return n?"Draggable item "+e.id+" was dropped over droppable area "+n.id:"Draggable item "+e.id+" was dropped."},onDragCancel(o){let{active:e}=o;return"Dragging was cancelled. Draggable item "+e.id+" was dropped."}};function XC(o){let{announcements:e=YC,container:n,hiddenTextDescribedById:r,screenReaderInstructions:i=WC}=o;const{announce:l,announcement:u}=VC(),d=mo("DndLiveRegion"),[f,g]=I.useState(!1);if(I.useEffect(()=>{g(!0)},[]),FC(I.useMemo(()=>({onDragStart(b){let{active:v}=b;l(e.onDragStart({active:v}))},onDragMove(b){let{active:v,over:S}=b;e.onDragMove&&l(e.onDragMove({active:v,over:S}))},onDragOver(b){let{active:v,over:S}=b;l(e.onDragOver({active:v,over:S}))},onDragEnd(b){let{active:v,over:S}=b;l(e.onDragEnd({active:v,over:S}))},onDragCancel(b){let{active:v,over:S}=b;l(e.onDragCancel({active:v,over:S}))}}),[l,e])),!f)return null;const m=Xe.createElement(Xe.Fragment,null,Xe.createElement(qC,{id:r,value:i.draggable}),Xe.createElement(GC,{id:d,announcement:u}));return n?Ar.createPortal(m,n):m}var rn;(function(o){o.DragStart="dragStart",o.DragMove="dragMove",o.DragEnd="dragEnd",o.DragCancel="dragCancel",o.DragOver="dragOver",o.RegisterDroppable="registerDroppable",o.SetDroppableDisabled="setDroppableDisabled",o.UnregisterDroppable="unregisterDroppable"})(rn||(rn={}));function ac(){}function wm(o,e){return I.useMemo(()=>({sensor:o,options:e??{}}),[o,e])}function JC(){for(var o=arguments.length,e=new Array(o),n=0;n[...e].filter(r=>r!=null),[...e])}const ya=Object.freeze({x:0,y:0});function Cm(o,e){return Math.sqrt(Math.pow(o.x-e.x,2)+Math.pow(o.y-e.y,2))}function Em(o,e){let{data:{value:n}}=o,{data:{value:r}}=e;return n-r}function QC(o,e){let{data:{value:n}}=o,{data:{value:r}}=e;return r-n}function _m(o){let{left:e,top:n,height:r,width:i}=o;return[{x:e,y:n},{x:e+i,y:n},{x:e,y:n+r},{x:e+i,y:n+r}]}function Am(o,e){if(!o||o.length===0)return null;const[n]=o;return n[e]}function xm(o,e,n){return e===void 0&&(e=o.left),n===void 0&&(n=o.top),{x:e+o.width*.5,y:n+o.height*.5}}const ZC=o=>{let{collisionRect:e,droppableRects:n,droppableContainers:r}=o;const i=xm(e,e.left,e.top),l=[];for(const u of r){const{id:d}=u,f=n.get(d);if(f){const g=Cm(xm(f),i);l.push({id:d,data:{droppableContainer:u,value:g}})}}return l.sort(Em)},eE=o=>{let{collisionRect:e,droppableRects:n,droppableContainers:r}=o;const i=_m(e),l=[];for(const u of r){const{id:d}=u,f=n.get(d);if(f){const g=_m(f),m=i.reduce((v,S,_)=>v+Cm(g[_],S),0),b=Number((m/4).toFixed(4));l.push({id:d,data:{droppableContainer:u,value:b}})}}return l.sort(Em)};function tE(o,e){const n=Math.max(e.top,o.top),r=Math.max(e.left,o.left),i=Math.min(e.left+e.width,o.left+o.width),l=Math.min(e.top+e.height,o.top+o.height),u=i-r,d=l-n;if(r{let{collisionRect:e,droppableRects:n,droppableContainers:r}=o;const i=[];for(const l of r){const{id:u}=l,d=n.get(u);if(d){const f=tE(d,e);f>0&&i.push({id:u,data:{droppableContainer:l,value:f}})}}return i.sort(QC)};function aE(o,e,n){return{...o,scaleX:e&&n?e.width/n.width:1,scaleY:e&&n?e.height/n.height:1}}function Tm(o,e){return o&&e?{x:o.left-e.left,y:o.top-e.top}:ya}function rE(o){return function(n){for(var r=arguments.length,i=new Array(r>1?r-1:0),l=1;l({...u,top:u.top+o*d.y,bottom:u.bottom+o*d.y,left:u.left+o*d.x,right:u.right+o*d.x}),{...n})}}const iE=rE(1);function sE(o){if(o.startsWith("matrix3d(")){const e=o.slice(9,-1).split(/, /);return{x:+e[12],y:+e[13],scaleX:+e[0],scaleY:+e[5]}}else if(o.startsWith("matrix(")){const e=o.slice(7,-1).split(/, /);return{x:+e[4],y:+e[5],scaleX:+e[0],scaleY:+e[3]}}return null}function oE(o,e,n){const r=sE(e);if(!r)return o;const{scaleX:i,scaleY:l,x:u,y:d}=r,f=o.left-u-(1-i)*parseFloat(n),g=o.top-d-(1-l)*parseFloat(n.slice(n.indexOf(" ")+1)),m=i?o.width/i:o.width,b=l?o.height/l:o.height;return{width:m,height:b,top:g,right:f+m,bottom:g+b,left:f}}const lE={ignoreTransform:!1};function us(o,e){e===void 0&&(e=lE);let n=o.getBoundingClientRect();if(e.ignoreTransform){const{transform:g,transformOrigin:m}=Mn(o).getComputedStyle(o);g&&(n=oE(n,g,m))}const{top:r,left:i,width:l,height:u,bottom:d,right:f}=n;return{top:r,left:i,width:l,height:u,bottom:d,right:f}}function Rm(o){return us(o,{ignoreTransform:!0})}function cE(o){const e=o.innerWidth,n=o.innerHeight;return{top:0,left:0,right:e,bottom:n,width:e,height:n}}function uE(o,e){return e===void 0&&(e=Mn(o).getComputedStyle(o)),e.position==="fixed"}function dE(o,e){e===void 0&&(e=Mn(o).getComputedStyle(o));const n=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(i=>{const l=e[i];return typeof l=="string"?n.test(l):!1})}function rc(o,e){const n=[];function r(i){if(e!=null&&n.length>=e||!i)return n;if(Ud(i)&&i.scrollingElement!=null&&!n.includes(i.scrollingElement))return n.push(i.scrollingElement),n;if(!ho(i)||ym(i)||n.includes(i))return n;const l=Mn(o).getComputedStyle(i);return i!==o&&dE(i,l)&&n.push(i),uE(i,l)?n:r(i.parentNode)}return o?r(o):n}function km(o){const[e]=rc(o,1);return e??null}function Fd(o){return!tc||!o?null:os(o)?o:jd(o)?Ud(o)||o===ls(o).scrollingElement?window:ho(o)?o:null:null}function Dm(o){return os(o)?o.scrollX:o.scrollLeft}function Om(o){return os(o)?o.scrollY:o.scrollTop}function Kd(o){return{x:Dm(o),y:Om(o)}}var fn;(function(o){o[o.Forward=1]="Forward",o[o.Backward=-1]="Backward"})(fn||(fn={}));function Lm(o){return!tc||!o?!1:o===document.scrollingElement}function Mm(o){const e={x:0,y:0},n=Lm(o)?{height:window.innerHeight,width:window.innerWidth}:{height:o.clientHeight,width:o.clientWidth},r={x:o.scrollWidth-n.width,y:o.scrollHeight-n.height},i=o.scrollTop<=e.y,l=o.scrollLeft<=e.x,u=o.scrollTop>=r.y,d=o.scrollLeft>=r.x;return{isTop:i,isLeft:l,isBottom:u,isRight:d,maxScroll:r,minScroll:e}}const fE={x:.2,y:.2};function hE(o,e,n,r,i){let{top:l,left:u,right:d,bottom:f}=n;r===void 0&&(r=10),i===void 0&&(i=fE);const{isTop:g,isBottom:m,isLeft:b,isRight:v}=Mm(o),S={x:0,y:0},_={x:0,y:0},x={height:e.height*i.y,width:e.width*i.x};return!g&&l<=e.top+x.height?(S.y=fn.Backward,_.y=r*Math.abs((e.top+x.height-l)/x.height)):!m&&f>=e.bottom-x.height&&(S.y=fn.Forward,_.y=r*Math.abs((e.bottom-x.height-f)/x.height)),!v&&d>=e.right-x.width?(S.x=fn.Forward,_.x=r*Math.abs((e.right-x.width-d)/x.width)):!b&&u<=e.left+x.width&&(S.x=fn.Backward,_.x=r*Math.abs((e.left+x.width-u)/x.width)),{direction:S,speed:_}}function gE(o){if(o===document.scrollingElement){const{innerWidth:l,innerHeight:u}=window;return{top:0,left:0,right:l,bottom:u,width:l,height:u}}const{top:e,left:n,right:r,bottom:i}=o.getBoundingClientRect();return{top:e,left:n,right:r,bottom:i,width:o.clientWidth,height:o.clientHeight}}function $m(o){return o.reduce((e,n)=>cs(e,Kd(n)),ya)}function pE(o){return o.reduce((e,n)=>e+Dm(n),0)}function mE(o){return o.reduce((e,n)=>e+Om(n),0)}function yE(o,e){if(e===void 0&&(e=us),!o)return;const{top:n,left:r,bottom:i,right:l}=e(o);km(o)&&(i<=0||l<=0||n>=window.innerHeight||r>=window.innerWidth)&&o.scrollIntoView({block:"center",inline:"center"})}const bE=[["x",["left","right"],pE],["y",["top","bottom"],mE]];class Wd{constructor(e,n){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;const r=rc(n),i=$m(r);this.rect={...e},this.width=e.width,this.height=e.height;for(const[l,u,d]of bE)for(const f of u)Object.defineProperty(this,f,{get:()=>{const g=d(r),m=i[l]-g;return this.rect[f]+m},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class vo{constructor(e){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(n=>{var r;return(r=this.target)==null?void 0:r.removeEventListener(...n)})},this.target=e}add(e,n,r){var i;(i=this.target)==null||i.addEventListener(e,n,r),this.listeners.push([e,n,r])}}function vE(o){const{EventTarget:e}=Mn(o);return o instanceof e?o:ls(o)}function Yd(o,e){const n=Math.abs(o.x),r=Math.abs(o.y);return typeof e=="number"?Math.sqrt(n**2+r**2)>e:"x"in e&&"y"in e?n>e.x&&r>e.y:"x"in e?n>e.x:"y"in e?r>e.y:!1}var ea;(function(o){o.Click="click",o.DragStart="dragstart",o.Keydown="keydown",o.ContextMenu="contextmenu",o.Resize="resize",o.SelectionChange="selectionchange",o.VisibilityChange="visibilitychange"})(ea||(ea={}));function Nm(o){o.preventDefault()}function SE(o){o.stopPropagation()}var st;(function(o){o.Space="Space",o.Down="ArrowDown",o.Right="ArrowRight",o.Left="ArrowLeft",o.Up="ArrowUp",o.Esc="Escape",o.Enter="Enter",o.Tab="Tab"})(st||(st={}));const Im={start:[st.Space,st.Enter],cancel:[st.Esc],end:[st.Space,st.Enter,st.Tab]},wE=(o,e)=>{let{currentCoordinates:n}=e;switch(o.code){case st.Right:return{...n,x:n.x+25};case st.Left:return{...n,x:n.x-25};case st.Down:return{...n,y:n.y+25};case st.Up:return{...n,y:n.y-25}}};class Xd{constructor(e){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=e;const{event:{target:n}}=e;this.props=e,this.listeners=new vo(ls(n)),this.windowListeners=new vo(Mn(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(ea.Resize,this.handleCancel),this.windowListeners.add(ea.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(ea.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:e,onStart:n}=this.props,r=e.node.current;r&&yE(r),n(ya)}handleKeyDown(e){if(Gd(e)){const{active:n,context:r,options:i}=this.props,{keyboardCodes:l=Im,coordinateGetter:u=wE,scrollBehavior:d="smooth"}=i,{code:f}=e;if(l.end.includes(f)){this.handleEnd(e);return}if(l.cancel.includes(f)){this.handleCancel(e);return}const{collisionRect:g}=r.current,m=g?{x:g.left,y:g.top}:ya;this.referenceCoordinates||(this.referenceCoordinates=m);const b=u(e,{active:n,context:r.current,currentCoordinates:m});if(b){const v=yo(b,m),S={x:0,y:0},{scrollableAncestors:_}=r.current;for(const x of _){const k=e.code,{isTop:O,isRight:M,isLeft:T,isBottom:D,maxScroll:j,minScroll:H}=Mm(x),P=gE(x),X={x:Math.min(k===st.Right?P.right-P.width/2:P.right,Math.max(k===st.Right?P.left:P.left+P.width/2,b.x)),y:Math.min(k===st.Down?P.bottom-P.height/2:P.bottom,Math.max(k===st.Down?P.top:P.top+P.height/2,b.y))},pe=k===st.Right&&!M||k===st.Left&&!T,_e=k===st.Down&&!D||k===st.Up&&!O;if(pe&&X.x!==b.x){const we=x.scrollLeft+v.x,Me=k===st.Right&&we<=j.x||k===st.Left&&we>=H.x;if(Me&&!v.y){x.scrollTo({left:we,behavior:d});return}Me?S.x=x.scrollLeft-we:S.x=k===st.Right?x.scrollLeft-j.x:x.scrollLeft-H.x,S.x&&x.scrollBy({left:-S.x,behavior:d});break}else if(_e&&X.y!==b.y){const we=x.scrollTop+v.y,Me=k===st.Down&&we<=j.y||k===st.Up&&we>=H.y;if(Me&&!v.x){x.scrollTo({top:we,behavior:d});return}Me?S.y=x.scrollTop-we:S.y=k===st.Down?x.scrollTop-j.y:x.scrollTop-H.y,S.y&&x.scrollBy({top:-S.y,behavior:d});break}}this.handleMove(e,cs(yo(b,this.referenceCoordinates),S))}}}handleMove(e,n){const{onMove:r}=this.props;e.preventDefault(),r(n)}handleEnd(e){const{onEnd:n}=this.props;e.preventDefault(),this.detach(),n()}handleCancel(e){const{onCancel:n}=this.props;e.preventDefault(),this.detach(),n()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}Xd.activators=[{eventName:"onKeyDown",handler:(o,e,n)=>{let{keyboardCodes:r=Im,onActivation:i}=e,{active:l}=n;const{code:u}=o.nativeEvent;if(r.start.includes(u)){const d=l.activatorNode.current;return d&&o.target!==d?!1:(o.preventDefault(),i?.({event:o.nativeEvent}),!0)}return!1}}];function Hm(o){return!!(o&&"distance"in o)}function zm(o){return!!(o&&"delay"in o)}class Jd{constructor(e,n,r){var i;r===void 0&&(r=vE(e.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=e,this.events=n;const{event:l}=e,{target:u}=l;this.props=e,this.events=n,this.document=ls(u),this.documentListeners=new vo(this.document),this.listeners=new vo(r),this.windowListeners=new vo(Mn(u)),this.initialCoordinates=(i=Vd(l))!=null?i:ya,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){const{events:e,props:{options:{activationConstraint:n,bypassActivationConstraint:r}}}=this;if(this.listeners.add(e.move.name,this.handleMove,{passive:!1}),this.listeners.add(e.end.name,this.handleEnd),e.cancel&&this.listeners.add(e.cancel.name,this.handleCancel),this.windowListeners.add(ea.Resize,this.handleCancel),this.windowListeners.add(ea.DragStart,Nm),this.windowListeners.add(ea.VisibilityChange,this.handleCancel),this.windowListeners.add(ea.ContextMenu,Nm),this.documentListeners.add(ea.Keydown,this.handleKeydown),n){if(r!=null&&r({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(zm(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(Hm(n)){this.handlePending(n);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(e,n){const{active:r,onPending:i}=this.props;i(r,e,this.initialCoordinates,n)}handleStart(){const{initialCoordinates:e}=this,{onStart:n}=this.props;e&&(this.activated=!0,this.documentListeners.add(ea.Click,SE,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(ea.SelectionChange,this.removeTextSelection),n(e))}handleMove(e){var n;const{activated:r,initialCoordinates:i,props:l}=this,{onMove:u,options:{activationConstraint:d}}=l;if(!i)return;const f=(n=Vd(e))!=null?n:ya,g=yo(i,f);if(!r&&d){if(Hm(d)){if(d.tolerance!=null&&Yd(g,d.tolerance))return this.handleCancel();if(Yd(g,d.distance))return this.handleStart()}if(zm(d)&&Yd(g,d.tolerance))return this.handleCancel();this.handlePending(d,g);return}e.cancelable&&e.preventDefault(),u(f)}handleEnd(){const{onAbort:e,onEnd:n}=this.props;this.detach(),this.activated||e(this.props.active),n()}handleCancel(){const{onAbort:e,onCancel:n}=this.props;this.detach(),this.activated||e(this.props.active),n()}handleKeydown(e){e.code===st.Esc&&this.handleCancel()}removeTextSelection(){var e;(e=this.document.getSelection())==null||e.removeAllRanges()}}const CE={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class Qd extends Jd{constructor(e){const{event:n}=e,r=ls(n.target);super(e,CE,r)}}Qd.activators=[{eventName:"onPointerDown",handler:(o,e)=>{let{nativeEvent:n}=o,{onActivation:r}=e;return!n.isPrimary||n.button!==0?!1:(r?.({event:n}),!0)}}];const EE={move:{name:"mousemove"},end:{name:"mouseup"}};var Zd;(function(o){o[o.RightClick=2]="RightClick"})(Zd||(Zd={}));class _E extends Jd{constructor(e){super(e,EE,ls(e.event.target))}}_E.activators=[{eventName:"onMouseDown",handler:(o,e)=>{let{nativeEvent:n}=o,{onActivation:r}=e;return n.button===Zd.RightClick?!1:(r?.({event:n}),!0)}}];const ef={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class AE extends Jd{constructor(e){super(e,ef)}static setup(){return window.addEventListener(ef.move.name,e,{capture:!1,passive:!1}),function(){window.removeEventListener(ef.move.name,e)};function e(){}}}AE.activators=[{eventName:"onTouchStart",handler:(o,e)=>{let{nativeEvent:n}=o,{onActivation:r}=e;const{touches:i}=n;return i.length>1?!1:(r?.({event:n}),!0)}}];var So;(function(o){o[o.Pointer=0]="Pointer",o[o.DraggableRect=1]="DraggableRect"})(So||(So={}));var ic;(function(o){o[o.TreeOrder=0]="TreeOrder",o[o.ReversedTreeOrder=1]="ReversedTreeOrder"})(ic||(ic={}));function xE(o){let{acceleration:e,activator:n=So.Pointer,canScroll:r,draggingRect:i,enabled:l,interval:u=5,order:d=ic.TreeOrder,pointerCoordinates:f,scrollableAncestors:g,scrollableAncestorRects:m,delta:b,threshold:v}=o;const S=RE({delta:b,disabled:!l}),[_,x]=zC(),k=I.useRef({x:0,y:0}),O=I.useRef({x:0,y:0}),M=I.useMemo(()=>{switch(n){case So.Pointer:return f?{top:f.y,bottom:f.y,left:f.x,right:f.x}:null;case So.DraggableRect:return i}},[n,i,f]),T=I.useRef(null),D=I.useCallback(()=>{const H=T.current;if(!H)return;const P=k.current.x*O.current.x,X=k.current.y*O.current.y;H.scrollBy(P,X)},[]),j=I.useMemo(()=>d===ic.TreeOrder?[...g].reverse():g,[d,g]);I.useEffect(()=>{if(!l||!g.length||!M){x();return}for(const H of j){if(r?.(H)===!1)continue;const P=g.indexOf(H),X=m[P];if(!X)continue;const{direction:pe,speed:_e}=hE(H,X,M,e,v);for(const we of["x","y"])S[we][pe[we]]||(_e[we]=0,pe[we]=0);if(_e.x>0||_e.y>0){x(),T.current=H,_(D,u),k.current=_e,O.current=pe;return}}k.current={x:0,y:0},O.current={x:0,y:0},x()},[e,D,r,x,l,u,JSON.stringify(M),JSON.stringify(S),_,g,j,m,JSON.stringify(v)])}const TE={x:{[fn.Backward]:!1,[fn.Forward]:!1},y:{[fn.Backward]:!1,[fn.Forward]:!1}};function RE(o){let{delta:e,disabled:n}=o;const r=Pd(e);return po(i=>{if(n||!r||!i)return TE;const l={x:Math.sign(e.x-r.x),y:Math.sign(e.y-r.y)};return{x:{[fn.Backward]:i.x[fn.Backward]||l.x===-1,[fn.Forward]:i.x[fn.Forward]||l.x===1},y:{[fn.Backward]:i.y[fn.Backward]||l.y===-1,[fn.Forward]:i.y[fn.Forward]||l.y===1}}},[n,e,r])}function kE(o,e){const n=e!=null?o.get(e):void 0,r=n?n.node.current:null;return po(i=>{var l;return e==null?null:(l=r??i)!=null?l:null},[r,e])}function DE(o,e){return I.useMemo(()=>o.reduce((n,r)=>{const{sensor:i}=r,l=i.activators.map(u=>({eventName:u.eventName,handler:e(u.handler,r)}));return[...n,...l]},[]),[o,e])}var wo;(function(o){o[o.Always=0]="Always",o[o.BeforeDragging=1]="BeforeDragging",o[o.WhileDragging=2]="WhileDragging"})(wo||(wo={}));var tf;(function(o){o.Optimized="optimized"})(tf||(tf={}));const jm=new Map;function OE(o,e){let{dragging:n,dependencies:r,config:i}=e;const[l,u]=I.useState(null),{frequency:d,measure:f,strategy:g}=i,m=I.useRef(o),b=k(),v=go(b),S=I.useCallback(function(O){O===void 0&&(O=[]),!v.current&&u(M=>M===null?O:M.concat(O.filter(T=>!M.includes(T))))},[v]),_=I.useRef(null),x=po(O=>{if(b&&!n)return jm;if(!O||O===jm||m.current!==o||l!=null){const M=new Map;for(let T of o){if(!T)continue;if(l&&l.length>0&&!l.includes(T.id)&&T.rect.current){M.set(T.id,T.rect.current);continue}const D=T.node.current,j=D?new Wd(f(D),D):null;T.rect.current=j,j&&M.set(T.id,j)}return M}return O},[o,l,n,b,f]);return I.useEffect(()=>{m.current=o},[o]),I.useEffect(()=>{b||S()},[n,b]),I.useEffect(()=>{l&&l.length>0&&u(null)},[JSON.stringify(l)]),I.useEffect(()=>{b||typeof d!="number"||_.current!==null||(_.current=setTimeout(()=>{S(),_.current=null},d))},[d,b,S,...r]),{droppableRects:x,measureDroppableContainers:S,measuringScheduled:l!=null};function k(){switch(g){case wo.Always:return!1;case wo.BeforeDragging:return n;default:return!n}}}function Um(o,e){return po(n=>o?n||(typeof e=="function"?e(o):o):null,[e,o])}function LE(o,e){return Um(o,e)}function ME(o){let{callback:e,disabled:n}=o;const r=Bd(e),i=I.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:l}=window;return new l(r)},[r,n]);return I.useEffect(()=>()=>i?.disconnect(),[i]),i}function sc(o){let{callback:e,disabled:n}=o;const r=Bd(e),i=I.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:l}=window;return new l(r)},[n]);return I.useEffect(()=>()=>i?.disconnect(),[i]),i}function $E(o){return new Wd(us(o),o)}function Bm(o,e,n){e===void 0&&(e=$E);const[r,i]=I.useState(null);function l(){i(f=>{if(!o)return null;if(o.isConnected===!1){var g;return(g=f??n)!=null?g:null}const m=e(o);return JSON.stringify(f)===JSON.stringify(m)?f:m})}const u=ME({callback(f){if(o)for(const g of f){const{type:m,target:b}=g;if(m==="childList"&&b instanceof HTMLElement&&b.contains(o)){l();break}}}}),d=sc({callback:l});return za(()=>{l(),o?(d?.observe(o),u?.observe(document.body,{childList:!0,subtree:!0})):(d?.disconnect(),u?.disconnect())},[o]),r}function NE(o){const e=Um(o);return Tm(o,e)}const Pm=[];function IE(o){const e=I.useRef(o),n=po(r=>o?r&&r!==Pm&&o&&e.current&&o.parentNode===e.current.parentNode?r:rc(o):Pm,[o]);return I.useEffect(()=>{e.current=o},[o]),n}function HE(o){const[e,n]=I.useState(null),r=I.useRef(o),i=I.useCallback(l=>{const u=Fd(l.target);u&&n(d=>d?(d.set(u,Kd(u)),new Map(d)):null)},[]);return I.useEffect(()=>{const l=r.current;if(o!==l){u(l);const d=o.map(f=>{const g=Fd(f);return g?(g.addEventListener("scroll",i,{passive:!0}),[g,Kd(g)]):null}).filter(f=>f!=null);n(d.length?new Map(d):null),r.current=o}return()=>{u(o),u(l)};function u(d){d.forEach(f=>{const g=Fd(f);g?.removeEventListener("scroll",i)})}},[i,o]),I.useMemo(()=>o.length?e?Array.from(e.values()).reduce((l,u)=>cs(l,u),ya):$m(o):ya,[o,e])}function qm(o,e){e===void 0&&(e=[]);const n=I.useRef(null);return I.useEffect(()=>{n.current=null},e),I.useEffect(()=>{const r=o!==ya;r&&!n.current&&(n.current=o),!r&&n.current&&(n.current=null)},[o]),n.current?yo(o,n.current):ya}function zE(o){I.useEffect(()=>{if(!tc)return;const e=o.map(n=>{let{sensor:r}=n;return r.setup==null?void 0:r.setup()});return()=>{for(const n of e)n?.()}},o.map(e=>{let{sensor:n}=e;return n}))}function jE(o,e){return I.useMemo(()=>o.reduce((n,r)=>{let{eventName:i,handler:l}=r;return n[i]=u=>{l(u,e)},n},{}),[o,e])}function Gm(o){return I.useMemo(()=>o?cE(o):null,[o])}const Vm=[];function UE(o,e){e===void 0&&(e=us);const[n]=o,r=Gm(n?Mn(n):null),[i,l]=I.useState(Vm);function u(){l(()=>o.length?o.map(f=>Lm(f)?r:new Wd(e(f),f)):Vm)}const d=sc({callback:u});return za(()=>{d?.disconnect(),u(),o.forEach(f=>d?.observe(f))},[o]),i}function BE(o){if(!o)return null;if(o.children.length>1)return o;const e=o.children[0];return ho(e)?e:o}function PE(o){let{measure:e}=o;const[n,r]=I.useState(null),i=I.useCallback(g=>{for(const{target:m}of g)if(ho(m)){r(b=>{const v=e(m);return b?{...b,width:v.width,height:v.height}:v});break}},[e]),l=sc({callback:i}),u=I.useCallback(g=>{const m=BE(g);l?.disconnect(),m&&l?.observe(m),r(m?e(m):null)},[e,l]),[d,f]=nc(u);return I.useMemo(()=>({nodeRef:d,rect:n,setRef:f}),[n,d,f])}const qE=[{sensor:Qd,options:{}},{sensor:Xd,options:{}}],GE={current:{}},oc={draggable:{measure:Rm},droppable:{measure:Rm,strategy:wo.WhileDragging,frequency:tf.Optimized},dragOverlay:{measure:us}};class Co extends Map{get(e){var n;return e!=null&&(n=super.get(e))!=null?n:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(e=>{let{disabled:n}=e;return!n})}getNodeFor(e){var n,r;return(n=(r=this.get(e))==null?void 0:r.node.current)!=null?n:void 0}}const VE={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new Co,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:ac},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:oc,measureDroppableContainers:ac,windowRect:null,measuringScheduled:!1},FE={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:ac,draggableNodes:new Map,over:null,measureDroppableContainers:ac},lc=I.createContext(FE),Fm=I.createContext(VE);function KE(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new Co}}}function WE(o,e){switch(e.type){case rn.DragStart:return{...o,draggable:{...o.draggable,initialCoordinates:e.initialCoordinates,active:e.active}};case rn.DragMove:return o.draggable.active==null?o:{...o,draggable:{...o.draggable,translate:{x:e.coordinates.x-o.draggable.initialCoordinates.x,y:e.coordinates.y-o.draggable.initialCoordinates.y}}};case rn.DragEnd:case rn.DragCancel:return{...o,draggable:{...o.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case rn.RegisterDroppable:{const{element:n}=e,{id:r}=n,i=new Co(o.droppable.containers);return i.set(r,n),{...o,droppable:{...o.droppable,containers:i}}}case rn.SetDroppableDisabled:{const{id:n,key:r,disabled:i}=e,l=o.droppable.containers.get(n);if(!l||r!==l.key)return o;const u=new Co(o.droppable.containers);return u.set(n,{...l,disabled:i}),{...o,droppable:{...o.droppable,containers:u}}}case rn.UnregisterDroppable:{const{id:n,key:r}=e,i=o.droppable.containers.get(n);if(!i||r!==i.key)return o;const l=new Co(o.droppable.containers);return l.delete(n),{...o,droppable:{...o.droppable,containers:l}}}default:return o}}function YE(o){let{disabled:e}=o;const{active:n,activatorEvent:r,draggableNodes:i}=I.useContext(lc),l=Pd(r),u=Pd(n?.id);return I.useEffect(()=>{if(!e&&!r&&l&&u!=null){if(!Gd(l)||document.activeElement===l.target)return;const d=i.get(u);if(!d)return;const{activatorNode:f,node:g}=d;if(!f.current&&!g.current)return;requestAnimationFrame(()=>{for(const m of[f.current,g.current]){if(!m)continue;const b=BC(m);if(b){b.focus();break}}})}},[r,e,i,u,l]),null}function XE(o,e){let{transform:n,...r}=e;return o!=null&&o.length?o.reduce((i,l)=>l({transform:i,...r}),n):n}function JE(o){return I.useMemo(()=>({draggable:{...oc.draggable,...o?.draggable},droppable:{...oc.droppable,...o?.droppable},dragOverlay:{...oc.dragOverlay,...o?.dragOverlay}}),[o?.draggable,o?.droppable,o?.dragOverlay])}function QE(o){let{activeNode:e,measure:n,initialRect:r,config:i=!0}=o;const l=I.useRef(!1),{x:u,y:d}=typeof i=="boolean"?{x:i,y:i}:i;za(()=>{if(!u&&!d||!e){l.current=!1;return}if(l.current||!r)return;const g=e?.node.current;if(!g||g.isConnected===!1)return;const m=n(g),b=Tm(m,r);if(u||(b.x=0),d||(b.y=0),l.current=!0,Math.abs(b.x)>0||Math.abs(b.y)>0){const v=km(g);v&&v.scrollBy({top:b.y,left:b.x})}},[e,u,d,r,n])}const Km=I.createContext({...ya,scaleX:1,scaleY:1});var xr;(function(o){o[o.Uninitialized=0]="Uninitialized",o[o.Initializing=1]="Initializing",o[o.Initialized=2]="Initialized"})(xr||(xr={}));const ZE=I.memo(function(e){var n,r,i,l;let{id:u,accessibility:d,autoScroll:f=!0,children:g,sensors:m=qE,collisionDetection:b=nE,measuring:v,modifiers:S,..._}=e;const x=I.useReducer(WE,void 0,KE),[k,O]=x,[M,T]=KC(),[D,j]=I.useState(xr.Uninitialized),H=D===xr.Initialized,{draggable:{active:P,nodes:X,translate:pe},droppable:{containers:_e}}=k,we=P!=null?X.get(P):null,Me=I.useRef({initial:null,translated:null}),qe=I.useMemo(()=>{var Te;return P!=null?{id:P,data:(Te=we?.data)!=null?Te:GE,rect:Me}:null},[P,we]),Je=I.useRef(null),[gt,Q]=I.useState(null),[fe,ve]=I.useState(null),ae=go(_,Object.values(_)),ge=mo("DndDescribedBy",u),A=I.useMemo(()=>_e.getEnabled(),[_e]),K=JE(v),{droppableRects:ue,measureDroppableContainers:he,measuringScheduled:le}=OE(A,{dragging:H,dependencies:[pe.x,pe.y],config:K.droppable}),de=kE(X,P),Oe=I.useMemo(()=>fe?Vd(fe):null,[fe]),He=me(),Pe=LE(de,K.draggable.measure);QE({activeNode:P!=null?X.get(P):null,config:He.layoutShiftCompensation,initialRect:Pe,measure:K.draggable.measure});const ke=Bm(de,K.draggable.measure,Pe),Ot=Bm(de?de.parentElement:null),ut=I.useRef({activatorEvent:null,active:null,activeNode:de,collisionRect:null,collisions:null,droppableRects:ue,draggableNodes:X,draggingNode:null,draggingNodeRect:null,droppableContainers:_e,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),Ct=_e.getNodeFor((n=ut.current.over)==null?void 0:n.id),vt=PE({measure:K.dragOverlay.measure}),kt=(r=vt.nodeRef.current)!=null?r:de,Ee=H?(i=vt.rect)!=null?i:ke:null,Nt=!!(vt.nodeRef.current&&vt.rect),zt=NE(Nt?null:ke),qt=Gm(kt?Mn(kt):null),Lt=IE(H?Ct??de:null),_n=UE(Lt),hn=XE(S,{transform:{x:pe.x-zt.x,y:pe.y-zt.y,scaleX:1,scaleY:1},activatorEvent:fe,active:qe,activeNodeRect:ke,containerNodeRect:Ot,draggingNodeRect:Ee,over:ut.current.over,overlayNodeRect:vt.rect,scrollableAncestors:Lt,scrollableAncestorRects:_n,windowRect:qt}),Ba=Oe?cs(Oe,pe):null,Jt=HE(Lt),Dr=qm(Jt),tr=qm(Jt,[ke]),An=cs(hn,Dr),sn=Ee?iE(Ee,hn):null,tt=qe&&sn?b({active:qe,collisionRect:sn,droppableRects:ue,droppableContainers:A,pointerCoordinates:Ba}):null,na=Am(tt,"id"),[kn,nr]=I.useState(null),_a=Nt?hn:cs(hn,tr),on=aE(_a,(l=kn?.rect)!=null?l:null,ke),Dn=I.useRef(null),q=I.useCallback((Te,xe)=>{let{sensor:je,options:ze}=xe;if(Je.current==null)return;const $e=X.get(Je.current);if(!$e)return;const De=Te.nativeEvent,Ye=new je({active:Je.current,activeNode:$e,event:De,options:ze,context:ut,onAbort(Ae){if(!X.get(Ae))return;const{onDragAbort:Ue}=ae.current,ot={id:Ae};Ue?.(ot),M({type:"onDragAbort",event:ot})},onPending(Ae,Re,Ue,ot){if(!X.get(Ae))return;const{onDragPending:Qt}=ae.current,Kt={id:Ae,constraint:Re,initialCoordinates:Ue,offset:ot};Qt?.(Kt),M({type:"onDragPending",event:Kt})},onStart(Ae){const Re=Je.current;if(Re==null)return;const Ue=X.get(Re);if(!Ue)return;const{onDragStart:ot}=ae.current,At={activatorEvent:De,active:{id:Re,data:Ue.data,rect:Me}};Ar.unstable_batchedUpdates(()=>{ot?.(At),j(xr.Initializing),O({type:rn.DragStart,initialCoordinates:Ae,active:Re}),M({type:"onDragStart",event:At}),Q(Dn.current),ve(De)})},onMove(Ae){O({type:rn.DragMove,coordinates:Ae})},onEnd:Ke(rn.DragEnd),onCancel:Ke(rn.DragCancel)});Dn.current=Ye;function Ke(Ae){return async function(){const{active:Ue,collisions:ot,over:At,scrollAdjustedTranslate:Qt}=ut.current;let Kt=null;if(Ue&&Qt){const{cancelDrop:Fn}=ae.current;Kt={activatorEvent:De,active:Ue,collisions:ot,delta:Qt,over:At},Ae===rn.DragEnd&&typeof Fn=="function"&&await Promise.resolve(Fn(Kt))&&(Ae=rn.DragCancel)}Je.current=null,Ar.unstable_batchedUpdates(()=>{O({type:Ae}),j(xr.Uninitialized),nr(null),Q(null),ve(null),Dn.current=null;const Fn=Ae===rn.DragEnd?"onDragEnd":"onDragCancel";if(Kt){const Nn=ae.current[Fn];Nn?.(Kt),M({type:Fn,event:Kt})}})}}},[X]),ie=I.useCallback((Te,xe)=>(je,ze)=>{const $e=je.nativeEvent,De=X.get(ze);if(Je.current!==null||!De||$e.dndKit||$e.defaultPrevented)return;const Ye={active:De};Te(je,xe.options,Ye)===!0&&($e.dndKit={capturedBy:xe.sensor},Je.current=ze,q(je,xe))},[X,q]),oe=DE(m,ie);zE(m),za(()=>{ke&&D===xr.Initializing&&j(xr.Initialized)},[ke,D]),I.useEffect(()=>{const{onDragMove:Te}=ae.current,{active:xe,activatorEvent:je,collisions:ze,over:$e}=ut.current;if(!xe||!je)return;const De={active:xe,activatorEvent:je,collisions:ze,delta:{x:An.x,y:An.y},over:$e};Ar.unstable_batchedUpdates(()=>{Te?.(De),M({type:"onDragMove",event:De})})},[An.x,An.y]),I.useEffect(()=>{const{active:Te,activatorEvent:xe,collisions:je,droppableContainers:ze,scrollAdjustedTranslate:$e}=ut.current;if(!Te||Je.current==null||!xe||!$e)return;const{onDragOver:De}=ae.current,Ye=ze.get(na),Ke=Ye&&Ye.rect.current?{id:Ye.id,rect:Ye.rect.current,data:Ye.data,disabled:Ye.disabled}:null,Ae={active:Te,activatorEvent:xe,collisions:je,delta:{x:$e.x,y:$e.y},over:Ke};Ar.unstable_batchedUpdates(()=>{nr(Ke),De?.(Ae),M({type:"onDragOver",event:Ae})})},[na]),za(()=>{ut.current={activatorEvent:fe,active:qe,activeNode:de,collisionRect:sn,collisions:tt,droppableRects:ue,draggableNodes:X,draggingNode:kt,draggingNodeRect:Ee,droppableContainers:_e,over:kn,scrollableAncestors:Lt,scrollAdjustedTranslate:An},Me.current={initial:Ee,translated:sn}},[qe,de,tt,sn,X,kt,Ee,ue,_e,kn,Lt,An]),xE({...He,delta:pe,draggingRect:sn,pointerCoordinates:Ba,scrollableAncestors:Lt,scrollableAncestorRects:_n});const Z=I.useMemo(()=>({active:qe,activeNode:de,activeNodeRect:ke,activatorEvent:fe,collisions:tt,containerNodeRect:Ot,dragOverlay:vt,draggableNodes:X,droppableContainers:_e,droppableRects:ue,over:kn,measureDroppableContainers:he,scrollableAncestors:Lt,scrollableAncestorRects:_n,measuringConfiguration:K,measuringScheduled:le,windowRect:qt}),[qe,de,ke,fe,tt,Ot,vt,X,_e,ue,kn,he,Lt,_n,K,le,qt]),be=I.useMemo(()=>({activatorEvent:fe,activators:oe,active:qe,activeNodeRect:ke,ariaDescribedById:{draggable:ge},dispatch:O,draggableNodes:X,over:kn,measureDroppableContainers:he}),[fe,oe,qe,ke,O,ge,X,kn,he]);return Xe.createElement(Sm.Provider,{value:T},Xe.createElement(lc.Provider,{value:be},Xe.createElement(Fm.Provider,{value:Z},Xe.createElement(Km.Provider,{value:on},g)),Xe.createElement(YE,{disabled:d?.restoreFocus===!1})),Xe.createElement(XC,{...d,hiddenTextDescribedById:ge}));function me(){const Te=gt?.autoScrollEnabled===!1,xe=typeof f=="object"?f.enabled===!1:f===!1,je=H&&!Te&&!xe;return typeof f=="object"?{...f,enabled:je}:{enabled:je}}}),e_=I.createContext(null),Wm="button",t_="Draggable";function n_(o){let{id:e,data:n,disabled:r=!1,attributes:i}=o;const l=mo(t_),{activators:u,activatorEvent:d,active:f,activeNodeRect:g,ariaDescribedById:m,draggableNodes:b,over:v}=I.useContext(lc),{role:S=Wm,roleDescription:_="draggable",tabIndex:x=0}=i??{},k=f?.id===e,O=I.useContext(k?Km:e_),[M,T]=nc(),[D,j]=nc(),H=jE(u,e),P=go(n);za(()=>(b.set(e,{id:e,key:l,node:M,activatorNode:D,data:P}),()=>{const pe=b.get(e);pe&&pe.key===l&&b.delete(e)}),[b,e]);const X=I.useMemo(()=>({role:S,tabIndex:x,"aria-disabled":r,"aria-pressed":k&&S===Wm?!0:void 0,"aria-roledescription":_,"aria-describedby":m.draggable}),[r,S,x,k,_,m.draggable]);return{active:f,activatorEvent:d,activeNodeRect:g,attributes:X,isDragging:k,listeners:r?void 0:H,node:M,over:v,setNodeRef:T,setActivatorNodeRef:j,transform:O}}function a_(){return I.useContext(Fm)}const r_="Droppable",i_={timeout:25};function s_(o){let{data:e,disabled:n=!1,id:r,resizeObserverConfig:i}=o;const l=mo(r_),{active:u,dispatch:d,over:f,measureDroppableContainers:g}=I.useContext(lc),m=I.useRef({disabled:n}),b=I.useRef(!1),v=I.useRef(null),S=I.useRef(null),{disabled:_,updateMeasurementsFor:x,timeout:k}={...i_,...i},O=go(x??r),M=I.useCallback(()=>{if(!b.current){b.current=!0;return}S.current!=null&&clearTimeout(S.current),S.current=setTimeout(()=>{g(Array.isArray(O.current)?O.current:[O.current]),S.current=null},k)},[k]),T=sc({callback:M,disabled:_||!u}),D=I.useCallback((X,pe)=>{T&&(pe&&(T.unobserve(pe),b.current=!1),X&&T.observe(X))},[T]),[j,H]=nc(D),P=go(e);return I.useEffect(()=>{!T||!j.current||(T.disconnect(),b.current=!1,T.observe(j.current))},[j,T]),I.useEffect(()=>(d({type:rn.RegisterDroppable,element:{id:r,key:l,disabled:n,node:j,rect:v,data:P}}),()=>d({type:rn.UnregisterDroppable,key:l,id:r})),[r]),I.useEffect(()=>{n!==m.current.disabled&&(d({type:rn.SetDroppableDisabled,id:r,key:l,disabled:n}),m.current.disabled=n)},[r,l,n,d]),{active:u,rect:v,isOver:f?.id===r,node:j,over:f,setNodeRef:H}}function nf(o,e,n){const r=o.slice();return r.splice(n<0?r.length+n:n,0,r.splice(e,1)[0]),r}function o_(o,e){return o.reduce((n,r,i)=>{const l=e.get(r);return l&&(n[i]=l),n},Array(o.length))}function cc(o){return o!==null&&o>=0}function l_(o,e){if(o===e)return!0;if(o.length!==e.length)return!1;for(let n=0;n{var e;let{rects:n,activeNodeRect:r,activeIndex:i,overIndex:l,index:u}=o;const d=(e=n[i])!=null?e:r;if(!d)return null;const f=d_(n,u,i);if(u===i){const g=n[l];return g?{x:ii&&u<=l?{x:-d.width-f,y:0,...uc}:u=l?{x:d.width+f,y:0,...uc}:{x:0,y:0,...uc}};function d_(o,e,n){const r=o[e],i=o[e-1],l=o[e+1];return!r||!i&&!l?0:n{let{rects:e,activeIndex:n,overIndex:r,index:i}=o;const l=nf(e,r,n),u=e[i],d=l[i];return!d||!u?null:{x:d.left-u.left,y:d.top-u.top,scaleX:d.width/u.width,scaleY:d.height/u.height}},dc={scaleX:1,scaleY:1},f_=o=>{var e;let{activeIndex:n,activeNodeRect:r,index:i,rects:l,overIndex:u}=o;const d=(e=l[n])!=null?e:r;if(!d)return null;if(i===n){const g=l[u];return g?{x:0,y:nn&&i<=u?{x:0,y:-d.height-f,...dc}:i=u?{x:0,y:d.height+f,...dc}:{x:0,y:0,...dc}};function h_(o,e,n){const r=o[e],i=o[e-1],l=o[e+1];return r?nr.map(H=>typeof H=="object"&&"id"in H?H.id:H),[r]),_=u!=null,x=u?S.indexOf(u.id):-1,k=g?S.indexOf(g.id):-1,O=I.useRef(S),M=!l_(S,O.current),T=k!==-1&&x===-1||M,D=c_(l);za(()=>{M&&_&&m(S)},[M,S,_,m]),I.useEffect(()=>{O.current=S},[S]);const j=I.useMemo(()=>({activeIndex:x,containerId:b,disabled:D,disableTransforms:T,items:S,overIndex:k,useDragOverlay:v,sortedRects:o_(S,f),strategy:i}),[x,b,D.draggable,D.droppable,T,S,k,f,v,i]);return Xe.createElement(Xm.Provider,{value:j},e)}const p_=o=>{let{id:e,items:n,activeIndex:r,overIndex:i}=o;return nf(n,r,i).indexOf(e)},m_=o=>{let{containerId:e,isSorting:n,wasDragging:r,index:i,items:l,newIndex:u,previousItems:d,previousContainerId:f,transition:g}=o;return!g||!r||d!==l&&i===u?!1:n?!0:u!==i&&e===f},y_={duration:200,easing:"ease"},Jm="transform",b_=bo.Transition.toString({property:Jm,duration:0,easing:"linear"}),v_={roleDescription:"sortable"};function S_(o){let{disabled:e,index:n,node:r,rect:i}=o;const[l,u]=I.useState(null),d=I.useRef(n);return za(()=>{if(!e&&n!==d.current&&r.current){const f=i.current;if(f){const g=us(r.current,{ignoreTransform:!0}),m={x:f.left-g.left,y:f.top-g.top,scaleX:f.width/g.width,scaleY:f.height/g.height};(m.x||m.y)&&u(m)}}n!==d.current&&(d.current=n)},[e,n,r,i]),I.useEffect(()=>{l&&u(null)},[l]),l}function w_(o){let{animateLayoutChanges:e=m_,attributes:n,disabled:r,data:i,getNewIndex:l=p_,id:u,strategy:d,resizeObserverConfig:f,transition:g=y_}=o;const{items:m,containerId:b,activeIndex:v,disabled:S,disableTransforms:_,sortedRects:x,overIndex:k,useDragOverlay:O,strategy:M}=I.useContext(Xm),T=C_(r,S),D=m.indexOf(u),j=I.useMemo(()=>({sortable:{containerId:b,index:D,items:m},...i}),[b,i,D,m]),H=I.useMemo(()=>m.slice(m.indexOf(u)),[m,u]),{rect:P,node:X,isOver:pe,setNodeRef:_e}=s_({id:u,data:j,disabled:T.droppable,resizeObserverConfig:{updateMeasurementsFor:H,...f}}),{active:we,activatorEvent:Me,activeNodeRect:qe,attributes:Je,setNodeRef:gt,listeners:Q,isDragging:fe,over:ve,setActivatorNodeRef:ae,transform:ge}=n_({id:u,data:j,attributes:{...v_,...n},disabled:T.draggable}),A=HC(_e,gt),K=!!we,ue=K&&!_&&cc(v)&&cc(k),he=!O&&fe,le=he&&ue?ge:null,Oe=ue?le??(d??M)({rects:x,activeNodeRect:qe,activeIndex:v,overIndex:k,index:D}):null,He=cc(v)&&cc(k)?l({id:u,items:m,activeIndex:v,overIndex:k}):D,Pe=we?.id,ke=I.useRef({activeId:Pe,items:m,newIndex:He,containerId:b}),Ot=m!==ke.current.items,ut=e({active:we,containerId:b,isDragging:fe,isSorting:K,id:u,index:D,items:m,newIndex:ke.current.newIndex,previousItems:ke.current.items,previousContainerId:ke.current.containerId,transition:g,wasDragging:ke.current.activeId!=null}),Ct=S_({disabled:!ut,index:D,node:X,rect:P});return I.useEffect(()=>{K&&ke.current.newIndex!==He&&(ke.current.newIndex=He),b!==ke.current.containerId&&(ke.current.containerId=b),m!==ke.current.items&&(ke.current.items=m)},[K,He,b,m]),I.useEffect(()=>{if(Pe===ke.current.activeId)return;if(Pe!=null&&ke.current.activeId==null){ke.current.activeId=Pe;return}const kt=setTimeout(()=>{ke.current.activeId=Pe},50);return()=>clearTimeout(kt)},[Pe]),{active:we,activeIndex:v,attributes:Je,data:j,rect:P,index:D,newIndex:He,items:m,isOver:pe,isSorting:K,isDragging:fe,listeners:Q,node:X,overIndex:k,over:ve,setNodeRef:A,setActivatorNodeRef:ae,setDroppableNodeRef:_e,setDraggableNodeRef:gt,transform:Ct??Oe,transition:vt()};function vt(){if(Ct||Ot&&ke.current.newIndex===D)return b_;if(!(he&&!Gd(Me)||!g)&&(K||ut))return bo.Transition.toString({...g,property:Jm})}}function C_(o,e){var n,r;return typeof o=="boolean"?{draggable:o,droppable:!1}:{draggable:(n=o?.draggable)!=null?n:e.draggable,droppable:(r=o?.droppable)!=null?r:e.droppable}}function fc(o){if(!o)return!1;const e=o.data.current;return!!(e&&"sortable"in e&&typeof e.sortable=="object"&&"containerId"in e.sortable&&"items"in e.sortable&&"index"in e.sortable)}const E_=[st.Down,st.Right,st.Up,st.Left],__=(o,e)=>{let{context:{active:n,collisionRect:r,droppableRects:i,droppableContainers:l,over:u,scrollableAncestors:d}}=e;if(E_.includes(o.code)){if(o.preventDefault(),!n||!r)return;const f=[];l.getEnabled().forEach(b=>{if(!b||b!=null&&b.disabled)return;const v=i.get(b.id);if(v)switch(o.code){case st.Down:r.topv.top&&f.push(b);break;case st.Left:r.left>v.left&&f.push(b);break;case st.Right:r.left1&&(m=g[1].id),m!=null){const b=l.get(n.id),v=l.get(m),S=v?i.get(v.id):null,_=v?.node.current;if(_&&S&&b&&v){const k=rc(_).some((H,P)=>d[P]!==H),O=Qm(b,v),M=A_(b,v),T=k||!O?{x:0,y:0}:{x:M?r.width-S.width:0,y:M?r.height-S.height:0},D={x:S.left,y:S.top};return T.x&&T.y?D:yo(D,T)}}}};function Qm(o,e){return!fc(o)||!fc(e)?!1:o.data.current.sortable.containerId===e.data.current.sortable.containerId}function A_(o,e){return!fc(o)||!fc(e)||!Qm(o,e)?!1:o.data.current.sortable.index{const d=I.useId(),f=I.useRef({inProgress:!1,lastSortTime:0,lastActiveId:null}),g=JC(wm(Qd,{activationConstraint:{distance:5}}),wm(Xd,{coordinateGetter:__})),m=I.useCallback(S=>{f.current={inProgress:!0,lastSortTime:Date.now(),lastActiveId:S.active.id},l?.({activeId:S.active.id})},[l]),b=I.useCallback(S=>{const{active:_,over:x}=S,k=Date.now();if(!x||_.id===x.id){f.current.inProgress=!1;return}const{lastSortTime:O,lastActiveId:M,inProgress:T}=f.current;if(M===_.id&&k-O<500&&!T)return;f.current={inProgress:!1,lastSortTime:k,lastActiveId:_.id};const D=o.findIndex(H=>String(H[e])===String(_.id)),j=o.findIndex(H=>String(H[e])===String(x.id));if(D!==-1&&j!==-1&&D!==j){const H=nf(o,D,j);i?.(H,{oldIndex:D,newIndex:j})}},[o,e,i]),v=o.map(S=>String(S[e]));return ft.jsx(ZE,{id:d,sensors:g,collisionDetection:ZC,onDragStart:m,onDragEnd:b,children:ft.jsx(g_,{items:v,strategy:x_[n],children:r})},u!==void 0?`${d}-v${u}`:d)},Zm=I.createContext(null),R_=({value:o,children:e})=>ft.jsx(Zm.Provider,{value:o,children:e}),k_=()=>I.useContext(Zm),D_=({id:o,handle:e,as:n="div",children:r})=>{const{attributes:i,listeners:l,setNodeRef:u,transform:d,transition:f,isDragging:g}=w_({id:o}),m={transform:bo.Transform.toString(d),transition:f,opacity:g?.5:1,position:"relative"};return ft.jsx(n,{ref:u,style:m,...i,...e?{}:l,"data-sortable-item":!0,"data-sortable-id":String(o),"data-dragging":g,children:ft.jsx(R_,{value:{listeners:l,handle:e,isDragging:g},children:r})})},ht=dt("DynamicRenderer");function Za(){try{return window.G7Core?.devTools}catch{return}}function rf(o,e,n,r){if(typeof o=="string"){if(/\$t:[a-zA-Z_][a-zA-Z0-9_.\-]*/.test(o))try{return e.resolveTranslations(o,n,r)}catch{return o}return o}if(Array.isArray(o))return o.map(i=>rf(i,e,n,r));if(o&&typeof o=="object"){const i={};for(const[l,u]of Object.entries(o))i[l]=rf(u,e,n,r);return i}return o}function O_(o){const e=Object.keys(o);return e.length>0&&e.every(n=>/^\d+$/.test(n))}const ba=(o,e)=>{const n=["errors"],r={...o};for(const i of Object.keys(e)){const l=e[i],u=o[i];if(l===null){r[i]=null;continue}if(n.includes(i)){r[i]=l;continue}if(Array.isArray(l)){r[i]=l;continue}if(Array.isArray(u)&&l!==null&&typeof l=="object"&&!Array.isArray(l)&&O_(l)){const d=Object.keys(l).map(g=>parseInt(g,10));if((d.length>0?Math.max(...d):0)>=u.length+d.length+10)r[i]={...l};else{const g=[...u];for(const[m,b]of Object.entries(l)){const v=parseInt(m,10);v>=0&&v=g.length&&(g[v]=b)}r[i]=g}}else l!==null&&typeof l=="object"&&u!==null&&typeof u=="object"&&!Array.isArray(u)?r[i]=ba(u,l):r[i]=l}return r},ey=(o,e)=>{const n={...o};for(const r of Object.keys(e)){if(!(r in n))continue;const i=e[r],l=n[r];if(i!==null&&typeof i=="object"&&!Array.isArray(i)&&l!==null&&typeof l=="object"&&!Array.isArray(l)){const u=ey(l,i);Object.keys(u).length===0?delete n[r]:n[r]=u}else delete n[r]}return n},L_=o=>{const e={},n=o.split(";").filter(r=>r.trim());for(const r of n){const i=r.indexOf(":");if(i===-1)continue;const l=r.substring(0,i).trim(),u=r.substring(i+1).trim();if(l&&u){const d=l.replace(/-([a-z])/g,(f,g)=>g.toUpperCase());e[d]=u}}return e};class M_ extends I.Component{constructor(e){super(e),this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,n){ht.error(`컴포넌트 렌더링 에러 (ID: ${this.props.componentId}, Name: ${this.props.componentName}):`,e,n)}render(){return this.state.hasError?this.props.fallback?this.props.fallback:ft.jsxs("div",{className:"p-4 my-2 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg text-red-800 dark:text-red-400",children:[ft.jsx("div",{className:"font-semibold mb-1",children:"컴포넌트 로드 실패"}),ft.jsxs("div",{className:"text-xs opacity-80",children:[this.props.componentName&&`[${this.props.componentName}] `,"데이터를 표시할 수 없습니다."]}),this.state.error&&ft.jsxs("details",{className:"mt-2",children:[ft.jsx("summary",{className:"cursor-pointer text-xs opacity-70 hover:opacity-100",children:"상세 정보"}),ft.jsx("div",{className:"mt-1 p-2 bg-red-100 dark:bg-red-900/30 rounded text-xs font-mono whitespace-pre-wrap break-all",children:this.state.error.message})]})]}):this.props.children}}const ja=I.memo(({componentDef:o,dataContext:e,translationContext:n,registry:r,bindingEngine:i,translationEngine:l,actionDispatcher:u,parentComponentContext:d,parentFormContextProp:f,parentDataContext:g,isRootRenderer:m=!1,isInsideIteration:b=!1,isEditMode:v=!1,onComponentSelect:S,onComponentHover:_,onDragStart:x,onDragEnd:k,componentPath:O,layoutKey:M})=>{const[T,D]=I.useState({loadingActions:{}});I.useLayoutEffect(()=>{d||(i.startRenderCycle(),window.__g7SetLocalOverrideKeys||(window.__g7ForcedLocalFields=void 0),window.__g7PendingLocalState=null)});const j=I.useRef(null);I.useLayoutEffect(()=>{if(!d&&e._localInit&&typeof e._localInit=="object"){const{_forceLocalInit:q,_merge:ie,...oe}=e._localInit,Z=`${JSON.stringify(oe)}:${q||"no-force"}`;if(j.current!==Z){j.current=Z;const be=ie||"shallow",Te=window.G7Core?.state?.get?.()?._local||{},xe=window.__g7PendingLocalState||{},je={...Te,...xe};be==="replace"?window.__g7PendingLocalState={loadingActions:je.loadingActions||{},...oe,hasChanges:!1}:be==="deep"?window.__g7PendingLocalState=ba(je,{...oe,hasChanges:!1}):window.__g7PendingLocalState={...je,...oe,hasChanges:!1};const ze=window.__g7SetLocalOverrideKeys;ze&&typeof ze=="object"&&(be==="replace"?window.__g7SetLocalOverrideKeys={...oe,hasChanges:!1}:window.__g7SetLocalOverrideKeys=ba(ze,{...oe,hasChanges:!1}))}}}),I.useLayoutEffect(()=>{if(!d){const q=window.__g7SetLocalOverrideKeys;if(q){D(be=>ey(be,q));const ie=q,oe=window.__g7ForcedLocalFields,Z=window.__g7LastSetLocalSnapshot;queueMicrotask(()=>{window.__g7SetLocalOverrideKeys===ie&&(window.__g7SetLocalOverrideKeys=void 0),window.__g7ForcedLocalFields===oe&&(window.__g7ForcedLocalFields=void 0),window.__g7LastSetLocalSnapshot===Z&&(window.__g7LastSetLocalSnapshot=void 0)})}}},[e._local]);const H=I.useRef(M);I.useEffect(()=>{o._fromBase&&M&&H.current!==M&&(H.current=M,D({loadingActions:{}}))},[M,o._fromBase]);const P=I.useRef(""),X=I.useRef(!1),pe=I.useRef(null),_e=I.useRef({}),we=I.useRef({}),Me=I.useRef(g),qe=IC(),Je=gC(),gt=Je?.getParentDataContext()??g;I.useEffect(()=>{if(e._localInit&&typeof e._localInit=="object"){const{_forceLocalInit:q,...ie}=e._localInit,oe=JSON.stringify(ie),Z=q!==void 0,be=Id(),me=`${oe}:${q||"no-force"}`;if(be.hash!==me){be.hash=me,be.timestamp=q,P.current=oe,Z&&(X.current=!0);const{_merge:je,...ze}=ie,$e=je||"shallow";if(D(De=>$e==="replace"?{loadingActions:De.loadingActions||{},...ze,hasChanges:!1}:$e==="deep"?ba(De,{...ze,hasChanges:!1}):{...De,...ze,hasChanges:!1}),e._globalSetState){const De=e._global?._local||{};let Ye;$e==="replace"?Ye={...ze,hasChanges:!1}:$e==="deep"?Ye=ba(De,{...ze,hasChanges:!1}):Ye={...De,...ze,hasChanges:!1},e._globalSetState({_local:Ye})}i.invalidateCacheByKeys(["_local"]),ht.log("_localInit applied (data changed):",Object.keys(ie))}pe.current=e._localInit,vC(e._localInit)}},[e._localInit,g,i]);const{isTransitioning:Q}=dm(),fe=TC(),ve=f??fe,{width:ae}=zd(),ge=k_(),A=I.useMemo(()=>{let q=o;if(o.type==="iterator"&&o.data){const{data:Z,itemName:be,indexName:me,...Te}=o;q={...Te,iteration:{source:Z,item_var:be||"item",index_var:me}}}if(!q.responsive)return q;const ie=ui.getMatchingKey(q.responsive,ae);if(!ie)return q;const oe=q.responsive[ie];return{...q,props:{...q.props,...oe.props},children:oe.children??q.children,text:oe.text??q.text,if:oe.if??q.if,iteration:oe.iteration??q.iteration,__responsiveChildrenKey:oe.children!==void 0?ie:void 0}},[o,ae]),K=I.useCallback(q=>{const ie=q?.__setStateId;if(D(oe=>{const Z=window.__g7PendingLocalState,me=window.__g7SetLocalOverrideKeys||Z,Te=me?ba(oe,me):oe;if(typeof q=="function"){const De=q(Te);return ba(Te,De)}const{__mergeMode:xe,__setStateId:je,...ze}=q;let $e;if(xe==="replace"?$e=ze:xe==="shallow"?$e={...Te,...ze}:$e=ba(Te,ze),xe!==void 0){const De=window.__g7ForcedLocalFields;De&&(window.__g7ForcedLocalFields={...De,...ze})}return $e}),ie){const oe=Za();if(oe?.isEnabled()){const Z=A.id||"unknown",be=A.name||"Unknown";setTimeout(()=>{oe.trackComponentRender?.(Z,be,0,["_local"],[]),oe.completeStateChange?.(ie)},0)}}},[A.id,A.name]),ue=d?.state??T,he=d?.setState??K,le=I.useMemo(()=>{const q=e._localInit&&e._localInit!==pe.current;let ie;q&&e._local?ie=e._local:ie=e._local?ba(e._local,ue):ue;const oe=window.__g7ForcedLocalFields;oe&&(ie=ba(ie,oe));const Z={...e,_local:ie},be=e._computedDefinitions;if(be&&Object.keys(be).length>0){const me=new Rn,Te={...Z,...qe?{_isolated:qe.state}:{}},xe={},je=Za(),ze=je?.isEnabled()??!1;for(const[$e,De]of Object.entries(be)){const Ye=ze?Date.now():0,Ke=ze?e._computed?.[$e]:void 0;let Ae;try{if(typeof De=="string")if(De.startsWith("{{")&&De.endsWith("}}")){const Re=De.slice(2,-2).trim(),Ue=me.evaluateExpression(Re,Te,{skipCache:!0});xe[$e]=Ue}else xe[$e]=De;else if(De&&typeof De=="object"&&"$switch"in De){const Re=me.resolveSwitch(De,Te,{skipCache:!0});xe[$e]=Re}}catch(Re){ht.warn(`Failed to recalculate computed value: ${$e}`,Re),xe[$e]=e._computed?.[$e],Ae=Re instanceof Error?Re.message:String(Re)}if(ze&&(Ae||Ke!==xe[$e])){const Ue=Date.now()-Ye;je.trackComputedProperty?.($e,typeof De=="string"?De:JSON.stringify(De),[{type:"_local",path:"_local",value:Z._local}],xe[$e],Ue,A.id,Ae),Ke!==xe[$e]&&je.trackComputedRecalc?.($e,"dependency-change",Ke,xe[$e],Ue,{type:"_local",path:"_local"},A.id)}}Z._computed=xe}if(qe&&(Z._isolated=qe.state),gt&&(Z.$parent=gt),o.extensionPointProps){const me=i.resolveObject(o.extensionPointProps,Z,b?{skipCache:!0}:void 0);Z.extensionPointProps=v&&l?rf(me,l,n,Z):me}return o.extensionPointCallbacks&&(Z.extensionPointCallbacks=o.extensionPointCallbacks),v&&(Z.$templateId===void 0&&n?.templateId&&(Z.$templateId=n.templateId),Z.$locale===void 0&&n?.locale&&(Z.$locale=n.locale)),Z},[e,ue,qe?.state,gt,Je?.version,o.extensionPointProps,o.extensionPointCallbacks]);_e.current=le._local,we.current=le._computed||{},Me.current=gt,I.useEffect(()=>{const q=Za();if(!q?.isEnabled())return;const ie=le._local;ie&&q.updateLocalState(ie);const oe=le._computed;oe&&q.updateComputedState(oe),gt&&q.updateParentContext?.(gt);const Z=A.id||`comp-${Date.now()}`,be=A.name||"Unknown",me={global:Object.keys(e._global||{}),local:Object.keys(ie||{}),context:d?Object.keys(d.state||{}):[]},Te={type:d?"componentContext":"dynamicState",hasComponentContext:!!d,parentId:d?"parent":void 0};q.trackComponentStateSource?.(Z,be,me,Te),ue&&Object.keys(ue).length>0&&q.trackDynamicState?.(Z,ue);const xe=!!(A.expandChildren||A.props?.expandChildren);q.trackContextFlow?.(Z,be,!!d,xe,!0)},[le._local,e,A.id,A.name,d,ue,A.expandChildren,A.props?.expandChildren,gt]);const de=I.useMemo(()=>({state:{...le._local},setState:he,stateRef:_e,computedRef:we,isolatedContext:qe,parentDataContext:le}),[le._local,he,T,qe,le]),Oe=I.useMemo(()=>{const q=Qi({if:A.if,condition:A.condition,conditions:A.conditions},le,i,A.id);if(A.if||A.condition!==void 0||A.conditions){const oe=Za();oe?.isEnabled()&&A.if&&oe.trackIfCondition(A.id||`if-${Date.now()}`,A.if,q)}return q},[A.if,A.conditions,le,i,A.id]),He=I.useMemo(()=>{if(!A.slot)return null;const q=A.slot;if(q.startsWith("{{")&&q.endsWith("}}")){const ie=q.slice(2,-2).trim();try{const oe={componentId:A.id,componentName:A.name,propName:"slot"},Z=i.evaluateExpression(ie,le,oe);return ht.log(`[Slot] 표현식 평가: "${ie}" => "${Z}" (컴포넌트: ${A.id})`),typeof Z=="string"?Z:null}catch(oe){return ht.warn(`slot 표현식 평가 실패 (컴포넌트: ${A.id}):`,oe),null}}return ht.log(`[Slot] 정적 슬롯 ID: "${q}" (컴포넌트: ${A.id})`),q},[A.slot,A.id,le,i]),Pe=I.useMemo(()=>!He||!A.id?"":`${A.id}-${He}-${JSON.stringify(A.slotOrder??0)}`,[He,A.id,A.slotOrder]),ke=I.useRef(null);I.useEffect(()=>{const q=window.__slotContextValue,ie=q?.isEnabled??!1;if(A.slot&&ht.log(`[Slot Registration] 컴포넌트: ${A.id}, isSlotEnabled: ${ie}, shouldRender: ${Oe}, resolvedSlotId: ${He}`),!ie||!Oe){A.slot&&ht.log(`[Slot Registration] 등록 스킵 - isSlotEnabled: ${ie}, shouldRender: ${Oe}`),ke.current&&A.id&&q&&(q.unregisterFromSlot(ke.current,A.id),ke.current=null);return}if(!He||!A.id){A.slot&&ht.log(`[Slot Registration] 등록 스킵 - resolvedSlotId: ${He}, id: ${A.id}`),ke.current&&A.id&&q&&(q.unregisterFromSlot(ke.current,A.id),ke.current=null);return}ke.current&&ke.current!==He&&q.unregisterFromSlot(ke.current,A.id);const oe={...A,slot:void 0,slotOrder:void 0};return q.registerToSlot(He,A.id,{componentDef:oe,dataContext:e,order:A.slotOrder??0,parentFormContext:f??null,getParentComponentContext:()=>de,translationContext:n,registrationKey:Pe}),ke.current=He,()=>{const Z=window.__slotContextValue;He&&A.id&&Z&&Z.unregisterFromSlot(He,A.id)}},[Oe,He,A,e,f,de,n,Pe]);const Ot=I.useCallback(q=>{if(typeof q=="string"){if(op(q))return cp(q);if(lp(q)){const ie=[],oe=q.replace(new RegExp(`${Ll}([^${Zs}]*)${Zs}`,"g"),(be,me)=>(ie.push(me),`${_r}${ie.length-1}${_r}`));let Z=oe;return/\$t:[a-zA-Z0-9._-]+/.test(oe)&&(Z=l.resolveTranslations(oe,n,le)),Z.replace(new RegExp(`${_r}(\\d+)${_r}`,"g"),(be,me)=>ie[parseInt(me)])}if(q.startsWith("$t:defer:"))return q;if(/\$t:[a-zA-Z0-9._-]+/.test(q)){const ie=q.trim();return ie.startsWith("{")&&ie.endsWith("}")||ie.startsWith("[")&&ie.endsWith("]")?q:l.resolveTranslations(q,n,le)}return q}if(Array.isArray(q))return q.map(ie=>Ot(ie));if(q&&typeof q=="object"){const ie={};for(const[oe,Z]of Object.entries(q))ie[oe]=Ot(Z);return ie}return q},[l,n,le]),ut=I.useCallback(q=>/[?:|&!+\-*/<>=()]/.test(q),[]),Ct=I.useCallback(q=>{if(!q.startsWith("{{")||!q.endsWith("}}"))return null;const ie=q.slice(2,-2);let oe=null,Z=0;for(let be=0;be0?ie[be-1]:"")!=="\\"&&((me==='"'||me==="'")&&!oe?oe=me:me===oe&&(oe=null),!oe&&(me==="{"&&Z++,me==="}"&&Z--,Z<0)))return null}return Z===0?ie.trim():null},[]),vt=I.useMemo(()=>{let q={...A.props||{}};const ie=["cellChildren","expandChildren","expandContext","render"],Z=r.getMetadata(A.name)?.skipBindingKeys||[],be=[...new Set([...ie,...Z])],me=b?{skipCache:!0}:void 0,Te=Ae=>{if(me)return me;if(Ae.startsWith("_computed")||Ae.startsWith("$computed"))return{skipCache:!0}};for(const[Ae,Re]of Object.entries(q))if(!be.includes(Ae))if(typeof Re=="string"){const Ue=Ct(Re);if(Ue!==null){let ot=!1,At=Ue;Ue.startsWith(Na)&&(ot=!0,At=Ue.slice(Na.length));const Qt={componentId:A.id,componentName:A.name,propName:Ae};let Kt;if(ci(At))Kt=i.resolveBindings(`{{${At}}}`,le,me,Qt);else if(ut(At))try{Kt=i.evaluateExpression(At,le,Qt)}catch(Fn){ht.warn(`표현식 평가 실패 (컴포넌트: ${A.id}, prop: ${Ae}):`,Fn),Kt=void 0}else Kt=i.resolve(At,le,Te(At),Qt);q[Ae]=ot&&Kt!=null?Ji(Kt):Kt}else{const ot={componentId:A.id,componentName:A.name,propName:Ae};q[Ae]=i.resolveBindings(Re,le,me,ot)}}else Array.isArray(Re)?q[Ae]=Re.map(Ue=>typeof Ue=="string"?i.resolveBindings(Ue,le,me):typeof Ue=="object"&&Ue!==null?i.resolveObject(Ue,le,me):Ue):Re&&typeof Re=="object"&&(q[Ae]=i.resolveObject(Re,le,me));for(const[Ae,Re]of Object.entries(q))q[Ae]=Ot(Re);if(typeof q.style=="string"&&(q.style=L_(q.style)),q=fd(q,v?void 0:A.actions,le,{componentContext:de,actionDispatcher:u}),A.classMap){const Ae=gw(A.classMap,le,i,{skipCache:!0});if(Ae){const Re=q.className||"";q.className=Re?`${Re} ${Ae}`:Ae}}A.style&&(q.style=A.style),A.actions&&A.actions.length>0&&A.type==="composite"&&Object.assign(q,ue),A.component_layout&&(q.__componentLayoutDefs=A.component_layout);const xe=A.expandChildren||A.props?.expandChildren,je=A.props?.cellChildren,ze=A.children&&A.children.length>0,$e=A.component_layout,De=A.slot,Ye=A.props?.modalId,Ke=A.type==="composite";return(xe||je||ze||$e||De||Ye||Ke)&&(q.__componentContext=de),q},[A.props,A.actions,A.style,A.classMap,A.id,le,n,i,l,de,ue,Ot,ut,Ct,b]),kt=I.useRef(null),Ee=I.useMemo(()=>kt.current&&hm(kt.current,vt)?kt.current:(kt.current=vt,vt),[vt]),Nt=I.useMemo(()=>{const q=A.id;if(typeof q!="string"||!q.includes("{{"))return q;const ie=i.resolveBindings(q,le,{skipCache:!0});return typeof ie=="string"?ie:q},[A.id,le,i]),zt=I.useMemo(()=>{const q=A.dataKey,ie=A.trackChanges,oe=A.debounce;if(q){const Z=q.startsWith("_global."),be=Z?q.slice(8):q,me=Z?e._global:le._local;return{dataKey:be,trackChanges:ie??!1,debounce:oe,setState:Z?xe=>{e._globalSetState?e._globalSetState(xe):ht.warn("_global.formData 사용 시 _globalSetState가 필요합니다.")}:he,state:me??{},_isGlobal:Z}}if(ve.dataKey)return ve},[A.dataKey,A.trackChanges,A.debounce,A.id,he,le._local,e._global,e._globalSetState,ve]),qt=I.useRef(new Set);I.useEffect(()=>{qt.current.clear()},[e._global?._remountKeys]);const Lt=I.useCallback((q,ie)=>{const oe=e._global?._remountKeys;return q&&oe?.[q]&&!qt.current.has(q)?(qt.current.add(q),`${q}-remount-${oe[q]}`):q||ie},[e._global?._remountKeys]),_n=I.useMemo(()=>{if(A.text!==void 0){if(typeof A.text=="string"){const q=A.text;let ie=q;const oe={componentId:A.id,componentName:A.name,propName:"text",skipCache:!0},Z=Ct(q);if(Z!==null){let be=!1,me=Z;if(Z.startsWith(Na)&&(be=!0,me=Z.slice(Na.length)),ci(me))ie=i.resolveBindings(`{{${me}}}`,le,{skipCache:!0},oe);else if(ut(me))try{ie=i.evaluateExpression(me,le,oe)}catch(Te){ht.warn(`text 표현식 평가 실패 (컴포넌트: ${A.id}):`,Te),ie=""}else ie=i.resolve(me,le,{skipCache:!0},oe);be&&ie!=null&&(ie=Ji(ie))}else q.includes("{{")&&(ie=i.resolveBindings(q,le,{skipCache:!0},oe));return ie=Ot(ie),ie??""}return A.text}return!A.children||A.children.length===0?null:A.children.map((q,ie)=>{if(typeof q=="string")return q;const oe=A.__responsiveChildrenKey,Z=oe?`responsive.${oe}.children`:"children",be=O?`${O}.${Z}.${ie}`:`${ie}`,me=q._fromBase?q.id||`child-${ie}`:Lt(q.id,`child-${ie}`),Te=!q._fromBase&&M?`${me}_${M}`:me;return ft.jsx(ja,{componentDef:q,dataContext:le,translationContext:n,registry:r,bindingEngine:i,translationEngine:l,actionDispatcher:u,parentComponentContext:de,parentFormContextProp:zt,isInsideIteration:b,isEditMode:v,onComponentSelect:S,onComponentHover:_,componentPath:be,onDragStart:x,onDragEnd:k,layoutKey:M},Te)})},[A.text,A.children,A.id,e,le,n,r,i,l,u,de,zt,Ct,ut,Ot,Lt,b,v,S,_,O,x,k,M]),hn=I.useMemo(()=>{if(!A.iteration)return null;try{const q=dd(A.iteration.source,le,i);if(!Array.isArray(q))return ht.warn(`iteration source가 배열이 아닙니다 (컴포넌트: ${A.id}):`,q),null;const ie=Za();return ie?.isEnabled()&&ie.trackIteration(A.id||`iteration-${Date.now()}`,A.iteration.source,A.iteration.item_var,A.iteration.index_var,q.length),q.map((oe,Z)=>{const be={...le,[A.iteration.item_var]:oe};A.iteration.index_var&&(be[A.iteration.index_var]=Z);const me=Z===0||Z===q.length-1;ie?.isEnabled()&&me&&ie.trackNestedContext?.({componentId:`${A.id||"unknown"}-iter-${Z}`,componentType:"iteration",parentContext:{available:Object.keys(le),values:{}},ownContext:{added:[A.iteration.item_var,...A.iteration.index_var?[A.iteration.index_var]:[]],values:{[A.iteration.item_var]:oe,...A.iteration.index_var?{[A.iteration.index_var]:Z}:{}}},depth:1});const Te={...A,iteration:void 0,responsive:void 0},xe=O?`${O}.iteration.${Z}`:`iteration.${Z}`,je=`${Lt(A.id,"item")}-${Z}`;return ft.jsx(ja,{componentDef:Te,dataContext:be,translationContext:n,registry:r,bindingEngine:i,translationEngine:l,actionDispatcher:u,parentComponentContext:de,parentFormContextProp:zt,isInsideIteration:!0,isEditMode:v,onComponentSelect:S,onComponentHover:_,componentPath:xe,onDragStart:x,onDragEnd:k,layoutKey:M},je)})}catch(q){return ht.error(`iteration 렌더링 실패 (컴포넌트: ${A.id}):`,q),null}},[A.iteration,A.children,A.id,e,le,n,r,i,l,u,de,zt,Lt,v,S,_,O,x,k,M]),[Ba,Jt]=I.useState(0),Dr=I.useMemo(()=>{if(!A.sortable||!A.itemTemplate)return null;const{sortable:q,itemTemplate:ie}=A;try{const oe=dd(q.source,le,i);if(!Array.isArray(oe))return ht.warn(`sortable source가 배열이 아닙니다 (컴포넌트: ${A.id}):`,oe),null;if(oe.length===0)return null;const Z=q.itemKey||"id",be=q.strategy||"verticalList",me=q.itemVar||"$item",Te=q.indexVar||"$index",xe=q.handle,je=q.wrapperElement,ze=(Ye,Ke)=>{const Ae=A.actions?.filter(Re=>Re.event==="onSortEnd"||Re.type==="onSortEnd");if(Jt(Re=>Re+1),Ae&&Ae.length>0&&u){const Re={...le,$sortedItems:Ye,$sortEvent:Ke};Ae.forEach(Ue=>{try{const ot=u.createHandler(Ue,Re,de),At=new Event("sortend");ot(At)}catch(ot){ht.error(`onSortEnd action failed: ${Ue.handler}`,ot)}})}},$e=Ye=>{const Ke=A.actions?.filter(Ae=>Ae.event==="onSortStart"||Ae.type==="onSortStart");if(Ke&&Ke.length>0&&u){const Ae={...le,$activeId:Ye.activeId};Ke.forEach(Re=>{try{const Ue=u.createHandler(Re,Ae,de),ot=new Event("sortstart");Ue(ot)}catch(Ue){ht.error(`onSortStart action failed: ${Re.handler}`,Ue)}})}},De=oe.map((Ye,Ke)=>{const Ae=String(Ye[Z]),Re={...le,[me]:Ye,[Te]:Ke},Ue=O?`${O}.sortable.${Ke}`:`sortable.${Ke}`,ot=`${Lt(A.id,"sortable-item")}-v${Ba}-${Ae}`;return ft.jsx(D_,{id:Ae,handle:xe,...je?{as:je}:{},children:(je&&ie.children?ie.children:[ie]).map((At,Qt)=>ft.jsx(ja,{componentDef:At,dataContext:Re,translationContext:n,registry:r,bindingEngine:i,translationEngine:l,actionDispatcher:u,parentComponentContext:de,parentFormContextProp:void 0,isInsideIteration:!0,isEditMode:v,onComponentSelect:S,onComponentHover:_,componentPath:Ue,onDragStart:x,onDragEnd:k,layoutKey:M},`${ot}-child-${Qt}`))},ot)});return ft.jsx(T_,{items:oe,itemKey:Z,strategy:be,onSortEnd:ze,onSortStart:$e,sortVersion:Ba,children:De})}catch(oe){return ht.error(`sortable 렌더링 실패 (컴포넌트: ${A.id}):`,oe),null}},[A.sortable,A.itemTemplate,A.actions,A.id,e,le,n,r,i,l,u,de,Lt,v,S,_,O,x,k,Ba,M]),tr=I.useRef(!1);I.useEffect(()=>{if(tr.current)return;tr.current=!0;const q=Za();if(q?.isEnabled()&&q.trackMount(o.id,{name:o.name,type:o.type||"component",props:Ee}),o.lifecycle?.onMount&&o.lifecycle.onMount.length>0)for(const oe of o.lifecycle.onMount)try{const Z=u.createHandler(oe,le,de),be=new Event("mount");Z(be),ht.log(`Lifecycle onMount executed: ${oe.handler} (Component: ${o.id})`)}catch(Z){ht.error(`Lifecycle onMount failed: ${oe.handler} (Component: ${o.id})`,Z)}const ie=[];if(o.onComponentEvent&&o.onComponentEvent.length>0){const oe=window.G7Core;if(oe?.componentEvent?.on)for(const Z of o.onComponentEvent){if(!Z.event){ht.warn(`onComponentEvent: event name is required (Component: ${o.id})`);continue}const be=async Te=>{try{const xe={...le,_eventData:Te},ze=await u.createHandler({handler:Z.handler,params:Z.params,onSuccess:Z.onSuccess,onError:Z.onError},xe,de)(new CustomEvent(Z.event,{detail:Te}));return ht.log(`onComponentEvent "${Z.event}" handled: ${Z.handler} (Component: ${o.id})`,{eventData:Te,result:ze}),ze}catch(xe){throw ht.error(`onComponentEvent "${Z.event}" failed: ${Z.handler} (Component: ${o.id})`,xe),xe}},me=oe.componentEvent.on(Z.event,be);ie.push(me),ht.log(`onComponentEvent: Subscribed to "${Z.event}" (Component: ${o.id})`)}else ht.warn(`onComponentEvent: G7Core.componentEvent is not available (Component: ${o.id})`)}return()=>{const oe=Za();oe?.isEnabled()&&oe.trackUnmount(o.id);for(const Z of ie)try{Z()}catch(be){ht.error(`onComponentEvent: Failed to unsubscribe (Component: ${o.id})`,be)}if(ie.length>0&&ht.log(`onComponentEvent: Unsubscribed ${ie.length} event(s) (Component: ${o.id})`),o.lifecycle?.onUnmount&&o.lifecycle.onUnmount.length>0)for(const Z of o.lifecycle.onUnmount)try{const be=u.createHandler(Z,le,de),me=new Event("unmount");be(me),ht.log(`Lifecycle onUnmount executed: ${Z.handler} (Component: ${o.id})`)}catch(be){ht.error(`Lifecycle onUnmount failed: ${Z.handler} (Component: ${o.id})`,be)}}},[]);const An=I.useMemo(()=>{const q=Ee.dataKey,ie=Ee.trackChanges,oe=Ee.debounce;return q?{dataKey:q,trackChanges:ie??!1,debounce:oe,setState:he,state:ue}:null},[Ee.dataKey,Ee.trackChanges,Ee.debounce,he,ue]);I.useEffect(()=>{const q=A.dataKey||Ee.dataKey;if(!q)return;const ie=Za();if(!ie?.isEnabled())return;const oe=[],Z=me=>{if(me)for(const Te of me){const xe=Te?.props?.name;if(xe&&oe.push({name:xe,type:Te.name||Te.type||"unknown"}),Te?.children&&Z(Te.children),Te?.slots)for(const je of Object.values(Te.slots))Array.isArray(je)&&Z(je)}};if(o.children&&Z(o.children),o.slots)for(const me of Object.values(o.slots))Array.isArray(me)&&Z(me);const be=o.id||`form-${q}`;return ie.trackForm(be,q,oe),()=>{ie.untrackForm(be)}},[A,Ee.dataKey,o.id,o.children]);const sn=I.useRef(null),tt=I.useRef(void 0);I.useEffect(()=>{const q=Ee?.name;if(!q||!ve.dataKey||!ve.setState||Ee?.autoBinding===!1)return;const ie=`${ve.dataKey}.${q}`,oe=window.__g7AutoBindingPaths??new Map;return window.__g7AutoBindingPaths=oe,oe.set(ie,(oe.get(ie)??0)+1),()=>{const Z=oe.get(ie)??0;Z<=1?oe.delete(ie):oe.set(ie,Z-1)}},[Ee?.name,Ee?.autoBinding,ve.dataKey,ve.setState]);const na=I.useMemo(()=>{const{dataKey:q,trackChanges:ie,debounce:oe,...Z}=Ee,be=Z.name;if(!be||!ve.dataKey||!ve.setState)return Z;if(Z.autoBinding===!1){const{autoBinding:Ae,...Re}=Z;return Re}const me=`${ve.dataKey}.${be}`,Te=RC(ve.state,me),xe=Te!==void 0?Te:Z.value,ze=r.getMetadata(o.name)?.bindingType,$e=typeof xe=="boolean"&&(ze==="checked"||ze==="checkable"&&["checkbox","radio"].includes(Z?.type)),De=ve.debounce,Ye=Ae=>{const Re=ve.state||{},Ue=kC(Re,me,Ae);if(ve.trackChanges&&(Ue.hasChanges=!0),window.__g7PendingLocalState=Ue,ve.setState(Ue),ve._isGlobal)return;const ot=window.G7Core,At={[me]:Ae};ve.trackChanges&&(At.hasChanges=!0),ot?.state?.setLocal?.(At,{render:!1})},Ke=(Ae,Re)=>{De&&De>0?(sn.current&&clearTimeout(sn.current),sn.current=setTimeout(()=>{Ye(Ae),sn.current=null,Re&&(Re(),window.__g7PendingLocalState=null)},De)):(Ye(Ae),Re&&(Re(),window.__g7PendingLocalState=null))};if($e)return{...Z,checked:xe,onChange:Re=>{const Ue=Re.target.checked;Ye(Ue),Z.onChange&&Z.onChange(Re)}};{const Ae=Ue=>{const ot=Ue?.target?.value!==void 0?Ue.target.value:Ue;De&&De>0&&(tt.current=ot);const At=Ue?.target?{target:{value:ot,name:Ue.target.name,type:Ue.target.type,checked:Ue.target.checked},currentTarget:Ue.currentTarget?{value:ot,name:Ue.currentTarget.name}:void 0}:Ue;Ke(ot,()=>{Z.onChange&&Z.onChange(At)})};let Re;return tt.current!==void 0?sn.current!==null?Re=tt.current:String(xe??"")===String(tt.current)?(tt.current=void 0,Re=xe??""):Re=tt.current:Re=xe??"",{...Z,value:Re,onChange:Ae}}},[Ee,ve,ve.state,ve.debounce]),kn=I.useMemo(()=>{const q=Za();if(q?.isEnabled()&&q.trackRender(o.name),!Oe)return null;if(A.sortable&&A.itemTemplate)return Dr;if(A.iteration)return hn;if(A.type==="extension_point"){const{layout:ze,columns:$e,gap:De,className:Ye,...Ke}=A.props||{};let Ae=Ye||"";return ze==="grid"&&$e?Ae=`${Ae} grid grid-cols-${$e} gap-${De||4}`.trim():ze==="flex"&&(Ae=`${Ae} flex flex-col gap-${De||4}`.trim()),ft.jsx("div",{id:Nt,className:Ae||void 0,...Ke,children:_n})}const ie=r.getComponent(A.name);if(!ie)return ht.error(`컴포넌트를 찾을 수 없습니다: ${A.name} (ID: ${A.id})`,"componentDef:",JSON.stringify(A,null,2)),null;const oe=e._global?._remountKeys,Z={...na,id:na.id??Nt,...oe&&Object.keys(oe).length>0&&{__remountTrigger:JSON.stringify(oe)}};if(ge?.listeners&&ge.handle&&na["data-drag-handle"]!==void 0&&(Object.assign(Z,ge.listeners),Z.style={...Z.style,cursor:ge.isDragging?"grabbing":"grab"}),v){const ze=A.id||`auto_${A.name||A.type||"unknown"}_${Math.random().toString(36).substring(2,8)}`,$e=Ke=>{typeof Ke.preventDefault=="function"&&Ke.preventDefault(),S&&(Ke.stopPropagation(),S(ze,Ke))},De={"data-editor-id":ze,"data-editor-name":A.name,"data-editor-type":A.type,onClick:$e};O&&(De["data-editor-path"]=O);const Ye=A.__editorSlotName??A.slot;typeof Ye=="string"&&(De["data-editor-slot"]=Ye),_&&(De.onMouseMove=Ke=>{Ke.stopPropagation(),_(ze,Ke)},De.onMouseLeave=Ke=>{_(null,Ke)}),Object.assign(Z,De),Z.editorAttrs=De}const be=A.type==="basic",me=A.type==="layout",xe=be||me?(()=>{const ze={};for(const[$e,De]of Object.entries(Z))$e.startsWith("__")||$e==="editorAttrs"&&be||(ze[$e]=De);return ze})():Z;let je=ft.jsx(ie,{...xe,children:_n});if(zt&&(je=ft.jsx(xC,{value:zt,children:je})),A.isolatedState){const ze=typeof A.isolatedState=="object"?A.isolatedState:{},$e=e?._isolatedInit,De=$e?{...ze,...$e}:ze;je=ft.jsx(NC,{initialState:De,scopeId:A.isolatedScopeId,children:je})}return je},[Oe,A.iteration,A.sortable,A.itemTemplate,A.type,A.name,A.id,A.props,A.isolatedState,A.isolatedScopeId,r,na,_n,hn,Dr,ge,An,v,S,_,x,k,O,e._global?._remountKeys]),nr=I.useMemo(()=>{const q=A.blur_until_loaded;if(!q||e?._global?.__isPreview)return!1;if(typeof q=="string"){const Z=Ct(q);if(Z!==null)try{const be={componentId:A.id,componentName:A.name,propName:"blur_until_loaded"};return!!i.evaluateExpression(Z,le,be)}catch(be){return ht.warn(`blur_until_loaded 표현식 평가 실패 (컴포넌트: ${A.id}):`,be),!1}return!1}if(typeof q=="object"&&q!==null){if(!q.enabled)return!1;if(q.data_sources)return(Array.isArray(q.data_sources)?q.data_sources:[q.data_sources]).some(Te=>e[Te]===void 0);if(Q)return!0;const Z=["route","query","_global","_local","_dataSourceErrors"];return Object.keys(e).filter(me=>!Z.includes(me)&&!me.startsWith("_")).some(me=>e[me]===void 0)}if(Q)return!0;const ie=["route","query","_global","_local","_dataSourceErrors"];return Object.keys(e).filter(Z=>!ie.includes(Z)&&!Z.startsWith("_")).some(Z=>e[Z]===void 0)},[A.blur_until_loaded,A.id,Q,e,le,i,Ct]);if(nr){const q=A.blur_until_loaded;if(typeof q=="object"&&q?.data_sources){const oe=(Array.isArray(q.data_sources)?q.data_sources:[q.data_sources]).reduce((be,me)=>(be[me]=e[me]===void 0?"UNDEFINED":"LOADED",be),{}),Z=Object.keys(e).filter(be=>!be.startsWith("_"));ht.log(`[BLUR APPLIED] Component: ${A.id}, data_sources status:`,oe,"Available keys:",Z)}else ht.log(`[BLUR APPLIED] Component: ${A.id}, blur_until_loaded:`,q)}const _a=I.useMemo(()=>{if(!A.blur_until_loaded)return{wrapperClasses:"",innerClasses:""};const q=vt?.className||"";if(!q)return{wrapperClasses:"",innerClasses:""};const ie=[/^(sm:|md:|lg:|xl:|2xl:)?(col-span-|row-span-|col-start-|col-end-|row-start-|row-end-)/,/^(sm:|md:|lg:|xl:|2xl:)?(self-|place-self-|order-)/,/^(sm:|md:|lg:|xl:|2xl:)?(flex-shrink|flex-grow|flex-\d|basis-)/],oe=q.split(/\s+/).filter(Boolean),Z=[],be=[];for(const me of oe)ie.some(xe=>xe.test(me))?Z.push(me):be.push(me);return{wrapperClasses:Z.join(" "),innerClasses:be.join(" ")}},[A.blur_until_loaded,vt?.className]),on=window.__slotContextValue;return He&&on?.isEnabled?null:ft.jsx(M_,{componentId:o.id,componentName:o.name,children:A.blur_until_loaded?ft.jsx("div",{className:[_a.wrapperClasses,nr?"opacity-50 blur-sm transition-all duration-300 pointer-events-none":void 0].filter(Boolean).join(" ")||void 0,children:kn}):kn})});ja.displayName="DynamicRenderer",typeof window<"u"&&(window.__DynamicRenderer=ja);function $_(o){const e={};try{const r=new URL(o,typeof window<"u"?window.location.origin:"http://localhost").searchParams,i=new Set;for(const l of r.keys()){if(i.has(l))continue;i.add(l);const u=r.getAll(l);u.length>1||l.endsWith("[]")?e[l]=u:e[l]=u[0]}}catch{}return e}function N_(o){try{return new URL(o,typeof window<"u"?window.location.origin:"http://localhost").pathname}catch{return o.split("?")[0]}}const bi=class bi{constructor(){$(this,"config",{enabled:!1,maxHistorySize:100,logLevel:"info",serverEndpoint:"/_boost/g7-debug/dump-state",autoCapture:!0});$(this,"stateHistory",[]);$(this,"snapshotIdCounter",0);$(this,"stateWatchers",new Map);$(this,"currentLocalState",{});$(this,"currentComputedState",{});$(this,"currentParentContext");$(this,"actionHistory",[]);$(this,"actionWatchers",new Set);$(this,"cacheStats",{hits:0,misses:0,entries:0});$(this,"cacheDecisions",[]);$(this,"cacheDecisionIdCounter",0);$(this,"maxCacheDecisions",200);$(this,"currentRenderCycleId",null);$(this,"isInActionExecution",!1);$(this,"isInIteration",!1);$(this,"mountedComponents",new Map);$(this,"eventListeners",new Map);$(this,"mountWatchers",new Set);$(this,"unmountWatchers",new Set);$(this,"renderCounts",new Map);$(this,"bindingEvalCount",0);$(this,"profilingData",[]);$(this,"isProfiling",!1);$(this,"profilingStartTime",0);$(this,"activeRequests",new Map);$(this,"requestHistory",[]);$(this,"pendingDataSources",new Set);$(this,"requestWatchers",new Set);$(this,"wsConnections",new Map);$(this,"wsMessageHistory",[]);$(this,"wsMessageWatchers",new Set);$(this,"ifConditions",new Map);$(this,"iterations",new Map);$(this,"conditionWatchers",new Set);$(this,"forms",new Map);$(this,"formWatchers",new Set);$(this,"expressionHistory",[]);$(this,"expressionWatchers",new Set);$(this,"expressionIdCounter",0);$(this,"dataSources",new Map);$(this,"dataPathTransforms",[]);$(this,"maxDataPathTransforms",100);$(this,"nestedContexts",[]);$(this,"nestedContextIdCounter",0);$(this,"maxNestedContexts",100);$(this,"formBindingIssues",[]);$(this,"formBindingValidations",[]);$(this,"formBindingIssueIdCounter",0);$(this,"maxFormBindingIssues",100);$(this,"computedProperties",new Map);$(this,"computedRecalcLogs",[]);$(this,"computedRecalcIdCounter",0);$(this,"maxComputedRecalcLogs",100);$(this,"handlers",new Map);$(this,"componentEventSubscriptions",new Map);$(this,"componentEventEmitHistory",[]);$(this,"componentEventIdCounter",0);$(this,"maxComponentEventHistory",100);$(this,"stateRenderingLogs",[]);$(this,"currentStateChangeContext",null);$(this,"stateRenderingIdCounter",0);$(this,"componentRenderCounts",new Map);$(this,"stateToComponentMap",new Map);$(this,"maxStateRenderingLogs",100);$(this,"componentStateSources",new Map);$(this,"contextFlowNodes",new Map);$(this,"dynamicStates",new Map);$(this,"styleIssues",[]);$(this,"componentStyles",new Map);$(this,"authEvents",[]);$(this,"authHeaderHistory",[]);$(this,"authEventIdCounter",0);$(this,"maxAuthEventHistory",50);$(this,"logHistory",[]);$(this,"logIdCounter",0);$(this,"maxLogHistory",500);$(this,"currentLayout",null);$(this,"layoutHistory",[]);$(this,"layoutIdCounter",0);$(this,"layoutStats",{totalLoads:0,cacheHits:0,apiLoads:0});$(this,"maxLayoutHistory",50);$(this,"executionDetails",new Map);$(this,"stateChangeHistory",[]);$(this,"dataSourceChangeHistory",[]);$(this,"changeAlerts",[]);$(this,"changeExpectations",new Map);$(this,"executionIdCounter",0);$(this,"stateChangeIdCounter",0);$(this,"alertIdCounter",0);$(this,"maxExecutionDetails",100);$(this,"maxStateChangeHistory",200);$(this,"maxChangeAlerts",100);$(this,"sequenceExecutions",[]);$(this,"sequenceExecutionStack",[]);$(this,"sequenceIdCounter",0);$(this,"maxSequenceExecutions",50);$(this,"staleClosureWarnings",[]);$(this,"staleClosureIdCounter",0);$(this,"maxStaleClosureWarnings",100);$(this,"stateCaptureRegistry",new Map);$(this,"modalStates",new Map);$(this,"modalStateIssues",[]);$(this,"modalStateRelations",[]);$(this,"modalStateChangeLogs",[]);$(this,"modalStateIssueIdCounter",0);$(this,"modalStateChangeLogIdCounter",0);$(this,"maxModalStateIssues",100);$(this,"maxModalStateChangeLogs",200);$(this,"namedActionDefinitions",{});$(this,"namedActionRefLogs",[]);$(this,"namedActionRefIdCounter",0);$(this,"maxNamedActionRefLogs",200);$(this,"debounceActionHistory",[]);$(this,"dataSourceUpdateHistory",[]);$(this,"debounceActionIdCounter",0);$(this,"dataSourceUpdateIdCounter",0)}static getInstance(){return bi.instance||(bi.instance=new bi),bi.instance}initialize(){if(this.config.enabled=this.checkDebugMode(),!this.config.enabled){console.log("[G7DevTools] 비활성화됨 (환경설정 > 고급 설정 > 디버그 모드를 켜세요)");return}console.log("[G7DevTools] 활성화됨"),this.setupGlobalErrorHandler()}checkDebugMode(){try{if(window.G7Config?.debug===!0)return!0;const r=window.G7Core?.state?.get?.();return r?.settings?.advanced?.debug_mode===!0||r?._global?.settings?.advanced?.debug_mode===!0}catch{return!1}}isEnabled(){return this.config.enabled}setupGlobalErrorHandler(){window.addEventListener("error",e=>{this.config.enabled&&this.logAction({id:this.generateId(),type:"globalError",startTime:Date.now(),status:"error",error:{name:"Error",message:e.message,stack:e.error?.stack}})}),window.addEventListener("unhandledrejection",e=>{this.config.enabled&&this.logAction({id:this.generateId(),type:"unhandledRejection",startTime:Date.now(),status:"error",error:{name:"UnhandledRejection",message:String(e.reason)}})})}captureStateSnapshot(e){if(!this.config.enabled)return;const n={id:++this.snapshotIdCounter,timestamp:Date.now(),source:e.source,prev:this.sanitizeObject(e.prev),next:this.sanitizeObject(e.next),diff:e.diff};this.stateHistory.push(n),this.stateHistory.length>this.config.maxHistorySize&&this.stateHistory.shift(),this.notifyStateWatchers(n)}getState(){try{const e=window.G7Core,n=e?.state?.get?.()||{},r={};if(e?._isolatedStates&&typeof e._isolatedStates=="object")for(const[i,l]of Object.entries(e._isolatedStates))r[i]=this.sanitizeObject(l);return{_global:n._global||n,_local:this.currentLocalState,_computed:this.currentComputedState,_isolated:Object.keys(r).length>0?r:void 0,$parent:this.currentParentContext}}catch{return{_global:{},_local:this.currentLocalState,_computed:this.currentComputedState}}}updateLocalState(e){this.config.enabled&&(this.currentLocalState=this.sanitizeObject(e))}updateComputedState(e){this.config.enabled&&(this.currentComputedState=this.sanitizeObject(e))}updateParentContext(e){this.config.enabled&&(this.currentParentContext=e?this.sanitizeObject(e):void 0)}getStateHistory(){return[...this.stateHistory]}getDualStorageMismatch(){const e=this.currentLocalState||{};let n={};try{n=(window.G7Core?.state?.get?.()||{})._local||{}}catch{n={}}const r=this.findMismatchedLeafPaths(e,n);return{hasMismatch:r.length>0,mismatchedPaths:r,storageA:e,storageB:n}}findMismatchedLeafPaths(e,n,r=""){const i=[],l=new Set([...Object.keys(e||{}),...Object.keys(n||{})]);for(const u of l){const d=r?`${r}.${u}`:u,f=e?.[u],g=n?.[u],m=f&&typeof f=="object"&&!Array.isArray(f),b=g&&typeof g=="object"&&!Array.isArray(g);if(m&&b)i.push(...this.findMismatchedLeafPaths(f,g,d));else{const v=f===void 0?"__undefined__":JSON.stringify(f),S=g===void 0?"__undefined__":JSON.stringify(g);v!==S&&i.push(d)}}return i}watchState(e,n){return this.stateWatchers.has(e)||this.stateWatchers.set(e,new Set),this.stateWatchers.get(e).add(n),()=>{this.stateWatchers.get(e)?.delete(n)}}notifyStateWatchers(e){if(this.stateWatchers.get("*")?.forEach(n=>{try{n(e.next,e.prev,"*")}catch(r){console.error("[G7DevTools] State watcher error:",r)}}),e.diff)for(const n of e.diff.changed)this.stateWatchers.get(n.path)?.forEach(r=>{try{r(n.newValue,n.oldValue,n.path)}catch(i){console.error("[G7DevTools] State watcher error:",i)}})}diffSnapshots(e,n){const r=this.stateHistory.find(l=>l.id===e),i=this.stateHistory.find(l=>l.id===n);return!r||!i?null:this.calculateDiff(r.next,i.next)}calculateDiff(e,n,r=""){const i={added:[],removed:[],changed:[]},l=new Set(Object.keys(e)),u=new Set(Object.keys(n));for(const d of u){const f=r?`${r}.${d}`:d;l.has(d)?JSON.stringify(e[d])!==JSON.stringify(n[d])&&i.changed.push({path:f,oldValue:e[d],newValue:n[d]}):i.added.push(f)}for(const d of l){const f=r?`${r}.${d}`:d;u.has(d)||i.removed.push(f)}return i}logAction(e){if(!this.config.enabled)return;const n=this.actionHistory.findIndex(r=>r.id===e.id);n>=0?this.actionHistory[n]={...this.actionHistory[n],...e}:(this.actionHistory.push(e),this.actionHistory.length>this.config.maxHistorySize&&this.actionHistory.shift()),this.isProfiling&&this.profilingData.push({type:"action",action:e.type,timestamp:performance.now(),duration:e.duration}),this.notifyActionWatchers(e)}getActionHistory(){return[...this.actionHistory]}watchActions(e){return this.actionWatchers.add(e),()=>{this.actionWatchers.delete(e)}}notifyActionWatchers(e){this.actionWatchers.forEach(n=>{try{n(e)}catch(r){console.error("[G7DevTools] Action watcher error:",r)}})}getActionMetrics(){const e=this.actionHistory.filter(l=>l.status==="success"),n=this.actionHistory.filter(l=>l.status==="error"),r={};for(const l of this.actionHistory)r[l.type]=(r[l.type]||0)+1;const i=e.reduce((l,u)=>l+(u.duration||0),0);return{totalActions:this.actionHistory.length,successCount:e.length,errorCount:n.length,averageDuration:e.length>0?i/e.length:0,actionsByType:r}}recordCacheHit(){this.config.enabled&&this.cacheStats.hits++}recordCacheMiss(){this.config.enabled&&this.cacheStats.misses++}updateCacheEntries(e){this.config.enabled&&(this.cacheStats.entries=e)}getCacheStats(){const e=this.cacheStats.hits+this.cacheStats.misses;return{...this.cacheStats,hitRate:e>0?this.cacheStats.hits/e:0}}resetCacheStats(){this.cacheStats={hits:0,misses:0,entries:0}}trackCacheDecision(e){if(!this.config.enabled)return;const n={id:`cache-${++this.cacheDecisionIdCounter}`,timestamp:Date.now(),expression:e.expression,decision:e.decision,reason:e.reason,context:{isInIteration:this.isInIteration,isInAction:this.isInActionExecution,renderCycleId:this.currentRenderCycleId||void 0,componentId:e.componentId,skipCacheOption:e.skipCacheOption},cachedValue:e.cachedValue!==void 0?this.safeClone(e.cachedValue):void 0,freshValue:e.freshValue!==void 0?this.safeClone(e.freshValue):void 0,valueMatch:e.cachedValue!==void 0&&e.freshValue!==void 0?JSON.stringify(e.cachedValue)===JSON.stringify(e.freshValue):void 0,duration:e.duration};this.cacheDecisions.push(n),this.cacheDecisions.length>this.maxCacheDecisions&&this.cacheDecisions.shift(),e.decision==="cache_hit"?this.cacheStats.hits++:(e.decision==="cache_miss"||e.decision==="skip_cache")&&this.cacheStats.misses++}startRenderCycle(e){return this.currentRenderCycleId=`render-${Date.now()}-${e||"root"}`,this.currentRenderCycleId}endRenderCycle(){this.currentRenderCycleId=null}startActionContext(){this.isInActionExecution=!0}endActionContext(){this.isInActionExecution=!1}startIterationContext(){this.isInIteration=!0}endIterationContext(){this.isInIteration=!1}getCacheDecisionTrackingInfo(){const e=this.getCacheDecisionStats();return{decisions:[...this.cacheDecisions],stats:e,timestamp:Date.now()}}getCacheDecisionStats(){const e=this.cacheDecisions;let n=0,r=0,i=0,l=0;const u={},d={};for(const g of e)g.decision==="cache_hit"?n++:g.decision==="cache_miss"?r++:g.decision==="skip_cache"?i++:g.decision==="invalidate"&&l++,u[g.reason]=(u[g.reason]||0)+1,g.context.componentId&&(d[g.context.componentId]=(d[g.context.componentId]||0)+1);const f=n+r+i;return{totalDecisions:e.length,cacheHits:n,cacheMisses:r,skipCacheCount:i,invalidateCount:l,byReason:u,byComponent:d,avgHitRate:f>0?n/f:0}}getRecentCacheDecisions(e=20,n){let r=[...this.cacheDecisions];return n&&(r=r.filter(i=>i.decision===n)),r.slice(-e)}clearCacheDecisionData(){this.cacheDecisions=[],this.cacheDecisionIdCounter=0}summarizePropsForLifecycle(e){if(!e||typeof e!="object")return e;const n={},r=["children","ref","key"];for(const[i,l]of Object.entries(e))if(!r.includes(i))if(l==null)n[i]=l;else if(Array.isArray(l))n[i]=`[Array(${l.length})]`;else if(typeof l=="object"){const u=Object.keys(l);u.length<=3?n[i]=`{${u.join(", ")}}`:n[i]=`{${u.slice(0,3).join(", ")}, ... +${u.length-3}}`}else typeof l=="string"&&l.length>50?n[i]=l.substring(0,50)+"...":typeof l=="function"?n[i]="[Function]":n[i]=l;return n}trackMount(e,n){if(!this.config.enabled)return;const r=this.summarizePropsForLifecycle(n.props),i={...n,props:r,id:e,mountTime:Date.now()};this.mountedComponents.set(e,i),this.mountWatchers.forEach(l=>{try{l({componentId:e,componentName:n.name,timestamp:i.mountTime})}catch(u){console.error("[G7DevTools] Mount watcher error:",u)}})}trackUnmount(e){if(!this.config.enabled)return;const n=this.mountedComponents.get(e),r=this.eventListeners.get(e)||[];r.length>0&&console.warn(`[G7DevTools] 컴포넌트 ${e} 언마운트 시 ${r.length}개 리스너 미정리`),n&&this.unmountWatchers.forEach(i=>{try{i({componentId:e,componentName:n.name,timestamp:Date.now(),orphanedListeners:r.length})}catch(l){console.error("[G7DevTools] Unmount watcher error:",l)}}),this.mountedComponents.delete(e)}trackListener(e,n,r){if(!this.config.enabled)return;const i=this.eventListeners.get(e)||[];i.push({type:n,target:r,addedAt:Date.now()}),this.eventListeners.set(e,i)}removeListener(e,n){if(!this.config.enabled)return;const r=this.eventListeners.get(e)||[],i=r.findIndex(l=>l.type===n);i>=0&&r.splice(i,1)}getMountedComponents(){return Array.from(this.mountedComponents.values())}getOrphanedListeners(){const e=[];for(const[n,r]of this.eventListeners)this.mountedComponents.has(n)||e.push(...r.map(i=>({...i,componentId:n})));return e}watchMount(e){return this.mountWatchers.add(e),()=>{this.mountWatchers.delete(e)}}watchUnmount(e){return this.unmountWatchers.add(e),()=>{this.unmountWatchers.delete(e)}}trackRender(e){if(!this.config.enabled)return;const n=this.renderCounts.get(e)||0;this.renderCounts.set(e,n+1),this.isProfiling&&this.profilingData.push({type:"render",component:e,timestamp:performance.now()})}trackBindingEval(e){this.config.enabled&&(this.bindingEvalCount++,this.isProfiling&&e&&this.profilingData.push({type:"binding",expression:e,timestamp:performance.now()}))}getRenderCount(){return new Map(this.renderCounts)}getBindingEvalCount(){return this.bindingEvalCount}getMemoryWarnings(){const e=[];try{const i=this.getState(),l=JSON.stringify(i).length;l>1e6&&e.push({type:"large-state",message:`상태 크기가 ${(l/1024/1024).toFixed(2)}MB입니다`,suggestion:"불필요한 데이터 정리 필요",severity:l>5e6?"error":"warning"})}catch{}this.stateHistory.length>this.config.maxHistorySize*.8&&e.push({type:"large-history",message:`상태 이력이 ${this.stateHistory.length}개입니다`,suggestion:"maxHistory 설정 조정 필요",severity:"warning"});const n=this.getOrphanedListeners().length;n>0&&e.push({type:"orphaned-listeners",message:`${n}개의 정리되지 않은 이벤트 리스너`,suggestion:"useEffect cleanup 또는 removeEventListener 확인",severity:n>10?"error":"warning"});const r=Array.from(this.renderCounts.entries()).filter(([,i])=>i>50);return r.length>0&&e.push({type:"excessive-renders",message:`${r.length}개 컴포넌트가 50회 이상 렌더링`,suggestion:"React.memo, useMemo, useCallback 사용 고려",severity:"warning"}),e}startProfiling(){this.config.enabled&&(this.isProfiling=!0,this.profilingData=[],this.profilingStartTime=performance.now(),console.log("[G7DevTools] 프로파일링 시작"))}stopProfiling(){this.isProfiling=!1;const e=performance.now()-this.profilingStartTime,n=this.analyzeProfile(e);return console.log("[G7DevTools] 프로파일링 완료",n),n}analyzeProfile(e){const n=this.profilingData.filter(g=>g.type==="render"),r=this.profilingData.filter(g=>g.type==="binding"),i=this.profilingData.filter(g=>g.type==="action"),l={};for(const g of n)g.component&&(l[g.component]||(l[g.component]={count:0,durations:[]}),l[g.component].count++,g.duration&&l[g.component].durations.push(g.duration));const u=Object.entries(l).map(([g,m])=>({name:g,renderCount:m.count,avgDuration:m.durations.length>0?m.durations.reduce((b,v)=>b+v,0)/m.durations.length:0})).sort((g,m)=>m.renderCount-g.renderCount).slice(0,10),d={};for(const g of r)g.expression&&(d[g.expression]=(d[g.expression]||0)+1);const f=Object.entries(d).sort(([,g],[,m])=>m-g).slice(0,10).map(([g])=>g);return{duration:e,entries:this.profilingData,summary:{totalRenders:n.length,totalBindings:r.length,totalActions:i.length,slowestComponents:u,hotPaths:f}}}resetPerformanceStats(){this.renderCounts.clear(),this.bindingEvalCount=0,this.profilingData=[]}trackRequest(e,n,r){if(!this.config.enabled)return"";const i=this.generateId(),l=N_(e),u=$_(e);return this.activeRequests.set(i,{id:i,url:l,fullUrl:e,queryParams:u,method:n,startTime:Date.now(),status:"pending",requestBody:r?.requestBody?this.sanitizeObject(r.requestBody):void 0,dataSourceId:r?.dataSourceId}),this.isProfiling&&this.profilingData.push({type:"network",timestamp:performance.now()}),i}completeRequest(e,n,r){if(!this.config.enabled)return;const i=this.activeRequests.get(e);if(!i)return;const l={...i,status:n>=200&&n<300?"success":"error",statusCode:n,duration:Date.now()-i.startTime,endTime:Date.now(),response:this.sanitizeObject(r)};this.requestHistory.push(l),this.activeRequests.delete(e),this.requestHistory.length>this.config.maxHistorySize&&this.requestHistory.shift(),this.notifyRequestWatchers(l)}failRequest(e,n){if(!this.config.enabled)return;const r=this.activeRequests.get(e);if(!r)return;const i={...r,status:"error",error:n,duration:Date.now()-r.startTime,endTime:Date.now()};this.requestHistory.push(i),this.activeRequests.delete(e),this.notifyRequestWatchers(i)}trackDataSource(e){this.config.enabled&&this.pendingDataSources.add(e)}completeDataSource(e){this.config.enabled&&this.pendingDataSources.delete(e)}getActiveRequests(){return Array.from(this.activeRequests.values())}getRequestHistory(){return[...this.requestHistory]}getPendingDataSources(){return Array.from(this.pendingDataSources)}watchRequest(e){return this.requestWatchers.add(e),()=>{this.requestWatchers.delete(e)}}notifyRequestWatchers(e){this.requestWatchers.forEach(n=>{try{n(e)}catch(r){console.error("[G7DevTools] Request watcher error:",r)}})}trackWebSocketConnection(e,n,r){this.config.enabled&&this.wsConnections.set(e,{id:e,url:n,state:r,connectedAt:r==="open"?Date.now():void 0})}trackWebSocketMessage(e,n,r,i){if(!this.config.enabled)return;const l={id:this.generateId(),connectionId:e,direction:n,type:r,payload:this.sanitizeObject(i),timestamp:Date.now(),sequence:this.wsMessageHistory.length};this.wsMessageHistory.push(l),this.wsMessageHistory.length>this.config.maxHistorySize&&this.wsMessageHistory.shift(),this.notifyWebSocketWatchers(l)}getWebSocketConnections(){return Array.from(this.wsConnections.values())}getWebSocketMessageHistory(){return[...this.wsMessageHistory]}getWebSocketConnectionState(){const e=Array.from(this.wsConnections.values());return e.some(n=>n.state==="open")?"connected":e.some(n=>n.state==="connecting")?"reconnecting":"disconnected"}watchWebSocketMessage(e){return this.wsMessageWatchers.add(e),()=>{this.wsMessageWatchers.delete(e)}}notifyWebSocketWatchers(e){this.wsMessageWatchers.forEach(n=>{try{n(e)}catch(r){console.error("[G7DevTools] WebSocket watcher error:",r)}})}trackIfCondition(e,n,r){if(!this.config.enabled)return;const i=this.ifConditions.get(e),l=i?.evaluatedValue;this.ifConditions.set(e,{id:e,expression:n,evaluatedValue:r,evaluationCount:(i?.evaluationCount||0)+1,lastEvaluated:Date.now()}),i&&l!==r&&this.notifyConditionWatchers({id:e,expression:n,oldValue:l,newValue:r,timestamp:Date.now()})}trackIteration(e,n){this.config.enabled&&this.iterations.set(e,{id:e,...n,lastRendered:Date.now()})}getIfConditions(){return Array.from(this.ifConditions.values())}getIterations(){return Array.from(this.iterations.values())}getScopeChain(e){const n=[],r=this.getState();return n.push({name:"_global",value:r._global,source:"global"}),n.push({name:"_local",value:r._local,source:"local"}),n.push({name:"_computed",value:r._computed,source:"computed"}),n}watchConditionChange(e){return this.conditionWatchers.add(e),()=>{this.conditionWatchers.delete(e)}}notifyConditionWatchers(e){this.conditionWatchers.forEach(n=>{try{n(e)}catch(r){console.error("[G7DevTools] Condition watcher error:",r)}})}trackForm(e,n,r){this.config.enabled&&this.forms.set(e,{id:e,dataKey:n,inputs:r,trackedAt:Date.now()})}trackFormChange(e,n,r){if(!this.config.enabled)return;const i={formId:e,inputName:n,value:r,timestamp:Date.now()};this.notifyFormWatchers(i)}untrackForm(e){this.forms.delete(e)}getForms(){return Array.from(this.forms.values())}getFormState(e){const n=this.getState();return this.getNestedValue(n,e)||{}}getBindingPath(e,n){return`${e}.${n}`}watchFormChange(e){return this.formWatchers.add(e),()=>{this.formWatchers.delete(e)}}notifyFormWatchers(e){this.formWatchers.forEach(n=>{try{n(e)}catch(r){console.error("[G7DevTools] Form watcher error:",r)}})}trackFormBindingIssue(e,n,r){if(!this.config.enabled)return;const i={id:`form-issue-${++this.formBindingIssueIdCounter}`,timestamp:Date.now(),type:e,severity:n,formId:r.formId,formDataKey:r.formDataKey,inputInfo:r.inputInfo,contextInfo:r.contextInfo,description:r.description,suggestion:r.suggestion,docLink:r.docLink};this.formBindingIssues.push(i),this.formBindingIssues.length>this.maxFormBindingIssues&&this.formBindingIssues.shift()}validateFormBinding(e,n,r,i){const l=r.map(f=>{const g=[];let m=!0;return f.name||(g.push("Input에 name 속성이 없습니다"),m=!1,this.trackFormBindingIssue("missing-input-name","error",{formId:e,formDataKey:n,inputInfo:{name:f.name,type:f.type},description:"Input에 name 속성이 없어 자동 바인딩이 동작하지 않습니다",suggestion:"Input에 name 속성을 추가하세요",docLink:"troubleshooting-components-form.md"})),n||(g.push("Form에 dataKey가 없습니다"),m=!1),{inputName:f.name||"(unnamed)",inputType:f.type,bindingPath:n&&f.name?`${n}.${f.name}`:"-",isValid:m,currentValue:f.value,issues:g}});if(n||this.trackFormBindingIssue("missing-datakey","error",{formId:e,description:"Form에 dataKey가 설정되지 않아 자동 바인딩이 동작하지 않습니다",suggestion:"Form 컴포넌트에 dataKey props를 설정하세요",docLink:"troubleshooting-components-form.md"}),i.isContextBroken){const f=i.breakReason?.includes("sortable")?"sortable-context-break":i.breakReason?.includes("modal")?"modal-context-isolation":"context-not-propagated";this.trackFormBindingIssue(f,"warning",{formId:e,formDataKey:n,contextInfo:{hasParentFormContext:i.hasParentContext,parentFormContextProp:i.parentContextProp,isInsideSortable:i.breakReason?.includes("sortable")||!1,isInsideModal:i.breakReason?.includes("modal")||!1,depth:0},description:i.breakReason||"Form 컨텍스트가 제대로 전파되지 않았습니다",suggestion:"parentFormContextProp={undefined}를 확인하거나 중첩 구조를 검토하세요",docLink:"troubleshooting-components-form.md"})}const u={formId:e,dataKey:n,timestamp:Date.now(),contextPropagation:i,inputBindings:l,isValid:l.every(f=>f.isValid)&&!!n&&!i.isContextBroken,issueCount:l.filter(f=>!f.isValid).length+(n?0:1)+(i.isContextBroken?1:0)},d=this.formBindingValidations.findIndex(f=>f.formId===e);return d>=0?this.formBindingValidations[d]=u:this.formBindingValidations.push(u),u}getFormBindingValidationTrackingInfo(){const e=this.getFormBindingValidationStats();return{issues:[...this.formBindingIssues],validations:[...this.formBindingValidations],stats:e,timestamp:Date.now()}}getFormBindingValidationStats(){const e={"missing-datakey":0,"missing-input-name":0,"context-not-propagated":0,"sortable-context-break":0,"modal-context-isolation":0,"duplicate-input-name":0,"value-type-mismatch":0,"binding-path-invalid":0},n={info:0,warning:0,error:0};for(const i of this.formBindingIssues)e[i.type]++,n[i.severity]++;const r=Object.entries(e).filter(([,i])=>i>0).sort((i,l)=>l[1]-i[1]).slice(0,5).map(([i,l])=>({type:i,count:l,description:this.getIssueTypeDescription(i)}));return{totalFormsValidated:this.formBindingValidations.length,validForms:this.formBindingValidations.filter(i=>i.isValid).length,formsWithIssues:this.formBindingValidations.filter(i=>!i.isValid).length,totalIssues:this.formBindingIssues.length,byIssueType:e,bySeverity:n,topIssues:r}}getIssueTypeDescription(e){return{"missing-datakey":"Form에 dataKey 누락","missing-input-name":"Input에 name 속성 누락","context-not-propagated":"Form 컨텍스트 전파 실패","sortable-context-break":"Sortable 컨테이너에서 컨텍스트 단절","modal-context-isolation":"모달에서 부모 Form 컨텍스트 격리","duplicate-input-name":"동일 Form 내 중복 Input name","value-type-mismatch":"값 타입과 Input 타입 불일치","binding-path-invalid":"바인딩 경로 유효하지 않음"}[e]||e}clearFormBindingIssues(){this.formBindingIssues=[],this.formBindingValidations=[],this.formBindingIssueIdCounter=0}trackComputedProperty(e,n,r,i,l,u,d){if(!this.config.enabled)return;const f=`computed-${e}-${u||"global"}`,g={id:f,name:e,expression:n,componentId:u,dependencies:r,currentValue:this.safeClone(i),lastComputedAt:Date.now(),computationTime:l,error:d};this.computedProperties.set(f,g)}trackComputedRecalc(e,n,r,i,l,u,d){if(!this.config.enabled)return;const f=`computed-${e}-${d||"global"}`,g=JSON.stringify(r)!==JSON.stringify(i),m={id:`recalc-${++this.computedRecalcIdCounter}`,computedId:f,computedName:e,timestamp:Date.now(),trigger:n,triggeredBy:u,previousValue:this.safeClone(r),newValue:this.safeClone(i),valueChanged:g,computationTime:l,cascadeCount:0};this.computedRecalcLogs.push(m),this.computedRecalcLogs.length>this.maxComputedRecalcLogs&&this.computedRecalcLogs.shift();const b=this.computedProperties.get(f);b&&(b.currentValue=this.safeClone(i),b.lastComputedAt=Date.now(),b.computationTime=l)}analyzeComputedDependencyChain(e,n){const r=new Set,i=[];let l=!1,u,d=0;const f=(m,b)=>{if(d=Math.max(d,b),r.has(m))return l=!0,u=[...i,m],{name:m,type:"computed",children:[],depth:b};r.add(m),i.push(m);const v=this.computedProperties.get(`computed-${m}-${n||"global"}`),S=[];if(v)for(const _ of v.dependencies)_.type==="computed"?S.push(f(_.path,b+1)):S.push({name:_.path,type:_.type,children:[],depth:b+1});return i.pop(),r.delete(m),{name:m,type:"computed",children:S,depth:b}},g=f(e,0);return{root:e,tree:g,hasCycle:l,cyclePath:u,maxDepth:d}}getComputedDependencyTrackingInfo(){const e=Array.from(this.computedProperties.values()),n=this.getComputedDependencyStats(),r=[];for(const i of e){const l=this.analyzeComputedDependencyChain(i.name,i.componentId);r.push(l)}return{properties:e,recalcLogs:[...this.computedRecalcLogs],dependencyChains:r,stats:n,timestamp:Date.now()}}getComputedDependencyStats(){const e={"state-change":0,"datasource-update":0,"dependency-change":0,manual:0,initial:0},n={},r={};let i=0,l=0;for(const g of this.computedRecalcLogs)e[g.trigger]++,g.valueChanged||l++,n[g.computedName]=(n[g.computedName]||0)+1,r[g.computedName]||(r[g.computedName]=[]),r[g.computedName].push(g.computationTime),i+=g.computationTime;const u=Object.entries(n).sort((g,m)=>m[1]-g[1]).slice(0,5).map(([g,m])=>({name:g,count:m})),d=Object.entries(r).map(([g,m])=>({name:g,avgTime:m.reduce((b,v)=>b+v,0)/m.length})).sort((g,m)=>m.avgTime-g.avgTime).slice(0,5);let f=0;for(const g of this.computedProperties.values())this.analyzeComputedDependencyChain(g.name,g.componentId).hasCycle&&f++;return{totalComputed:this.computedProperties.size,totalRecalculations:this.computedRecalcLogs.length,unnecessaryRecalculations:l,avgComputationTime:this.computedRecalcLogs.length>0?i/this.computedRecalcLogs.length:0,topRecalculated:u,slowestComputed:d,cycleDetectionCount:f,byTrigger:e}}clearComputedTracking(){this.computedProperties.clear(),this.computedRecalcLogs=[],this.computedRecalcIdCounter=0}trackModalOpen(e){if(!this.config.enabled)return;const n={modalId:e.modalId,modalName:e.modalName,openedAt:Date.now(),closedAt:null,scopeType:e.scopeType||"isolated",parentModalId:e.parentModalId,componentId:e.componentId,initialState:e.initialState?{...e.initialState}:{},currentState:e.initialState?{...e.initialState}:{},stateChangeCount:0,isolatedStateKeys:e.isolatedStateKeys||[],sharedStateKeys:e.sharedStateKeys||[]};this.modalStates.set(e.modalId,n),this.validateModalDefinitionExists(e.modalId,e.modalName),e.parentModalId&&(this.modalStateRelations.find(i=>i.parentModalId===e.parentModalId&&i.childModalId===e.modalId)||this.modalStateRelations.push({parentModalId:e.parentModalId,childModalId:e.modalId,sharedKeys:e.sharedStateKeys||[],isolatedKeys:e.isolatedStateKeys||[],relationType:"parent-child"}))}trackModalClose(e,n){if(!this.config.enabled)return;const r=this.modalStates.get(e);r&&(r.closedAt=Date.now(),n&&(r.currentState={...n}),this.detectStateLeakage(r))}validateModalDefinitionExists(e,n){const r=this.currentLayout;if(!r?.layoutJson)return;const i=r.layoutJson.modals;if(!i){this.recordModalStateIssue({type:"missing-definition",modalId:e,modalName:n,severity:"error",description:`모달 "${e}"이(가) modalStack에 추가되었으나, 현재 레이아웃에 modals 섹션이 없습니다. 레이아웃 경로: ${r.layoutPath}`,affectedStateKeys:[],expectedValue:`modals 섹션에 id="${e}" 정의 존재`,actualValue:"modals 섹션 없음"});return}const l=Array.isArray(i)?i:Object.values(i);l.some(d=>d?.id===e||d?.props?.id===e)||this.recordModalStateIssue({type:"missing-definition",modalId:e,modalName:n,severity:"error",description:`모달 "${e}"이(가) modalStack에 추가되었으나, 렌더링된 레이아웃의 modals 섹션에 해당 ID의 정의가 없습니다. partial 로딩 실패, 레이아웃 병합 문제, extends 상속 누락 등을 확인하세요. 레이아웃 경로: ${r.layoutPath}`,affectedStateKeys:[],expectedValue:`modals 배열에 id="${e}" 항목 존재`,actualValue:`modals 배열에 ${l.length}개 모달 정의 (${l.map(d=>d?.id||"unknown").join(", ")})`})}trackModalStateChange(e){if(!this.config.enabled)return;const n=this.modalStates.get(e.modalId);if(!n)return;n.stateChangeCount++,n.currentState[e.stateKey]=e.newValue;const r=this.checkIsolationViolation(n,e.stateKey),i={id:`modal-change-${++this.modalStateChangeLogIdCounter}`,modalId:e.modalId,modalName:n.modalName,timestamp:Date.now(),stateKey:e.stateKey,previousValue:e.previousValue,newValue:e.newValue,changeSource:e.changeSource||"user-action",violatesIsolation:r};this.modalStateChangeLogs.push(i),this.modalStateChangeLogs.length>this.maxModalStateChangeLogs&&this.modalStateChangeLogs.shift(),r&&this.recordModalStateIssue({type:"isolation-violation",modalId:e.modalId,modalName:n.modalName,severity:"warning",description:`모달 '${n.modalName}'에서 격리된 상태 키 '${e.stateKey}'가 변경됨`,affectedStateKeys:[e.stateKey]})}detectStateLeakage(e){if(e.scopeType==="isolated")for(const n of e.isolatedStateKeys){const r=e.initialState[n],i=e.currentState[n];if(r!==i&&e.parentModalId){const l=this.modalStates.get(e.parentModalId);l&&l.currentState.hasOwnProperty(n)&&this.recordModalStateIssue({type:"state-leakage",modalId:e.modalId,modalName:e.modalName,severity:"error",description:`모달 닫힘 후 상태 '${n}'가 부모 모달로 유출될 수 있음`,affectedStateKeys:[n],leakedValue:i,expectedValue:r})}}}checkIsolationViolation(e,n){return e.scopeType==="isolated",!1}recordModalStateIssue(e){const n={id:`modal-issue-${++this.modalStateIssueIdCounter}`,type:e.type,modalId:e.modalId,modalName:e.modalName,timestamp:Date.now(),severity:e.severity,description:e.description,affectedStateKeys:e.affectedStateKeys,leakedValue:e.leakedValue,expectedValue:e.expectedValue,actualValue:e.actualValue,stackInfo:e.stackInfo};this.modalStateIssues.push(n),this.modalStateIssues.length>this.maxModalStateIssues&&this.modalStateIssues.shift()}getModalStateScopeTrackingInfo(){const e=Array.from(this.modalStates.values()),n=this.getModalStateScopeStats();return{modals:e,issues:[...this.modalStateIssues],relations:[...this.modalStateRelations],changeLogs:[...this.modalStateChangeLogs],stats:n,timestamp:Date.now()}}getModalStateScopeStats(){const e=Array.from(this.modalStates.values()),n={warning:0,error:0},r={"state-leakage":0,"isolation-violation":0,"parent-mutation":0,"orphaned-state":0,"scope-mismatch":0,"cleanup-failure":0,"missing-definition":0};for(const l of this.modalStateIssues)n[l.severity]++,r[l.type]++;const i={isolated:0,shared:0,inherited:0};for(const l of e)i[l.scopeType]++;return{totalModals:e.length,openModals:e.filter(l=>l.closedAt===null).length,nestedModals:e.filter(l=>l.parentModalId!==void 0).length,totalIssues:this.modalStateIssues.length,issuesBySeverity:n,issuesByType:r,byScope:i,leakageDetectionCount:r["state-leakage"],cleanupFailureCount:r["cleanup-failure"]}}clearModalStateScopeTracking(){this.modalStates.clear(),this.modalStateIssues=[],this.modalStateRelations=[],this.modalStateChangeLogs=[],this.modalStateIssueIdCounter=0,this.modalStateChangeLogIdCounter=0}setNamedActionDefinitions(e){this.config.enabled&&(this.namedActionDefinitions=e||{})}trackNamedActionRef(e){if(!this.config.enabled)return;const n={...e,id:`named_action_ref_${++this.namedActionRefIdCounter}`};this.namedActionRefLogs.push(n),this.namedActionRefLogs.length>this.maxNamedActionRefLogs&&(this.namedActionRefLogs=this.namedActionRefLogs.slice(-this.maxNamedActionRefLogs))}getNamedActionTrackingInfo(){const e={};for(const r of this.namedActionRefLogs)e[r.actionRefName]=(e[r.actionRefName]||0)+1;const n=Object.keys(this.namedActionDefinitions).filter(r=>!e[r]);return{definitions:this.namedActionDefinitions,refLogs:[...this.namedActionRefLogs],stats:{totalDefinitions:Object.keys(this.namedActionDefinitions).length,totalRefs:this.namedActionRefLogs.length,refCountByName:e,unusedDefinitions:n},timestamp:Date.now()}}clearNamedActionTracking(){this.namedActionDefinitions={},this.namedActionRefLogs=[],this.namedActionRefIdCounter=0}trackExpressionEval(e){if(!this.config.enabled)return;const n={...e,id:`expr-${++this.expressionIdCounter}`,timestamp:Date.now(),warning:this.detectExpressionWarning(e)};this.expressionHistory.push(n),this.expressionHistory.length>500&&this.expressionHistory.shift(),this.isProfiling&&this.profilingData.push({type:"binding",expression:e.expression,timestamp:performance.now(),duration:e.duration}),this.notifyExpressionWatchers(n)}detectExpressionWarning(e){const{expression:n,result:r,resultType:i,method:l,duration:u}=e;if(i==="undefined"&&!n.includes("??")&&!n.includes("||")&&/^[a-zA-Z_$][a-zA-Z0-9_$.]*$/.test(n.replace(/{{|}}/g,"").trim()))return{type:"undefined-result",message:"표현식 결과가 undefined입니다",suggestion:`데이터가 로드되었는지 확인하거나 fallback 값을 추가하세요: ${n} ?? ''`};if(i==="null")return{type:"null-result",message:"표현식 결과가 null입니다",suggestion:`nullish coalescing 연산자를 사용하세요: ${n} ?? ''`};if(l==="resolveBindings"&&i==="string"){const d=String(r);if(d.includes("[object Object]")||/^\[.*\]$/.test(d))return{type:"array-to-string",message:"배열/객체가 문자열로 변환되었습니다",suggestion:"evaluateExpression()을 사용하여 원본 타입을 유지하세요"}}if(l==="resolveBindings"&&i==="string"&&String(r).includes("[object Object]"))return{type:"object-to-string",message:"객체가 [object Object]로 변환되었습니다",suggestion:"evaluateExpression()을 사용하거나 특정 속성에 접근하세요"};if(i==="undefined"&&n.includes(".")&&!n.includes("?.")){const d=n.replace(/{{|}}/g,"").trim().split(".");if(d.length>=2)return{type:"missing-optional-chain",message:"Optional chaining(?.) 누락 가능성",suggestion:`안전한 접근을 위해 ?. 사용을 고려하세요: ${d.join("?.")}`}}if((n.includes("{{item.")||n.includes("{{index}}"))&&Array.from(this.iterations.values()).some(g=>g.itemVar!=="item"))return{type:"wrong-iteration-var",message:"'item'/'index' 대신 iteration에서 정의한 변수명을 사용해야 합니다",suggestion:"iteration의 item_var/index_var에 정의된 변수명을 확인하세요"};if(u&&u>10)return{type:"slow-evaluation",message:`표현식 평가에 ${u.toFixed(2)}ms 소요됨`,suggestion:"복잡한 표현식을 단순화하거나 computed 값으로 분리하세요"}}getExpressions(){return[...this.expressionHistory]}getExpressionWarnings(){return this.expressionHistory.filter(e=>e.warning!=null)}searchExpressions(e){const n=e.toLowerCase();return this.expressionHistory.filter(r=>r.expression.toLowerCase().includes(n)||r.componentName?.toLowerCase().includes(n)||r.propName?.toLowerCase().includes(n))}getExpressionStats(){const e=this.expressionHistory,n=new Set(e.map(f=>f.expression)),r=e.filter(f=>f.warning!=null),i=e.filter(f=>f.fromCache),l=e.filter(f=>f.duration!=null).map(f=>f.duration),u={};for(const f of e)u[f.resultType]=(u[f.resultType]||0)+1;const d={};for(const f of r)f.warning&&(d[f.warning.type]=(d[f.warning.type]||0)+1);return{totalEvaluations:e.length,uniqueExpressions:n.size,warningCount:r.length,cacheHitRate:e.length>0?i.length/e.length:0,averageDuration:l.length>0?l.reduce((f,g)=>f+g,0)/l.length:0,byType:u,byWarning:d}}clearExpressions(){this.expressionHistory=[],this.expressionIdCounter=0}watchExpressions(e){return this.expressionWatchers.add(e),()=>{this.expressionWatchers.delete(e)}}notifyExpressionWatchers(e){this.expressionWatchers.forEach(n=>{try{n(e)}catch(r){console.error("[G7DevTools] Expression watcher error:",r)}})}setLogLevel(e){this.config.logLevel=e}setMaxHistory(e){this.config.maxHistorySize=Math.max(10,Math.min(1e3,e))}setServerEndpoint(e){this.config.serverEndpoint=e}getConfig(){return{...this.config}}generateId(){return`${Date.now()}-${Math.random().toString(36).substr(2,9)}`}sanitizeObject(e,n=new WeakSet){if(e===null||typeof e!="object")return e;if(n.has(e))return"[Circular]";if(n.add(e),Array.isArray(e))return e.map(i=>this.sanitizeObject(i,n));const r={};for(const i of Object.keys(e))try{r[i]=this.sanitizeObject(e[i],n)}catch{r[i]="[Unable to serialize]"}return r}getNestedValue(e,n){if(!n)return e;const r=n.split(".");let i=e;for(const l of r){if(i==null)return;i=i[l]}return i}getLifecycleInfo(){return{mountedComponents:Array.from(this.mountedComponents.values()),orphanedListeners:this.getOrphanedListeners()}}getPerformanceInfo(){return{renderCounts:this.renderCounts,bindingEvalCount:this.bindingEvalCount,memoryWarnings:this.getMemoryWarnings()}}getNetworkInfo(){return{activeRequests:Array.from(this.activeRequests.values()),requestHistory:[...this.requestHistory],pendingDataSources:Array.from(this.pendingDataSources)}}getConditionalInfo(){return{ifConditions:Array.from(this.ifConditions.values()),iterations:Array.from(this.iterations.values())}}getFormInfo(){return Array.from(this.forms.values())}getWebSocketInfo(){return{connections:Array.from(this.wsConnections.values()),messageHistory:[...this.wsMessageHistory],connectionState:this.getWebSocketConnectionState()}}getStateAtTime(e){const n=[...this.stateHistory].reverse().find(r=>r.timestamp<=e);if(n)return{_global:n.next,_local:{}}}reset(){this.stateHistory=[],this.actionHistory=[],this.cacheStats={hits:0,misses:0,entries:0},this.cacheDecisions=[],this.cacheDecisionIdCounter=0,this.currentRenderCycleId=null,this.isInActionExecution=!1,this.isInIteration=!1,this.mountedComponents.clear(),this.eventListeners.clear(),this.renderCounts.clear(),this.bindingEvalCount=0,this.profilingData=[],this.activeRequests.clear(),this.requestHistory=[],this.pendingDataSources.clear(),this.wsConnections.clear(),this.wsMessageHistory=[],this.ifConditions.clear(),this.iterations.clear(),this.forms.clear(),this.expressionHistory=[],this.expressionIdCounter=0,this.dataSources.clear(),this.dataPathTransforms=[],this.nestedContexts=[],this.nestedContextIdCounter=0,this.formBindingIssues=[],this.formBindingValidations=[],this.formBindingIssueIdCounter=0,this.computedProperties.clear(),this.computedRecalcLogs=[],this.computedRecalcIdCounter=0,this.modalStates.clear(),this.modalStateIssues=[],this.modalStateRelations=[],this.modalStateChangeLogs=[],this.modalStateIssueIdCounter=0,this.modalStateChangeLogIdCounter=0,this.logHistory=[],this.logIdCounter=0}getExpressionInfo(){return{expressions:this.getExpressions(),stats:this.getExpressionStats()}}trackLog(e,n,r){if(!this.config.enabled)return;const i=r.map(u=>{if(typeof u=="string")return u;try{return JSON.stringify(u)}catch{return String(u)}}).join(" "),l={id:`log-${++this.logIdCounter}`,level:e,prefix:n,message:i,args:this.sanitizeObject(r),timestamp:Date.now(),stack:e==="error"?new Error().stack:void 0};this.logHistory.push(l),this.logHistory.length>this.maxLogHistory&&this.logHistory.shift()}trackAction(e){if(!this.config.enabled)return;const n={id:`debounce-action-${++this.debounceActionIdCounter}`,...e,timestamp:Date.now()};this.debounceActionHistory.push(n),this.debounceActionHistory.length>100&&this.debounceActionHistory.shift()}trackDataSourceUpdate(e){if(!this.config.enabled)return;const n={id:`ds-update-${++this.dataSourceUpdateIdCounter}`,...e};this.dataSourceUpdateHistory.push(n),this.dataSourceUpdateHistory.length>100&&this.dataSourceUpdateHistory.shift()}getDebounceActionHistory(e){let n=[...this.debounceActionHistory];return e?.handler&&(n=n.filter(r=>r.handler.includes(e.handler))),e?.status&&(n=n.filter(r=>r.status===e.status)),e?.limit&&(n=n.slice(-e.limit)),n}getDataSourceUpdateHistory(e){let n=[...this.dataSourceUpdateHistory];return e?.dataSourceId&&(n=n.filter(r=>r.dataSourceId===e.dataSourceId)),e?.updateType&&(n=n.filter(r=>r.updateType===e.updateType)),e?.limit&&(n=n.slice(-e.limit)),n}getLogs(e){let n=[...this.logHistory];if(e?.level){const r=Array.isArray(e.level)?e.level:[e.level];n=n.filter(i=>r.includes(i.level))}if(e?.prefix){const r=e.prefix.toLowerCase();n=n.filter(i=>i.prefix.toLowerCase().includes(r))}if(e?.search){const r=e.search.toLowerCase();n=n.filter(i=>i.message.toLowerCase().includes(r))}return e?.since&&(n=n.filter(r=>r.timestamp>=e.since)),e?.limit&&(n=n.slice(-e.limit)),n}getLogStats(){const n=Date.now()-6e4,r={log:0,warn:0,error:0,debug:0,info:0},i={};let l=0,u=0;for(const d of this.logHistory)r[d.level]++,i[d.prefix]=(i[d.prefix]||0)+1,d.timestamp>=n&&(d.level==="error"&&l++,d.level==="warn"&&u++);return{totalLogs:this.logHistory.length,byLevel:r,byPrefix:i,recentErrors:l,recentWarnings:u}}clearLogs(){this.logHistory=[],this.logIdCounter=0}getLogInfo(){return{entries:this.getLogs(),stats:this.getLogStats()}}trackDataSourceDefinition(e){this.config.enabled&&this.dataSources.set(e.id,{...e,status:"idle"})}trackDataSourceLoading(e){if(!this.config.enabled)return;const n=this.dataSources.get(e);n&&this.dataSources.set(e,{...n,status:"loading"})}trackDataSourceLoaded(e,n,r){if(!this.config.enabled)return;const i=this.dataSources.get(e);if(!i)return;let l,u,d=r;n&&(Array.isArray(n)?(l=n.length,u=n.length>0&&typeof n[0]=="object"?Object.keys(n[0]):void 0):typeof n=="object"&&(Array.isArray(n.data)?(d=d||"data",l=n.data.length,u=n.data.length>0&&typeof n.data[0]=="object"?Object.keys(n.data[0]):void 0):Array.isArray(n.items)?(d=d||"items",l=n.items.length,u=n.items.length>0&&typeof n.items[0]=="object"?Object.keys(n.items[0]):void 0):u=Object.keys(n))),this.dataSources.set(e,{...i,status:"loaded",dataPath:d,itemCount:l,keys:u,lastLoadedAt:Date.now(),error:void 0})}trackDataSourceError(e,n){if(!this.config.enabled)return;const r=this.dataSources.get(e);r&&this.dataSources.set(e,{...r,status:"error",error:n,lastLoadedAt:Date.now()})}untrackDataSource(e){this.dataSources.delete(e)}getDataSources(){return Array.from(this.dataSources.values())}getDataSource(e){return this.dataSources.get(e)}clearDataSources(){this.dataSources.clear()}trackDataPathTransform(e){if(!this.config.enabled)return;let n=this.dataPathTransforms.find(r=>r.dataSourceId===e.dataSourceId);n||(n={dataSourceId:e.dataSourceId,timestamp:Date.now(),transformSteps:[],warnings:[]},this.dataPathTransforms.push(n),this.dataPathTransforms.length>this.maxDataPathTransforms&&this.dataPathTransforms.shift()),n.transformSteps.push({step:e.step,inputPath:e.inputPath,inputValue:this.safeClone(e.inputValue),outputPath:e.outputPath,outputValue:this.safeClone(e.outputValue),config:e.config}),e.warning&&n.warnings.push(e.warning)}setDataPathFinalBinding(e,n){if(!this.config.enabled)return;const r=this.dataPathTransforms.find(i=>i.dataSourceId===e);r&&(r.finalBinding={expression:n.expression,resolvedPath:n.resolvedPath,value:this.safeClone(n.value)})}getDataPathTransformTrackingInfo(){const e=this.getDataPathTransformStats();return{transforms:[...this.dataPathTransforms],stats:e,timestamp:Date.now()}}getDataPathTransformStats(){const e=this.dataPathTransforms,n={};let r=0;const i={};for(const u of e){n[u.dataSourceId]=(n[u.dataSourceId]||0)+1,r+=u.warnings.length;for(const d of u.warnings)i[d]=(i[d]||0)+1}const l=Object.entries(i).map(([u,d])=>({warning:u,count:d})).sort((u,d)=>d.count-u.count).slice(0,10);return{totalTransforms:e.length,byDataSource:n,warningsCount:r,commonWarnings:l}}getDataPathTransformForDataSource(e){return this.dataPathTransforms.find(n=>n.dataSourceId===e)}clearDataPathTransforms(){this.dataPathTransforms=[]}trackNestedContext(e){if(!this.config.enabled)return"";const n=`nested-${++this.nestedContextIdCounter}`,r=[...new Set([...e.parentContext.available,...e.ownContext.added])],i={...e.parentContext.values,...e.ownContext.values},l={id:n,timestamp:Date.now(),componentId:e.componentId,componentType:e.componentType,parentContext:{available:e.parentContext.available,values:this.safeClone(e.parentContext.values)},ownContext:{added:e.ownContext.added,values:this.safeClone(e.ownContext.values)},mergedContext:{all:r,values:this.safeClone(i)},accessAttempts:[],depth:e.depth,parentId:e.parentId};return this.nestedContexts.push(l),this.nestedContexts.length>this.maxNestedContexts&&this.nestedContexts.shift(),n}trackNestedContextAccess(e,n){if(!this.config.enabled)return;const r=this.nestedContexts.find(i=>i.id===e);r&&r.accessAttempts.push({path:n.path,found:n.found,value:n.found?this.safeClone(n.value):void 0,error:n.error})}getNestedContextTrackingInfo(){const e=this.getNestedContextStats();return{contexts:[...this.nestedContexts],stats:e,timestamp:Date.now()}}getNestedContextStats(){const e=this.nestedContexts,n={expandChildren:0,cellChildren:0,iteration:0,modal:0,slot:0};let r=0,i=0;const l={};for(const d of e){n[d.componentType]++,d.depth>r&&(r=d.depth);for(const f of d.accessAttempts)f.found||(i++,l[f.path]=(l[f.path]||0)+1)}const u=Object.entries(l).map(([d,f])=>({path:d,count:f})).sort((d,f)=>f.count-d.count).slice(0,10);return{totalContexts:e.length,byType:n,maxDepth:r,failedAccessCount:i,commonFailedPaths:u}}getNestedContextForComponent(e){return this.nestedContexts.find(n=>n.componentId===e)}clearNestedContexts(){this.nestedContexts=[],this.nestedContextIdCounter=0}trackHandlerRegistration(e,n="custom",r,i){this.isEnabled&&this.handlers.set(e,{name:e,category:n,description:r,registeredAt:Date.now(),source:i})}trackHandlerUnregistration(e){this.isEnabled&&this.handlers.delete(e)}getHandlers(){return Array.from(this.handlers.values())}getHandler(e){return this.handlers.get(e)}getHandlersByCategory(e){return Array.from(this.handlers.values()).filter(n=>n.category===e)}clearHandlers(){this.handlers.clear()}trackEventSubscribe(e){if(!this.isEnabled)return;const n=this.componentEventSubscriptions.get(e),r=Date.now();n?(n.subscriberCount++,n.lastSubscribedAt=r):this.componentEventSubscriptions.set(e,{eventName:e,subscriberCount:1,firstSubscribedAt:r,lastSubscribedAt:r})}trackEventUnsubscribe(e){if(!this.isEnabled)return;const n=this.componentEventSubscriptions.get(e);n&&(n.subscriberCount--,n.subscriberCount<=0&&this.componentEventSubscriptions.delete(e))}trackEventEmit(e,n,r,i,l){if(!this.isEnabled)return;const u={id:`evt_${++this.componentEventIdCounter}`,eventName:e,data:this.sanitizeForLogging(n),timestamp:Date.now(),listenerCount:r,results:i?this.sanitizeForLogging(i):void 0,hasError:!!l,errorMessage:l?.message};this.componentEventEmitHistory.push(u),this.componentEventEmitHistory.length>this.maxComponentEventHistory&&(this.componentEventEmitHistory=this.componentEventEmitHistory.slice(-this.maxComponentEventHistory))}trackEventOff(e){this.isEnabled&&this.componentEventSubscriptions.delete(e)}trackEventClear(){this.isEnabled&&this.componentEventSubscriptions.clear()}getComponentEventInfo(){const e=Array.from(this.componentEventSubscriptions.values());return{subscriptions:e,emitHistory:[...this.componentEventEmitHistory],totalSubscribers:e.reduce((n,r)=>n+r.subscriberCount,0),totalEmits:this.componentEventEmitHistory.length}}getEventEmitHistory(){return[...this.componentEventEmitHistory]}getEventSubscriptions(){return Array.from(this.componentEventSubscriptions.values())}clearComponentEvents(){this.componentEventSubscriptions.clear(),this.componentEventEmitHistory=[],this.componentEventIdCounter=0}sanitizeForLogging(e){if(e==null||typeof e!="object")return e;try{return JSON.parse(JSON.stringify(e))}catch{return"[Circular or Non-serializable]"}}startStateChange(e,n,r,i){if(!this.config.enabled)return"";const l=`setState_${++this.stateRenderingIdCounter}`;this.currentStateChangeContext={setStateId:l,startTime:performance.now(),changedPath:e,trigger:i||{},renderedComponents:[]};const u={id:`sr_${this.stateRenderingIdCounter}`,setStateId:l,statePath:e,oldValue:this.sanitizeForLogging(n),newValue:this.sanitizeForLogging(r),timestamp:Date.now(),triggeredBy:i||{},renderedComponents:[],totalRenderDuration:0,affectedBindingsCount:0};return this.stateRenderingLogs.push(u),this.stateRenderingLogs.length>this.maxStateRenderingLogs&&this.stateRenderingLogs.shift(),l}trackComponentRender(e,n,r,i=[],l=[],u){if(!this.config.enabled)return;const d=this.componentRenderCounts.get(n)||0;this.componentRenderCounts.set(n,d+1);for(const f of i)this.stateToComponentMap.has(f)||this.stateToComponentMap.set(f,new Set),this.stateToComponentMap.get(f).add(n);if(this.currentStateChangeContext){const f={componentId:e,componentName:n,renderDuration:r,accessedStatePaths:i,evaluatedBindings:l,renderOrder:this.currentStateChangeContext.renderedComponents.length,parentId:u};this.currentStateChangeContext.renderedComponents.push(f)}this.trackRender(n)}completeStateChange(e){if(!this.config.enabled||!this.currentStateChangeContext||this.currentStateChangeContext.setStateId!==e)return;const n=this.currentStateChangeContext,i=performance.now()-n.startTime,l=this.stateRenderingLogs.findIndex(u=>u.setStateId===e);if(l>=0){const u=this.stateRenderingLogs[l];u.renderedComponents=n.renderedComponents,u.totalRenderDuration=i,u.affectedBindingsCount=n.renderedComponents.reduce((d,f)=>d+f.evaluatedBindings.length,0)}this.currentStateChangeContext=null}getCurrentStateChangeContext(){return this.currentStateChangeContext}getStateRenderingLogs(){return[...this.stateRenderingLogs]}getStateRenderingInfo(){const e=this.stateRenderingLogs,n=Object.fromEntries(this.componentRenderCounts),r={};for(const[i,l]of this.stateToComponentMap)r[i]=Array.from(l);return{logs:e,componentRenderCounts:n,stateToComponentMap:r,stats:this.calculateStateRenderingStats()}}calculateStateRenderingStats(){const e=this.stateRenderingLogs;if(e.length===0)return{totalStateChanges:0,totalRenders:0,avgRenderDuration:0,avgComponentsPerChange:0,topRenderedComponents:[],topInfluentialPaths:[]};const n=e.reduce((d,f)=>d+f.renderedComponents.length,0),r=e.reduce((d,f)=>d+f.totalRenderDuration,0)/e.length,i=n/e.length,l=Array.from(this.componentRenderCounts.entries()).sort((d,f)=>f[1]-d[1]).slice(0,5).map(([d,f])=>({name:d,count:f})),u=Array.from(this.stateToComponentMap.entries()).sort((d,f)=>f[1].size-d[1].size).slice(0,5).map(([d,f])=>({path:d,affectedComponents:f.size}));return{totalStateChanges:e.length,totalRenders:n,avgRenderDuration:r,avgComponentsPerChange:i,topRenderedComponents:l,topInfluentialPaths:u}}getComponentsAffectedByState(e){const n=this.stateToComponentMap.get(e);return n?Array.from(n):[]}getComponentRenderHistory(e){return this.stateRenderingLogs.filter(n=>n.renderedComponents.some(r=>r.componentName===e))}clearStateRenderingLogs(){this.stateRenderingLogs=[],this.componentRenderCounts.clear(),this.stateToComponentMap.clear(),this.currentStateChangeContext=null,this.stateRenderingIdCounter=0}trackComponentStateSource(e,n,r,i){this.config.enabled&&this.componentStateSources.set(e,{componentId:e,componentName:n,stateSource:r,stateProvider:i})}trackDynamicState(e,n){this.config.enabled&&this.dynamicStates.set(e,n)}trackContextFlow(e,n,r,i,l,u){if(!this.config.enabled)return;const d={component:n,componentId:e,contextReceived:r,passedToChildren:i,usedInRender:l};if(this.contextFlowNodes.set(e,d),u){const f=this.contextFlowNodes.get(u);f&&(f.children||(f.children=[]),f.children.push(d))}}getStateHierarchyInfo(e=!0){const n=this.buildStateHierarchyLayers(),r=this.detectStateConflicts(n),i=Array.from(this.componentStateSources.values());return{layers:e?n.map(u=>({...u,values:this.summarizeValues(u.values,2)})):n,conflicts:r,componentStateSources:i,timestamp:Date.now()}}summarizeValues(e,n,r=0){if(e==null)return e;if(typeof e!="object")return typeof e=="string"&&e.length>100?e.substring(0,100)+`... (${e.length}자)`:e;if(r>=n){if(Array.isArray(e))return`[Array(${e.length})]`;const u=Object.keys(e);return`{${u.slice(0,5).join(", ")}${u.length>5?`, ... +${u.length-5}`:""}}`}if(Array.isArray(e))return e.length<=3?e.map(u=>this.summarizeValues(u,n,r+1)):{__type:"array",__length:e.length,__preview:e.slice(0,3).map(u=>this.summarizeValues(u,n,r+1))};const i={},l=Object.keys(e);for(const u of l)i[u]=this.summarizeValues(e[u],n,r+1);return i}buildStateHierarchyLayers(){const e=[];try{const r=window.G7Core?.state?.get?.();if(!r)return e;r._local&&e.push({name:"Global _local",type:"global",path:"_local",values:r._local,priority:1}),r._global&&e.push({name:"Global _global",type:"global",path:"_global",values:r._global,priority:1});for(const[l,u]of this.dynamicStates)u&&Object.keys(u).length>0&&e.push({name:`DynamicState (${l})`,type:"dynamicState",componentId:l,values:u,priority:2});const i=this.computeEffectiveState(r._local||{});e.push({name:"Effective _local (merged)",type:"effective",values:i,priority:3})}catch(n){console.warn("[G7DevTools] 상태 계층 빌드 실패:",n)}return e}computeEffectiveState(e){const n={...e};for(const[,r]of this.dynamicStates)r._local&&Object.assign(n,r._local);return n}detectStateConflicts(e){const n=[],r=e.find(l=>l.type==="global"&&l.path==="_local");if(!r)return n;const i=e.filter(l=>l.type==="dynamicState");for(const l of i){const u=l.values._local||l.values;for(const[d,f]of Object.entries(u)){const g=r.values[d];if(JSON.stringify(g)!==JSON.stringify(f)){const m=[],b=[];for(const v of this.componentStateSources.values())v.stateSource.local.some(_=>_===`_local.${d}`||_===d)&&(v.stateProvider.type==="dynamicState"?m.push(v.componentName):v.stateProvider.type==="globalState"&&b.push(v.componentName));n.push({path:`_local.${d}`,globalValue:g,dynamicStateValue:f,effectiveValue:f,usedBy:m,notUsedBy:b,severity:b.length>0?"warning":"info",description:b.length>0?`${b.join(", ")}은(는) globalState._local을 읽어 dynamicState 값을 사용하지 못함`:"dynamicState 값이 globalState와 다르지만 모든 컴포넌트가 dynamicState를 사용"})}}}return n}getContextFlowInfo(){const e=[],n=new Set(this.contextFlowNodes.keys());for(const r of this.contextFlowNodes.values())if(r.children)for(const i of r.children)n.delete(i.componentId);for(const r of n){const i=this.contextFlowNodes.get(r);i&&e.push(i)}return{rootComponent:e.length>0?e[0].component:"Unknown",contextFlow:e,timestamp:Date.now()}}clearStateHierarchyData(){this.componentStateSources.clear(),this.contextFlowNodes.clear(),this.dynamicStates.clear()}trackComponentStyle(e,n,r,i){if(!this.config.enabled)return;const l=this.analyzeTailwindClasses(r),u={componentId:e,componentName:n,classes:r,computedStyles:i,tailwindAnalysis:l};this.componentStyles.set(e,u),this.detectStyleIssues(u)}analyzeTailwindClasses(e){const n=[],r=[],i=[],l=[],u=["sm:","md:","lg:","xl:","2xl:"],d=[/bg-\w+-\d+/,/text-\w+-\d+/,/border-\w+-\d+/];for(const f of e){l.push(f),f.startsWith("dark:")&&n.push(f);for(const g of u)if(f.startsWith(g)){r.push(f);break}for(const g of d)if(g.test(f)){i.push(f);break}}return{usedClasses:l,darkClasses:n,responsiveClasses:r,dynamicClasses:i}}detectStyleIssues(e){const{componentId:n,componentName:r,computedStyles:i,tailwindAnalysis:l}=e;(i.opacity==="0"||i.visibility==="hidden"||i.display==="none"||i.width==="0px"&&i.height==="0px")&&this.addStyleIssue({id:this.generateId(),type:"invisible-element",componentId:n,componentName:r,property:i.opacity==="0"?"opacity":i.visibility==="hidden"?"visibility":i.display==="none"?"display":"width/height",currentValue:i.opacity==="0"?"0":i.visibility==="hidden"?"hidden":i.display==="none"?"none":"0px",severity:"warning",description:"요소가 화면에 보이지 않습니다.",suggestion:"opacity, visibility, display, width/height 값을 확인하세요."});const u=l.usedClasses.filter(f=>f.startsWith("bg-")&&!f.startsWith("dark:")),d=l.darkClasses.filter(f=>f.includes("bg-"));u.length>0&&d.length===0&&this.addStyleIssue({id:this.generateId(),type:"dark-mode-missing",componentId:n,componentName:r,property:"background-color",currentValue:u.join(", "),expectedValue:"dark:bg-* 클래스 필요",severity:"info",description:"다크 모드 배경색 클래스가 누락되었습니다.",suggestion:`${u[0]}에 대응하는 dark: 클래스를 추가하세요.`}),l.dynamicClasses.length>0&&this.addStyleIssue({id:this.generateId(),type:"tailwind-purging",componentId:n,componentName:r,property:"class",currentValue:l.dynamicClasses.join(", "),severity:"info",description:"동적으로 생성된 Tailwind 클래스가 있습니다.",suggestion:"tailwind.config.js의 safelist에 추가하거나 전체 클래스명을 상수로 정의하세요."})}addStyleIssue(e){this.styleIssues.some(r=>r.componentId===e.componentId&&r.type===e.type&&r.property===e.property)||this.styleIssues.push(e)}getStyleValidationInfo(){const e=Array.from(this.componentStyles.values());return{issues:[...this.styleIssues],componentStyles:e,stats:{totalComponents:e.length,invisibleCount:this.styleIssues.filter(n=>n.type==="invisible-element").length,tailwindIssueCount:this.styleIssues.filter(n=>n.type==="tailwind-purging").length,darkModeIssueCount:this.styleIssues.filter(n=>n.type==="dark-mode-missing").length},timestamp:Date.now()}}clearStyleValidationData(){this.styleIssues=[],this.componentStyles.clear()}trackAuthEvent(e,n,r,i){if(!this.config.enabled)return;const l={id:`auth_${++this.authEventIdCounter}`,type:e,timestamp:Date.now(),success:n,error:r,details:i};this.authEvents.push(l),this.authEvents.length>this.maxAuthEventHistory&&(this.authEvents=this.authEvents.slice(-this.maxAuthEventHistory))}trackAuthHeader(e,n,r,i,l){if(!this.config.enabled)return;const u={url:e,hasAuthHeader:n,headerType:r,tokenValid:i??!1,responseStatus:l,timestamp:Date.now()};this.authHeaderHistory.push(u),this.authHeaderHistory.length>this.maxAuthEventHistory&&(this.authHeaderHistory=this.authHeaderHistory.slice(-this.maxAuthEventHistory)),l===401&&this.trackAuthEvent("api-unauthorized",!1,`401 Unauthorized: ${e}`,{url:e})}getAuthState(){try{const e=window.G7Core,n=e?.api;let r=e?.auth;!r&&e?.AuthManager?.getInstance&&(r=e.AuthManager.getInstance());const i=n?.getToken?.()||r?.getAccessToken?.()||localStorage.getItem("auth_token")||localStorage.getItem("access_token"),l=r?.getRefreshToken?.()||localStorage.getItem("refresh_token");let u="unknown",d=r?.getUser?.();if(d&&(u="AuthManager"),!d){const S=e?.state?.get?.();d=S?._global?.user||S?._global?.currentUser||S?.user||S?.currentUser,d&&(u="G7Core.state")}const f=r?.isAuthenticated?.()??!1;let g="memory";localStorage.getItem("auth_token")||localStorage.getItem("access_token")?g="localStorage":(sessionStorage.getItem("auth_token")||sessionStorage.getItem("access_token"))&&(g="sessionStorage");const m=!!i&&(!!d||f);let b;i&&typeof i=="string"&&i.length>20?b=`${i.substring(0,10)}...${i.substring(i.length-6)}`:i&&(b="***");const v=d?{id:d.id,email:d.email,name:d.name,roles:d.roles?.map(S=>typeof S=="string"?{name:S}:{id:S.id,name:S.name,guard_name:S.guard_name}),permissions:d.permissions?.map(S=>typeof S=="string"?{name:S}:{id:S.id,name:S.name,guard_name:S.guard_name}),avatar:d.avatar||d.profile_photo_url||d.profile_image,created_at:d.created_at,updated_at:d.updated_at,last_login_at:d.last_login_at,email_verified_at:d.email_verified_at,...d.phone&&{phone:d.phone},...d.nickname&&{nickname:d.nickname},...d.status&&{status:d.status},...d.locale&&{locale:d.locale}}:void 0;return{isAuthenticated:m,user:v,tokens:{hasAccessToken:!!i,hasRefreshToken:!!l,storage:g,accessTokenPreview:b},lastActivity:Date.now(),source:u}}catch{return{isAuthenticated:!1,tokens:{hasAccessToken:!1,hasRefreshToken:!1,storage:"memory"},source:"unknown"}}}getAuthDebugInfo(){const e=[...this.authEvents];return{state:this.getAuthState(),events:e,headerAnalysis:[...this.authHeaderHistory],stats:{loginAttempts:e.filter(n=>n.type==="login").length,successfulLogins:e.filter(n=>n.type==="login"&&n.success).length,failedLogins:e.filter(n=>n.type==="login"&&!n.success).length,tokenRefreshes:e.filter(n=>n.type==="token-refresh").length,unauthorizedResponses:e.filter(n=>n.type==="api-unauthorized").length},timestamp:Date.now()}}clearAuthData(){this.authEvents=[],this.authHeaderHistory=[],this.authEventIdCounter=0}trackLayoutLoad(e,n,r,i="api"){if(!this.config.enabled)return;const l=Date.now();this.currentLayout={layoutPath:e,templateId:n,layoutJson:this.sanitizeObject(r),loadedAt:l,version:r.version,layoutName:r.layout_name,source:i};const u={id:`layout-${++this.layoutIdCounter}`,layoutPath:e,templateId:n,loadedAt:l,source:i,version:r.version};this.layoutHistory.push(u),this.layoutHistory.length>this.maxLayoutHistory&&this.layoutHistory.shift(),this.layoutStats.totalLoads++,i==="cache"?this.layoutStats.cacheHits++:this.layoutStats.apiLoads++}getCurrentLayout(){return this.currentLayout}getLayoutHistory(){return[...this.layoutHistory]}getLayoutDebugInfo(){return{current:this.currentLayout,history:[...this.layoutHistory],stats:{...this.layoutStats}}}clearLayoutData(){this.currentLayout=null,this.layoutHistory=[],this.layoutIdCounter=0,this.layoutStats={totalLoads:0,cacheHits:0,apiLoads:0}}startHandlerExecution(e){if(!this.config.enabled)return"";const n=`exec_${++this.executionIdCounter}_${Date.now()}`,r={handlerName:e,executionId:n,startTime:Date.now(),stateChanges:[],dataSourceChanges:[],alerts:[]};if(this.executionDetails.set(n,r),this.executionDetails.size>this.maxExecutionDetails){const i=Array.from(this.executionDetails.keys());i.slice(0,i.length-this.maxExecutionDetails).forEach(u=>this.executionDetails.delete(u))}return n}endHandlerExecution(e,n,r,i){if(!this.config.enabled||!e)return;const l=this.executionDetails.get(e);if(!l)return;l.endTime=Date.now(),l.duration=l.endTime-l.startTime,l.exitReason=n,l.exitLocation=r,l.exitDescription=i;const u=this.changeExpectations.get(e);u&&(l.expectedChanges=u,this.checkExpectations(e,l,u),this.changeExpectations.delete(e)),n==="normal"&&l.stateChanges.length===0&&l.dataSourceChanges.length===0&&this.addChangeAlert(e,{type:"no-state-change",severity:"warning",message:`핸들러 "${l.handlerName}"이(가) 상태 변경 없이 완료됨`,description:"핸들러가 성공적으로 완료되었지만 상태나 데이터소스 변경이 없습니다. 의도한 동작인지 확인하세요.",handlerName:l.handlerName,suggestion:'핸들러 내부 조건문을 확인하거나 DevTools의 "변경감지" 탭에서 exitLocation을 확인하세요.',docLink:"troubleshooting-state.md"}),(n==="early-return-condition"||n==="early-return-validation")&&this.addChangeAlert(e,{type:"early-return-detected",severity:"info",message:`핸들러 "${l.handlerName}"이(가) early return으로 종료됨`,description:i||`종료 위치: ${r||"알 수 없음"}`,handlerName:l.handlerName,suggestion:n==="early-return-validation"?"검증 실패로 인한 early return입니다. 입력 데이터를 확인하세요.":"조건부 early return입니다. 조건문의 평가 결과를 확인하세요."})}recordExitReason(e,n,r,i){if(!this.config.enabled||!e)return;const l=this.executionDetails.get(e);l&&(l.exitReason=n,l.exitLocation=r,l.exitDescription=i)}recordStateChange(e,n,r,i,l){if(!this.config.enabled)return;const u={id:`sc_${++this.stateChangeIdCounter}`,path:n,changeType:r,oldValue:this.safeClone(i),newValue:this.safeClone(l),timestamp:Date.now(),comparison:this.compareValues(i,l),executionId:e};if(this.stateChangeHistory.push(u),e){const d=this.executionDetails.get(e);d&&d.stateChanges.push(u)}this.stateChangeHistory.length>this.maxStateChangeHistory&&this.stateChangeHistory.splice(0,this.stateChangeHistory.length-this.maxStateChangeHistory),u.comparison.isDeepEqual&&typeof i=="object"&&i!==null&&this.addChangeAlert(e||"",{type:"object-reference-same",severity:"warning",message:`상태 "${n}"가 변경되었으나 값이 동일함`,description:"객체 참조가 동일하거나 깊은 비교 결과 변경이 없습니다. 변경 감지가 실패할 수 있습니다.",handlerName:e&&this.executionDetails.get(e)?.handlerName||"unknown",statePath:n,suggestion:"불변성을 유지하여 새 객체를 생성하세요. 예: { ...oldObject, newField: value }",docLink:"troubleshooting-state.md#object-mutation"})}recordDataSourceChange(e,n,r,i,l){if(!this.config.enabled)return;const u={dataSourceId:n,changeType:r,timestamp:Date.now(),previousStatus:i,newStatus:l,executionId:e};if(this.dataSourceChangeHistory.push(u),e){const d=this.executionDetails.get(e);d&&d.dataSourceChanges.push(u)}this.dataSourceChangeHistory.length>this.maxStateChangeHistory&&this.dataSourceChangeHistory.splice(0,this.dataSourceChangeHistory.length-this.maxStateChangeHistory)}expectChange(e,n,r){if(!this.config.enabled||!e)return;const i=this.executionDetails.get(e);if(!i)return;const l={expectedStatePaths:n,expectedDataSources:r,setAt:Date.now(),source:i.handlerName};this.changeExpectations.set(e,l)}checkExpectations(e,n,r){const i=new Set(n.stateChanges.map(u=>u.path)),l=new Set(n.dataSourceChanges.map(u=>u.dataSourceId));for(const u of r.expectedStatePaths)i.has(u)||this.addChangeAlert(e,{type:"expected-not-fulfilled",severity:"error",message:`기대한 상태 변경 "${u}"가 발생하지 않음`,description:`핸들러 "${n.handlerName}"이(가) "${u}" 변경을 예고했지만 실제로 변경되지 않았습니다.`,handlerName:n.handlerName,statePath:u,suggestion:"핸들러 내부 로직을 확인하세요. early return이나 조건부 분기로 인해 변경이 생략되었을 수 있습니다.",docLink:"troubleshooting-state.md"});for(const u of r.expectedDataSources)l.has(u)||this.addChangeAlert(e,{type:"expected-not-fulfilled",severity:"error",message:`기대한 데이터소스 갱신 "${u}"가 발생하지 않음`,description:`핸들러 "${n.handlerName}"이(가) "${u}" 갱신을 예고했지만 실제로 갱신되지 않았습니다.`,handlerName:n.handlerName,dataSourceId:u,suggestion:"refetchDataSource 호출이 실행되었는지 확인하세요.",docLink:"data-sources.md"})}addChangeAlert(e,n){const r={...n,id:`alert_${++this.alertIdCounter}`,timestamp:Date.now()};if(this.changeAlerts.push(r),e){const i=this.executionDetails.get(e);i&&i.alerts.push(r)}this.changeAlerts.length>this.maxChangeAlerts&&this.changeAlerts.splice(0,this.changeAlerts.length-this.maxChangeAlerts)}compareValues(e,n){const r=this.getValueType(e),i=this.getValueType(n),l=r!==i;let u=!1,d;return!l&&(r==="object"||r==="array")?(u=this.deepEqual(e,n),!u&&r==="object"&&(d=this.getChangedKeys(e,n))):u=e===n,{typeChanged:l,oldType:r,newType:i,isDeepEqual:u,changedKeys:d}}getValueType(e){return e===null?"null":e===void 0?"undefined":Array.isArray(e)?"array":typeof e}deepEqual(e,n){if(e===n)return!0;if(typeof e!=typeof n)return!1;if(e===null||n===null||typeof e!="object")return e===n;if(Array.isArray(e)!==Array.isArray(n))return!1;const r=Object.keys(e),i=Object.keys(n);if(r.length!==i.length)return!1;for(const l of r)if(!i.includes(l)||!this.deepEqual(e[l],n[l]))return!1;return!0}getChangedKeys(e,n){const r=[],i=new Set([...Object.keys(e),...Object.keys(n)]);for(const l of i)this.deepEqual(e[l],n[l])||r.push(l);return r}getChangeDetectionInfo(){const e=Array.from(this.executionDetails.values()),n={totalExecutions:e.length,executionsWithStateChange:e.filter(r=>r.stateChanges.length>0).length,executionsWithoutStateChange:e.filter(r=>r.stateChanges.length===0&&r.exitReason==="normal").length,earlyReturnCount:e.filter(r=>r.exitReason==="early-return-condition"||r.exitReason==="early-return-validation").length,alertCount:this.changeAlerts.length,alertsByType:this.getAlertsByType()};return{executionDetails:e,stateChangeHistory:[...this.stateChangeHistory],dataSourceChangeHistory:[...this.dataSourceChangeHistory],alerts:[...this.changeAlerts],stats:n,timestamp:Date.now()}}getAlertsByType(){const e={"no-state-change":0,"no-datasource-change":0,"expected-not-fulfilled":0,"object-reference-same":0,"early-return-detected":0,"async-timing-issue":0};for(const n of this.changeAlerts)e[n.type]++;return e}clearChangeDetectionData(){this.executionDetails.clear(),this.stateChangeHistory=[],this.dataSourceChangeHistory=[],this.changeAlerts=[],this.changeExpectations.clear(),this.executionIdCounter=0,this.stateChangeIdCounter=0,this.alertIdCounter=0}getRecentAlerts(e=10,n){let r=[...this.changeAlerts];return n&&(r=r.filter(i=>i.severity===n)),r.slice(-e)}getHandlerExecutions(e,n=10){return Array.from(this.executionDetails.values()).filter(i=>i.handlerName===e).slice(-n)}findExecutionInStack(e){return this.sequenceExecutionStack.find(n=>n.sequenceId===e)}startSequenceExecution(e){if(!this.config.enabled)return"";const n=`seq_${++this.sequenceIdCounter}_${Date.now()}`,r={sequenceId:n,startTime:Date.now(),totalDuration:0,trigger:e,actions:[],status:"running"};return this.sequenceExecutionStack.push(r),n}captureSequenceActionBefore(e,n,r,i,l){if(!this.config.enabled)return;const u=this.findExecutionInStack(e);if(!u)return;const d={index:n,handler:r,params:this.safeClone(i),stateBeforeAction:{_global:this.safeClone(l._global),_local:this.safeClone(l._local),_isolated:l._isolated?this.safeClone(l._isolated):void 0},stateAfterAction:{_global:{},_local:{}},duration:0,status:"success"};u.actions.push(d)}captureSequenceActionAfter(e,n,r,i,l,u){if(!this.config.enabled)return;const d=this.findExecutionInStack(e);if(!d)return;const f=d.actions.find(m=>m.index===n);if(!f)return;f.stateAfterAction={_global:this.safeClone(r._global),_local:this.safeClone(r._local),_isolated:r._isolated?this.safeClone(r._isolated):void 0},f.duration=i,f.result=this.safeClone(l),f.stateDiff={global:this.computeStateDiff(f.stateBeforeAction._global,f.stateAfterAction._global),local:this.computeStateDiff(f.stateBeforeAction._local,f.stateAfterAction._local)},f.stateBeforeAction._isolated&&f.stateAfterAction._isolated&&(f.stateDiff.isolated=this.computeStateDiff(f.stateBeforeAction._isolated,f.stateAfterAction._isolated));const g=window.__g7PendingLocalState;g&&(f.pendingState=this.safeClone(g)),u&&(f.status="error",f.error={name:u.name,message:u.message,stack:u.stack})}endSequenceExecution(e,n){if(!this.config.enabled)return;const r=this.sequenceExecutionStack.findIndex(l=>l.sequenceId===e);if(r===-1)return;const i=this.sequenceExecutionStack[r];if(i.endTime=Date.now(),i.totalDuration=i.endTime-i.startTime,n){i.status="error",i.error={name:n.name,message:n.message,stack:n.stack};const l=i.actions.find(u=>u.status==="error");l&&(i.failedAtIndex=l.index)}else i.status="success";this.sequenceExecutions.push(i),this.sequenceExecutions.length>this.maxSequenceExecutions&&this.sequenceExecutions.shift(),this.sequenceExecutionStack.splice(r,1)}computeStateDiff(e,n){const r=[],i=[],l=[],u=new Set(Object.keys(e)),d=new Set(Object.keys(n));for(const f of d)u.has(f)||r.push(f);for(const f of u)d.has(f)||i.push(f);for(const f of u)if(d.has(f)){const g=e[f],m=n[f];JSON.stringify(g)!==JSON.stringify(m)&&l.push({path:f,oldValue:g,newValue:m})}return{added:r,removed:i,changed:l}}getSequenceTrackingInfo(){const e=this.getSequenceStats(),n=this.sequenceExecutionStack.length>0?this.sequenceExecutionStack[this.sequenceExecutionStack.length-1]:void 0;return{executions:[...this.sequenceExecutions],currentExecution:n,stats:e}}getSequenceStats(){const e=this.sequenceExecutions,n=e.length,r=e.filter(g=>g.status==="success").length,i=e.filter(g=>g.status==="error").length,l=e.reduce((g,m)=>g+m.actions.length,0),u=n>0?e.reduce((g,m)=>g+m.totalDuration,0)/n:0,d={};for(const g of e)for(const m of g.actions)d[m.handler]=(d[m.handler]||0)+1;const f=Object.entries(d).sort(([,g],[,m])=>m-g).slice(0,5).map(([g,m])=>({handler:g,count:m}));return{totalExecutions:n,successCount:r,errorCount:i,totalActions:l,avgDuration:u,topHandlers:f}}clearSequenceData(){this.sequenceExecutions=[],this.sequenceExecutionStack=[],this.sequenceIdCounter=0}getSequenceExecution(e){const n=this.findExecutionInStack(e);return n||this.sequenceExecutions.find(r=>r.sequenceId===e)}getRecentSequences(e=10){return this.sequenceExecutions.slice(-e)}registerStateCaptureForHandler(e,n,r){if(!this.config.enabled)return;const i=new Map,l=Date.now();for(const u of n)i.set(u,{value:this.safeClone(r[u]),capturedAt:l});this.stateCaptureRegistry.set(e,i)}detectStaleClosure(e,n,r,i,l){if(!this.config.enabled)return[];const u=this.stateCaptureRegistry.get(e);if(!u)return[];const d=Date.now(),f=[];for(const[g,m]of u){const b=this.getValueByPath(r,g),v=d-m.capturedAt;if(!this.isDeepEqual(m.value,b)&&v>0){const S=this.createStaleClosureWarning(i,n,g,m.value,m.capturedAt,b,d,v,l);f.push(S),this.addStaleClosureWarning(S)}}return this.stateCaptureRegistry.delete(e),f}trackStaleClosureWarning(e){if(!this.config.enabled)return;const n=Date.now(),r=this.createStaleClosureWarning(e.type,e.location,e.capturedPath,e.capturedValue,e.capturedAt,e.currentValue,n,n-e.capturedAt,e.actionId,e.stackTrace);this.addStaleClosureWarning(r)}createStaleClosureWarning(e,n,r,i,l,u,d,f,g,m){const b=this.getStaleClosureSeverity(e,f),{description:v,suggestion:S,docLink:_}=this.getStaleClosureMessages(e,r,f);return{id:`stale_${++this.staleClosureIdCounter}_${Date.now()}`,timestamp:Date.now(),type:e,location:n,capturedState:{path:r,capturedValue:this.safeClone(i),capturedAt:l},currentState:{path:r,currentValue:this.safeClone(u),retrievedAt:d},timeDiff:f,severity:b,description:v,suggestion:S,docLink:_,actionId:g,stackTrace:m}}getStaleClosureSeverity(e,n){if(n>5e3)return"error";if(n>1e3)return"warning";switch(e){case"async-state-capture":case"sequence-state-mismatch":return"warning";case"callback-state-capture":case"timeout-state-capture":return"info";case"event-handler-stale":return"warning";default:return"info"}}getStaleClosureMessages(e,n,r){const i=r<1e3?`${r}ms`:`${(r/1e3).toFixed(1)}s`;switch(e){case"async-state-capture":return{description:`await 후 ${i} 경과 시점에 '${n}' 상태가 변경됨. 캡처된 상태 대신 최신 상태를 사용해야 함`,suggestion:"await 이후에는 G7Core.state.get()으로 최신 상태를 다시 조회하거나, useRef + getter 패턴을 사용하세요",docLink:"troubleshooting-state-closure.md"};case"callback-state-capture":return{description:`콜백에서 ${i} 전에 캡처된 '${n}' 상태를 사용 중. 최신 상태와 다름`,suggestion:"콜백에서 상태를 참조할 때는 stateRef.current 패턴 또는 G7Core.state.get()를 사용하세요",docLink:"troubleshooting-state-closure.md"};case"timeout-state-capture":return{description:`setTimeout/setInterval 콜백에서 '${n}' 상태가 ${i} 전 값 사용 중`,suggestion:"타이머 콜백 내에서는 G7Core.state.get()으로 최신 상태를 조회하세요",docLink:"troubleshooting-state-closure.md"};case"sequence-state-mismatch":return{description:`sequence 내 '${n}' 상태가 이전 액션 결과와 불일치. context.state 대신 캡처된 값 사용 의심`,suggestion:"sequence 내에서는 context.state 또는 $prev를 사용하여 최신 상태를 참조하세요",docLink:"troubleshooting-state-setstate.md"};case"event-handler-stale":return{description:`이벤트 핸들러에서 ${i} 전에 바인딩된 '${n}' 상태 사용 중`,suggestion:"이벤트 핸들러에서 상태를 참조할 때는 useRef 패턴 또는 G7Core.state.get()를 사용하세요",docLink:"troubleshooting-state-closure.md"};default:return{description:`'${n}' 상태에서 stale closure 감지됨 (${i} 경과)`,suggestion:"상태 참조 시 최신 값을 사용하는지 확인하세요"}}}addStaleClosureWarning(e){this.staleClosureWarnings.push(e),this.staleClosureWarnings.length>this.maxStaleClosureWarnings&&this.staleClosureWarnings.shift()}getValueByPath(e,n){const r=n.split(".");let i=e;for(const l of r){if(i==null)return;i=i[l]}return i}isDeepEqual(e,n){if(e===n)return!0;if(e===null||n===null)return e===n;if(typeof e!=typeof n)return!1;if(typeof e!="object")return e===n;try{return JSON.stringify(e)===JSON.stringify(n)}catch{return!1}}getStaleClosureTrackingInfo(){const e=this.getStaleClosureStats();return{warnings:[...this.staleClosureWarnings],stats:e,timestamp:Date.now()}}getStaleClosureStats(){const e=this.staleClosureWarnings,n={"async-state-capture":0,"callback-state-capture":0,"timeout-state-capture":0,"sequence-state-mismatch":0,"event-handler-stale":0};for(const f of e)n[f.type]++;const r={info:0,warning:0,error:0};for(const f of e)r[f.severity]++;const i={};for(const f of e)i[f.location]=(i[f.location]||0)+1;const l=Object.entries(i).sort(([,f],[,g])=>g-f).slice(0,5).map(([f,g])=>({location:f,count:g})),u={};for(const f of e)u[f.capturedState.path]=(u[f.capturedState.path]||0)+1;const d=Object.entries(u).sort(([,f],[,g])=>g-f).slice(0,5).map(([f,g])=>({path:f,count:g}));return{totalWarnings:e.length,warningsByType:n,warningsBySeverity:r,topLocations:l,topAffectedPaths:d}}clearStaleClosureData(){this.staleClosureWarnings=[],this.staleClosureIdCounter=0,this.stateCaptureRegistry.clear()}getRecentStaleClosureWarnings(e=10,n){let r=[...this.staleClosureWarnings];return n&&(r=r.filter(i=>i.severity===n)),r.slice(-e)}safeClone(e){if(e==null||typeof e!="object")return e;try{return JSON.parse(JSON.stringify(e))}catch{if(Array.isArray(e))return e.map(r=>{try{return JSON.parse(JSON.stringify(r))}catch{return"[Unserializable]"}});const n={};for(const r of Object.keys(e))try{n[r]=JSON.parse(JSON.stringify(e[r]))}catch{n[r]="[Unserializable]"}return n}}};$(bi,"instance");let Tr=bi;const Gn=dt("LayoutLoader");class va extends Error{constructor(n,r,i){super(n);$(this,"code");$(this,"details");this.code=r,this.details=i,this.name="LayoutLoaderError"}}class sf{constructor(e){$(this,"componentRegistry");$(this,"currentLayout",null);$(this,"layoutCache",new Map);$(this,"cacheVersion",0);this.componentRegistry=e}setCacheVersion(e){this.cacheVersion!==e&&(Gn.log("Cache version updated:",this.cacheVersion,"->",e),this.cacheVersion=e,this.layoutCache.clear())}getCacheVersion(){return this.cacheVersion}async loadLayout(e,n){const r=`${e}:${n}`;if(this.layoutCache.has(r)){Gn.log("Loading layout from cache:",n);const l=await this.layoutCache.get(r),u=JSON.parse(JSON.stringify(l));return this.currentLayout=u,Tr.getInstance().trackLayoutLoad(n,e,u,"cache"),u}const i=this.fetchLayout(e,n);return this.layoutCache.set(r,i),i.catch(()=>{this.layoutCache.get(r)===i&&this.layoutCache.delete(r)}),i}async fetchLayout(e,n,r=!1){try{const i=this.cacheVersion>0?this.cacheVersion:null;let l;if(n.startsWith("__preview__/")){const v=n.replace("__preview__/","");l=Ma(`/api/layouts/preview/${v}`,"json",i)}else l=Ma(`/api/layouts/${e}/${n}`,"json",i);Gn.log("Fetching layout from API:",l);const u=Ia(),d=r?null:u.getToken(),f={Accept:"application/json"};d&&(f.Authorization=`Bearer ${d}`);const g=await Dl(l,{init:{headers:f},label:`layout: ${n}`});let m;try{m=await g.json()}catch{m=null}if(!g.ok){if(g.status===401&&!r&&d){Gn.log("Token invalid, removing and retrying without token"),u.removeToken();try{return await this.fetchLayout(e,n,!0)}catch(S){throw S instanceof va&&S.details?.status===401?new va(S.message,S.code,{...S.details,hadToken:!0}):S}}const v=m?.message||m?.error;throw new va(`Failed to fetch layout: ${g.status} ${g.statusText}`,"FETCH_FAILED",{status:g.status,statusText:g.statusText,url:l,apiMessage:v})}const b=m.data||m;return this.validateLayoutData(b),this.currentLayout=b,Tr.getInstance().trackLayoutLoad(n,e,b,"api"),Gn.log("Layout fetched and cached successfully:",b.layout_name),b}catch(i){const l=`${e}:${n}`;throw this.layoutCache.delete(l),i instanceof va?i:new va("Failed to load layout","LOAD_FAILED",{originalError:i})}}prefetchLayout(e,n){return this.loadLayout(e,n)}validateLayoutData(e){if(!e.version)throw new va("Layout data missing required field: version","VALIDATION_FAILED",{field:"version"});if(!e.layout_name)throw new va("Layout data missing required field: layout_name","VALIDATION_FAILED",{field:"layout_name"});if(!Array.isArray(e.components))throw new va('Layout data field "components" must be an array',"VALIDATION_FAILED",{field:"components",value:e.components});Gn.log("Layout data validation passed")}renderLayout(e,n){try{const r=n||this.currentLayout;if(!r)throw new va("No layout data to render","NO_LAYOUT_DATA");Gn.log("Rendering layout:",r.layout_name),e.innerHTML="",this.renderComponents(e,r.components),Gn.log("Layout rendered successfully")}catch(r){Gn.error("Render error:",r),this.renderErrorState(e,r)}}renderComponents(e,n){for(const r of n){const i=this.renderComponent(r);i&&e.appendChild(i)}}renderComponent(e){try{if(!this.componentRegistry.getComponent(e.type))return Gn.warn(`Component not found: ${e.type}`),this.createPlaceholderElement(e.type);const r=document.createElement("div");return r.setAttribute("data-component",e.type),e.props&&Object.entries(e.props).forEach(([i,l])=>{r.setAttribute(`data-prop-${i}`,JSON.stringify(l))}),e.children&&e.children.length>0?this.renderComponents(r,e.children):e.text&&(r.textContent=e.text),r}catch(n){return Gn.error(`Error rendering component ${e.type}:`,n),this.createErrorElement(e.type,n)}}createPlaceholderElement(e){const n=document.createElement("div");return n.className="component-placeholder",n.setAttribute("data-component-type",e),n.innerHTML=`

Component not found: ${e}

- `,a}createErrorElement(e,a){const r=document.createElement("div");return r.className="component-error",r.setAttribute("data-component-type",e),r.innerHTML=` + `,n}createErrorElement(e,n){const r=document.createElement("div");return r.className="component-error",r.setAttribute("data-component-type",e),r.innerHTML=`

Component Error: ${e}

-

${a?.message||"Unknown error"}

+

${n?.message||"Unknown error"}

- `,r}renderErrorState(e,a){const r=a instanceof Error?a.message:String(a),i=a instanceof ba?a.code:"UNKNOWN_ERROR";e.innerHTML=` + `,r}renderErrorState(e,n){const r=n instanceof Error?n.message:String(n),i=n instanceof va?n.code:"UNKNOWN_ERROR";e.innerHTML=`
페이지 새로고침
- `,Bn.error("Error state rendered:",i,r)}getCurrentLayout(){return this.currentLayout}clear(){this.currentLayout=null,this.layoutCache.clear(),Bn.log("Layout data and cache cleared")}}const S_=ct("TranslationContext"),nf=N.createContext(null),uc=({children:o,translationEngine:e,translationContext:a})=>{const r=N.useMemo(()=>(l,u)=>{if(u){const d="|"+Object.entries(u).map(([f,g])=>`${f}=${g}`).join("|");return e.translate(l,a,d)}return e.translate(l,a)},[e,a]),i=N.useMemo(()=>({translationEngine:e,translationContext:a,t:r}),[e,a,r]);return ut.jsx(nf.Provider,{value:i,children:o})},Fm=()=>{const o=N.useContext(nf);return o||(S_.warn("TranslationProvider 외부에서 호출되었습니다. 키를 그대로 반환합니다."),{t:e=>e,translationEngine:null,translationContext:null})},Rr=ct("SlotContext"),w_={registerToSlot:()=>{Rr.warn("SlotContext not available: registerToSlot called outside SlotProvider")},unregisterFromSlot:()=>{Rr.warn("SlotContext not available: unregisterFromSlot called outside SlotProvider")},getSlotComponents:()=>[],subscribeToSlot:()=>()=>{},clearAllSlots:()=>{},isEnabled:!1},C_=N.createContext(w_),af=({children:o})=>{const e=N.useRef(new Map),a=N.useRef(new Map),r=N.useCallback(m=>{const b=a.current.get(m);b&&b.forEach(v=>{try{v()}catch(S){Rr.error(`Slot subscriber error (slotId: ${m}):`,S)}})},[]),i=N.useCallback((m,b,v)=>{if(!m||!b){Rr.warn("registerToSlot: slotId and componentId are required");return}e.current.has(m)||e.current.set(m,new Map);const S=e.current.get(m),E=S.get(b);E&&E.registrationKey===v.registrationKey||(S.set(b,v),Rr.log(`Component registered to slot: ${b} -> ${m} (order: ${v.order})`),r(m))},[r]),l=N.useCallback((m,b)=>{const v=e.current.get(m);v&&v.has(b)&&(v.delete(b),Rr.log(`Component unregistered from slot: ${b} <- ${m}`),v.size===0&&e.current.delete(m),r(m))},[r]),u=N.useCallback(m=>{const b=e.current.get(m);return b?Array.from(b.values()).sort((v,S)=>v.order-S.order):[]},[]),d=N.useCallback((m,b)=>{a.current.has(m)||a.current.set(m,new Set);const v=a.current.get(m);return v.add(b),()=>{v.delete(b),v.size===0&&a.current.delete(m)}},[]),f=N.useCallback(()=>{e.current.forEach((m,b)=>{r(b)}),e.current.clear(),a.current.clear(),Rr.log("All slots cleared")},[r]),g=N.useMemo(()=>({registerToSlot:i,unregisterFromSlot:l,getSlotComponents:u,subscribeToSlot:d,clearAllSlots:f,isEnabled:!0}),[i,l,u,d,f]);return N.useLayoutEffect(()=>{typeof window<"u"&&(window.__slotContextValue=g,Rr.log("SlotContext exposed to window.__slotContextValue"))},[g]),ut.jsx(C_.Provider,{value:g,children:o})};class rf{constructor(){this.notificationCreatedEvent=".Illuminate\\Notifications\\Events\\BroadcastNotificationCreated"}listenForWhisper(e,a){return this.listen(".client-"+e,a)}notification(e){return this.listen(this.notificationCreatedEvent,e)}stopListeningForNotification(e){return this.stopListening(this.notificationCreatedEvent,e)}stopListeningForWhisper(e,a){return this.stopListening(".client-"+e,a)}}class Km{constructor(e){this.namespace=e}format(e){return[".","\\"].includes(e.charAt(0))?e.substring(1):(this.namespace&&(e=this.namespace+"."+e),e.replace(/\./g,"\\"))}setNamespace(e){this.namespace=e}}function E_(o){try{return Reflect.construct(String,[],o),!0}catch{return!1}}class sf extends rf{constructor(e,a,r){super(),this.name=a,this.pusher=e,this.options=r,this.eventFormatter=new Km(this.options.namespace),this.subscribe()}subscribe(){this.subscription=this.pusher.subscribe(this.name)}unsubscribe(){this.pusher.unsubscribe(this.name)}listen(e,a){return this.on(this.eventFormatter.format(e),a),this}listenToAll(e){return this.subscription.bind_global((a,r)=>{if(a.startsWith("pusher:"))return;let i=String(this.options.namespace??"").replace(/\./g,"\\"),l=a.startsWith(i)?a.substring(i.length+1):"."+a;e(l,r)}),this}stopListening(e,a){return a?this.subscription.unbind(this.eventFormatter.format(e),a):this.subscription.unbind(this.eventFormatter.format(e)),this}stopListeningToAll(e){return e?this.subscription.unbind_global(e):this.subscription.unbind_global(),this}subscribed(e){return this.on("pusher:subscription_succeeded",()=>{e()}),this}error(e){return this.on("pusher:subscription_error",a=>{e(a)}),this}on(e,a){return this.subscription.bind(e,a),this}}class Wm extends sf{whisper(e,a){return this.pusher.channels.channels[this.name].trigger(`client-${e}`,a),this}}class __ extends sf{whisper(e,a){return this.pusher.channels.channels[this.name].trigger(`client-${e}`,a),this}}class A_ extends Wm{here(e){return this.on("pusher:subscription_succeeded",a=>{e(Object.keys(a.members).map(r=>a.members[r]))}),this}joining(e){return this.on("pusher:member_added",a=>{e(a.info)}),this}whisper(e,a){return this.pusher.channels.channels[this.name].trigger(`client-${e}`,a),this}leaving(e){return this.on("pusher:member_removed",a=>{e(a.info)}),this}}class Ym extends rf{constructor(e,a,r){super(),this.events={},this.listeners={},this.name=a,this.socket=e,this.options=r,this.eventFormatter=new Km(this.options.namespace),this.subscribe()}subscribe(){this.socket.emit("subscribe",{channel:this.name,auth:this.options.auth||{}})}unsubscribe(){this.unbind(),this.socket.emit("unsubscribe",{channel:this.name,auth:this.options.auth||{}})}listen(e,a){return this.on(this.eventFormatter.format(e),a),this}stopListening(e,a){return this.unbindEvent(this.eventFormatter.format(e),a),this}subscribed(e){return this.on("connect",a=>{e(a)}),this}error(e){return this}on(e,a){return this.listeners[e]=this.listeners[e]||[],this.events[e]||(this.events[e]=(r,i)=>{this.name===r&&this.listeners[e]&&this.listeners[e].forEach(l=>l(i))},this.socket.on(e,this.events[e])),this.listeners[e].push(a),this}unbind(){Object.keys(this.events).forEach(e=>{this.unbindEvent(e)})}unbindEvent(e,a){this.listeners[e]=this.listeners[e]||[],a&&(this.listeners[e]=this.listeners[e].filter(r=>r!==a)),(!a||this.listeners[e].length===0)&&(this.events[e]&&(this.socket.removeListener(e,this.events[e]),delete this.events[e]),delete this.listeners[e])}}class Xm extends Ym{whisper(e,a){return this.socket.emit("client event",{channel:this.name,event:`client-${e}`,data:a}),this}}class x_ extends Xm{here(e){return this.on("presence:subscribed",a=>{e(a.map(r=>r.user_info))}),this}joining(e){return this.on("presence:joining",a=>e(a.user_info)),this}whisper(e,a){return this.socket.emit("client event",{channel:this.name,event:`client-${e}`,data:a}),this}leaving(e){return this.on("presence:leaving",a=>e(a.user_info)),this}}class dc extends rf{subscribe(){}unsubscribe(){}listen(e,a){return this}listenToAll(e){return this}stopListening(e,a){return this}subscribed(e){return this}error(e){return this}on(e,a){return this}}class Jm extends dc{whisper(e,a){return this}}class T_ extends dc{whisper(e,a){return this}}class R_ extends Jm{here(e){return this}joining(e){return this}whisper(e,a){return this}leaving(e){return this}}const Qm=class DS{constructor(e){this.setOptions(e),this.connect()}setOptions(e){this.options={...DS._defaultOptions,...e,broadcaster:e.broadcaster};let a=this.csrfToken();a&&(this.options.auth.headers["X-CSRF-TOKEN"]=a,this.options.userAuthentication.headers["X-CSRF-TOKEN"]=a),a=this.options.bearerToken,a&&(this.options.auth.headers.Authorization="Bearer "+a,this.options.userAuthentication.headers.Authorization="Bearer "+a)}csrfToken(){var e,a;return typeof window<"u"&&(e=window.Laravel)!=null&&e.csrfToken?window.Laravel.csrfToken:this.options.csrfToken?this.options.csrfToken:typeof document<"u"&&typeof document.querySelector=="function"?((a=document.querySelector('meta[name="csrf-token"]'))==null?void 0:a.getAttribute("content"))??null:null}};Qm._defaultOptions={auth:{headers:{}},authEndpoint:"/broadcasting/auth",userAuthentication:{endpoint:"/broadcasting/user-auth",headers:{}},csrfToken:null,bearerToken:null,host:null,key:null,namespace:"App.Events"};let of=Qm;class fc extends of{constructor(){super(...arguments),this.channels={}}connect(){if(typeof this.options.client<"u")this.pusher=this.options.client;else if(this.options.Pusher)this.pusher=new this.options.Pusher(this.options.key,this.options);else if(typeof window<"u"&&typeof window.Pusher<"u")this.pusher=new window.Pusher(this.options.key,this.options);else throw new Error("Pusher client not found. Should be globally available or passed via options.client")}signin(){this.pusher.signin()}listen(e,a,r){return this.channel(e).listen(a,r)}channel(e){return this.channels[e]||(this.channels[e]=new sf(this.pusher,e,this.options)),this.channels[e]}privateChannel(e){return this.channels["private-"+e]||(this.channels["private-"+e]=new Wm(this.pusher,"private-"+e,this.options)),this.channels["private-"+e]}encryptedPrivateChannel(e){return this.channels["private-encrypted-"+e]||(this.channels["private-encrypted-"+e]=new __(this.pusher,"private-encrypted-"+e,this.options)),this.channels["private-encrypted-"+e]}presenceChannel(e){return this.channels["presence-"+e]||(this.channels["presence-"+e]=new A_(this.pusher,"presence-"+e,this.options)),this.channels["presence-"+e]}leave(e){[e,"private-"+e,"private-encrypted-"+e,"presence-"+e].forEach(a=>{this.leaveChannel(a)})}leaveChannel(e){this.channels[e]&&(this.channels[e].unsubscribe(),delete this.channels[e])}socketId(){return this.pusher.connection.socket_id}connectionStatus(){const e=this.pusher.connection.state;switch(e){case"connected":case"connecting":return e;case"failed":case"unavailable":return"failed";default:return"disconnected"}}onConnectionChange(e){const a=()=>{e(this.connectionStatus())},r=["state_change","connected","disconnected"];return r.forEach(i=>{this.pusher.connection.bind(i,a)}),()=>{r.forEach(i=>{this.pusher.connection.unbind(i,a)})}}disconnect(){this.pusher.disconnect()}}class k_ extends of{constructor(){super(...arguments),this.channels={}}connect(){let e=this.getSocketIO();this.socket=e(this.options.host??void 0,this.options),this.socket.io.on("reconnect",()=>{Object.values(this.channels).forEach(a=>{a.subscribe()})})}getSocketIO(){if(typeof this.options.client<"u")return this.options.client;if(typeof window<"u"&&typeof window.io<"u")return window.io;throw new Error("Socket.io client not found. Should be globally available or passed via options.client")}listen(e,a,r){return this.channel(e).listen(a,r)}channel(e){return this.channels[e]||(this.channels[e]=new Ym(this.socket,e,this.options)),this.channels[e]}privateChannel(e){return this.channels["private-"+e]||(this.channels["private-"+e]=new Xm(this.socket,"private-"+e,this.options)),this.channels["private-"+e]}presenceChannel(e){return this.channels["presence-"+e]||(this.channels["presence-"+e]=new x_(this.socket,"presence-"+e,this.options)),this.channels["presence-"+e]}leave(e){[e,"private-"+e,"presence-"+e].forEach(a=>{this.leaveChannel(a)})}leaveChannel(e){this.channels[e]&&(this.channels[e].unsubscribe(),delete this.channels[e])}socketId(){return this.socket.id}connectionStatus(){return this.socket.connected?"connected":this.socket.io._reconnecting?"reconnecting":this.socket.id!==void 0?"disconnected":"connecting"}onConnectionChange(e){const a=()=>{e(this.connectionStatus())},r=["connect","disconnect","connect_error","reconnect_attempt","reconnect","reconnect_error","reconnect_failed"];return r.forEach(i=>{this.socket.on(i,a)}),()=>{r.forEach(i=>{this.socket.off(i,a)})}}disconnect(){this.socket.disconnect()}}class Zm extends of{constructor(){super(...arguments),this.channels={}}connect(){}listen(e,a,r){return new dc}channel(e){return new dc}privateChannel(e){return new Jm}encryptedPrivateChannel(e){return new T_}presenceChannel(e){return new R_}leave(e){}leaveChannel(e){}socketId(){return"fake-socket-id"}connectionStatus(){return"connected"}onConnectionChange(e){return()=>{}}disconnect(){}}class D_{constructor(e){this.options=e,this.connect(),this.options.withoutInterceptors||this.registerInterceptors()}channel(e){return this.connector.channel(e)}connect(){if(this.options.broadcaster==="reverb")this.connector=new fc({...this.options,cluster:""});else if(this.options.broadcaster==="pusher")this.connector=new fc(this.options);else if(this.options.broadcaster==="ably")this.connector=new fc({...this.options,cluster:"",broadcaster:"pusher"});else if(this.options.broadcaster==="socket.io")this.connector=new k_(this.options);else if(this.options.broadcaster==="null")this.connector=new Zm(this.options);else if(typeof this.options.broadcaster=="function"&&E_(this.options.broadcaster))this.connector=new this.options.broadcaster(this.options);else throw new Error(`Broadcaster ${typeof this.options.broadcaster} ${String(this.options.broadcaster)} is not supported.`)}disconnect(){this.connector.disconnect()}join(e){return this.connector.presenceChannel(e)}leave(e){this.connector.leave(e)}leaveChannel(e){this.connector.leaveChannel(e)}leaveAllChannels(){for(const e in this.connector.channels)this.leaveChannel(e)}listen(e,a,r){return this.connector.listen(e,a,r)}private(e){return this.connector.privateChannel(e)}encryptedPrivate(e){if(this.connectorSupportsEncryptedPrivateChannels(this.connector))return this.connector.encryptedPrivateChannel(e);throw new Error(`Broadcaster ${typeof this.options.broadcaster} ${String(this.options.broadcaster)} does not support encrypted private channels.`)}connectorSupportsEncryptedPrivateChannels(e){return e instanceof fc||e instanceof Zm}socketId(){return this.connector.socketId()}connectionStatus(){return this.connector.connectionStatus()}registerInterceptors(){typeof Vue<"u"&&Vue!=null&&Vue.http&&this.registerVueRequestInterceptor(),typeof axios=="function"&&this.registerAxiosRequestInterceptor(),typeof jQuery=="function"&&this.registerjQueryAjaxSetup(),typeof Turbo=="object"&&this.registerTurboRequestInterceptor()}registerVueRequestInterceptor(){Vue.http.interceptors.push((e,a)=>{this.socketId()&&e.headers.set("X-Socket-ID",this.socketId()),a()})}registerAxiosRequestInterceptor(){axios.interceptors.request.use(e=>(this.socketId()&&(e.headers["X-Socket-Id"]=this.socketId()),e))}registerjQueryAjaxSetup(){typeof jQuery.ajax<"u"&&jQuery.ajaxPrefilter((e,a,r)=>{this.socketId()&&r.setRequestHeader("X-Socket-Id",this.socketId())})}registerTurboRequestInterceptor(){document.addEventListener("turbo:before-fetch-request",e=>{e.detail.fetchOptions.headers["X-Socket-Id"]=this.socketId()})}}var lf={exports:{}};var ey;function O_(){return ey||(ey=1,(function(o,e){(function(r,i){o.exports=i()})(self,()=>(()=>{var a={594(u,d){var f=this&&this.__extends||(function(){var M=function(R,D){return M=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(U,j){U.__proto__=j}||function(U,j){for(var P in j)j.hasOwnProperty(P)&&(U[P]=j[P])},M(R,D)};return function(R,D){M(R,D);function U(){this.constructor=R}R.prototype=D===null?Object.create(D):(U.prototype=D.prototype,new U)}})();Object.defineProperty(d,"__esModule",{value:!0});var g=256,m=(function(){function M(R){R===void 0&&(R="="),this._paddingCharacter=R}return M.prototype.encodedLength=function(R){return this._paddingCharacter?(R+2)/3*4|0:(R*8+5)/6|0},M.prototype.encode=function(R){for(var D="",U=0;U>>18&63),D+=this._encodeByte(j>>>12&63),D+=this._encodeByte(j>>>6&63),D+=this._encodeByte(j>>>0&63)}var P=R.length-U;if(P>0){var j=R[U]<<16|(P===2?R[U+1]<<8:0);D+=this._encodeByte(j>>>18&63),D+=this._encodeByte(j>>>12&63),P===2?D+=this._encodeByte(j>>>6&63):D+=this._paddingCharacter||"",D+=this._paddingCharacter||""}return D},M.prototype.maxDecodedLength=function(R){return this._paddingCharacter?R/4*3|0:(R*6+7)/8|0},M.prototype.decodedLength=function(R){return this.maxDecodedLength(R.length-this._getPaddingLength(R))},M.prototype.decode=function(R){if(R.length===0)return new Uint8Array(0);for(var D=this._getPaddingLength(R),U=R.length-D,j=new Uint8Array(this.maxDecodedLength(U)),P=0,X=0,ge=0,Ee=0,Ce=0,$e=0,Pe=0;X>>4,j[P++]=Ce<<4|$e>>>2,j[P++]=$e<<6|Pe,ge|=Ee&g,ge|=Ce&g,ge|=$e&g,ge|=Pe&g;if(X>>4,ge|=Ee&g,ge|=Ce&g),X>>2,ge|=$e&g),X>>8&6,D+=51-R>>>8&-75,D+=61-R>>>8&-15,D+=62-R>>>8&3,String.fromCharCode(D)},M.prototype._decodeChar=function(R){var D=g;return D+=(42-R&R-44)>>>8&-g+R-43+62,D+=(46-R&R-48)>>>8&-g+R-47+63,D+=(47-R&R-58)>>>8&-g+R-48+52,D+=(64-R&R-91)>>>8&-g+R-65+0,D+=(96-R&R-123)>>>8&-g+R-97+26,D},M.prototype._getPaddingLength=function(R){var D=0;if(this._paddingCharacter){for(var U=R.length-1;U>=0&&R[U]===this._paddingCharacter;U--)D++;if(R.length<4||D>2)throw new Error("Base64Coder: incorrect padding")}return D},M})();d.Coder=m;var b=new m;function v(M){return b.encode(M)}d.encode=v;function S(M){return b.decode(M)}d.decode=S;var E=(function(M){f(R,M);function R(){return M!==null&&M.apply(this,arguments)||this}return R.prototype._encodeByte=function(D){var U=D;return U+=65,U+=25-D>>>8&6,U+=51-D>>>8&-75,U+=61-D>>>8&-13,U+=62-D>>>8&49,String.fromCharCode(U)},R.prototype._decodeChar=function(D){var U=g;return U+=(44-D&D-46)>>>8&-g+D-45+62,U+=(94-D&D-96)>>>8&-g+D-95+63,U+=(47-D&D-58)>>>8&-g+D-48+52,U+=(64-D&D-91)>>>8&-g+D-65+0,U+=(96-D&D-123)>>>8&-g+D-97+26,U},R})(m);d.URLSafeCoder=E;var A=new E;function T(M){return A.encode(M)}d.encodeURLSafe=T;function L(M){return A.decode(M)}d.decodeURLSafe=L,d.encodedLength=function(M){return b.encodedLength(M)},d.maxDecodedLength=function(M){return b.maxDecodedLength(M)},d.decodedLength=function(M){return b.decodedLength(M)}},978(u,d){var f="utf8: invalid source encoding";function g(m){for(var b=[],v=0;v=m.length)throw new Error(f);var A=m[++v];if((A&192)!==128)throw new Error(f);S=(S&31)<<6|A&63,E=128}else if(S<240){if(v>=m.length-1)throw new Error(f);var A=m[++v],T=m[++v];if((A&192)!==128||(T&192)!==128)throw new Error(f);S=(S&15)<<12|(A&63)<<6|T&63,E=2048}else if(S<248){if(v>=m.length-2)throw new Error(f);var A=m[++v],T=m[++v],L=m[++v];if((A&192)!==128||(T&192)!==128||(L&192)!==128)throw new Error(f);S=(S&15)<<18|(A&63)<<12|(T&63)<<6|L&63,E=65536}else throw new Error(f);if(S=55296&&S<=57343)throw new Error(f);if(S>=65536){if(S>1114111)throw new Error(f);S-=65536,b.push(String.fromCharCode(55296|S>>10)),S=56320|S&1023}}b.push(String.fromCharCode(S))}return b.join("")}d.D4=g},721(u,d,f){u.exports=f(207).default},207(u,d,f){f.d(d,{default:()=>ms});class g{constructor(y,C){this.lastId=0,this.prefix=y,this.name=C}create(y){this.lastId++;var C=this.lastId,O=this.prefix+C,I=this.name+"["+C+"]",ne=!1,pe=function(){ne||(y.apply(null,arguments),ne=!0)};return this[C]=pe,{number:C,id:O,name:I,callback:pe}}remove(y){delete this[y.number]}}var m=new g("_pusher_script_","Pusher.ScriptReceivers"),b={VERSION:"8.5.0",PROTOCOL:7,wsPort:80,wssPort:443,wsPath:"",httpHost:"sockjs.pusher.com",httpPort:80,httpsPort:443,httpPath:"/pusher",stats_host:"stats.pusher.com",authEndpoint:"/pusher/auth",authTransport:"ajax",activityTimeout:12e4,pongTimeout:3e4,unavailableTimeout:1e4,userAuthentication:{endpoint:"/pusher/user-auth",transport:"ajax"},channelAuthorization:{endpoint:"/pusher/auth",transport:"ajax"},cdn_http:"http://js.pusher.com",cdn_https:"https://js.pusher.com",dependency_suffix:""};const v=b;class S{constructor(y){this.options=y,this.receivers=y.receivers||m,this.loading={}}load(y,C,O){var I=this;if(I.loading[y]&&I.loading[y].length>0)I.loading[y].push(O);else{I.loading[y]=[O];var ne=Be.createScriptRequest(I.getPath(y,C)),pe=I.receivers.create(function(Me){if(I.receivers.remove(pe),I.loading[y]){var Ve=I.loading[y];delete I.loading[y];for(var ot=function(Nt){Nt||ne.cleanup()},pt=0;pt>>6)+Q(128|y&63):Q(224|y>>>12&15)+Q(128|y>>>6&63)+Q(128|y&63)},te=function(_){return _.replace(/[^\x00-\x7F]/g,ye)},he=function(_){var y=[0,2,1][_.length%3],C=_.charCodeAt(0)<<16|(_.length>1?_.charCodeAt(1):0)<<8|(_.length>2?_.charCodeAt(2):0),O=[fe.charAt(C>>>18),fe.charAt(C>>>12&63),y>=2?"=":fe.charAt(C>>>6&63),y>=1?"=":fe.charAt(C&63)];return O.join("")},x=window.btoa||function(_){return _.replace(/[\s\S]{1,3}/g,he)};class K{constructor(y,C,O,I){this.clear=C,this.timer=y(()=>{this.timer&&(this.timer=I(this.timer))},O)}isRunning(){return this.timer!==null}ensureAborted(){this.timer&&(this.clear(this.timer),this.timer=null)}}const re=K;function de(_){window.clearTimeout(_)}function ie(_){window.clearInterval(_)}class me extends re{constructor(y,C){super(setTimeout,de,y,function(O){return C(),null})}}class Ne extends re{constructor(y,C){super(setInterval,ie,y,function(O){return C(),O})}}var Se={now(){return Date.now?Date.now():new Date().valueOf()},defer(_){return new me(0,_)},method(_,...y){var C=Array.prototype.slice.call(arguments,1);return function(O){return O[_].apply(O,C.concat(arguments))}}};const He=Se;function Ae(_,...y){for(var C=0;C{window.console&&window.console.log&&window.console.log(y)}}debug(...y){this.log(this.globalLog,y)}warn(...y){this.log(this.globalLogWarn,y)}error(...y){this.log(this.globalLogError,y)}globalLogWarn(y){window.console&&window.console.warn?window.console.warn(y):this.globalLog(y)}globalLogError(y){window.console&&window.console.error?window.console.error(y):this.globalLogWarn(y)}log(y,...C){var O=Et.apply(this,arguments);ms.log?ms.log(O):ms.logToConsole&&y.bind(this)(O)}}const et=new tn;var ta=function(_,y,C,O,I){(C.headers!==void 0||C.headersProvider!=null)&&et.warn(`To send headers with the ${O.toString()} request, you must use AJAX, rather than JSONP.`);var ne=_.nextAuthCallbackID.toString();_.nextAuthCallbackID++;var pe=_.getDocument(),Me=pe.createElement("script");_.auth_callbacks[ne]=function(pt){I(null,pt)};var Ve="Pusher.auth_callbacks['"+ne+"']";Me.src=C.endpoint+"?callback="+encodeURIComponent(Ve)+"&"+y;var ot=pe.getElementsByTagName("head")[0]||pe.documentElement;ot.insertBefore(Me,ot.firstChild)};const En=ta;class tr{constructor(y){this.src=y}send(y){var C=this,O="Error loading "+C.src;C.script=document.createElement("script"),C.script.id=y.id,C.script.src=C.src,C.script.type="text/javascript",C.script.charset="UTF-8",C.script.addEventListener?(C.script.onerror=function(){y.callback(O)},C.script.onload=function(){y.callback(null)}):C.script.onreadystatechange=function(){(C.script.readyState==="loaded"||C.script.readyState==="complete")&&y.callback(null)},C.script.async===void 0&&document.attachEvent&&/opera/i.test(navigator.userAgent)?(C.errorScript=document.createElement("script"),C.errorScript.id=y.id+"_error",C.errorScript.text=y.name+"('"+O+"');",C.script.async=C.errorScript.async=!1):C.script.async=!0;var I=document.getElementsByTagName("head")[0];I.insertBefore(C.script,I.firstChild),C.errorScript&&I.insertBefore(C.errorScript,C.script.nextSibling)}cleanup(){this.script&&(this.script.onload=this.script.onerror=null,this.script.onreadystatechange=null),this.script&&this.script.parentNode&&this.script.parentNode.removeChild(this.script),this.errorScript&&this.errorScript.parentNode&&this.errorScript.parentNode.removeChild(this.errorScript),this.script=null,this.errorScript=null}}class Ea{constructor(y,C){this.url=y,this.data=C}send(y){if(!this.request){var C=Dr(this.data),O=this.url+"/"+y.number+"?"+C;this.request=Be.createScriptRequest(O),this.request.send(y)}}cleanup(){this.request&&this.request.cleanup()}}var nn=function(_,y){return function(C,O){var I="http"+(y?"s":"")+"://",ne=I+(_.host||_.options.host)+_.options.path,pe=Be.createJSONPRequest(ne,C),Me=Be.ScriptReceivers.create(function(Ve,ot){m.remove(Me),pe.cleanup(),ot&&ot.host&&(_.host=ot.host),O&&O(Ve,ot)});pe.send(Me)}},_n={name:"jsonp",getAgent:nn};const q=_n;function ce(_,y,C){var O=_+(y.useTLS?"s":""),I=y.useTLS?y.hostTLS:y.hostNonTLS;return O+"://"+I+C}function le(_,y){var C="/app/"+_,O="?protocol="+v.PROTOCOL+"&client=js&version="+v.VERSION+(y?"&"+y:"");return C+O}var Z={getInitial:function(_,y){var C=(y.httpPath||"")+le(_,"flash=false");return ce("ws",y,C)}},be={getInitial:function(_,y){var C=(y.httpPath||"/pusher")+le(_);return ce("http",y,C)}},ve={getInitial:function(_,y){return ce("http",y,y.httpPath||"/pusher")},getPath:function(_,y){return le(_)}};class Re{constructor(){this._callbacks={}}get(y){return this._callbacks[xe(y)]}add(y,C,O){var I=xe(y);this._callbacks[I]=this._callbacks[I]||[],this._callbacks[I].push({fn:C,context:O})}remove(y,C,O){if(!y&&!C&&!O){this._callbacks={};return}var I=y?[xe(y)]:ft(this._callbacks);C||O?this.removeCallback(I,C,O):this.removeAllCallbacks(I)}removeCallback(y,C,O){gt(y,function(I){this._callbacks[I]=Dn(this._callbacks[I]||[],function(ne){return C&&C!==ne.fn||O&&O!==ne.context}),this._callbacks[I].length===0&&delete this._callbacks[I]},this)}removeAllCallbacks(y){gt(y,function(C){delete this._callbacks[C]},this)}}function xe(_){return"_"+_}class je{constructor(y){this.callbacks=new Re,this.global_callbacks=[],this.failThrough=y}bind(y,C,O){return this.callbacks.add(y,C,O),this}bind_global(y){return this.global_callbacks.push(y),this}unbind(y,C,O){return this.callbacks.remove(y,C,O),this}unbind_global(y){return y?(this.global_callbacks=Dn(this.global_callbacks||[],C=>C!==y),this):(this.global_callbacks=[],this)}unbind_all(){return this.unbind(),this.unbind_global(),this}emit(y,C,O){for(var I=0;I0)for(var I=0;I{this.onError(C),this.changeState("closed")}),!1}return this.bindListeners(),et.debug("Connecting",{transport:this.name,url:y}),this.changeState("connecting"),!0}close(){return this.socket?(this.socket.close(),!0):!1}send(y){return this.state==="open"?(He.defer(()=>{this.socket&&this.socket.send(y)}),!0):!1}ping(){this.state==="open"&&this.supportsPing()&&this.socket.ping()}onOpen(){this.hooks.beforeOpen&&this.hooks.beforeOpen(this.socket,this.hooks.urls.getPath(this.key,this.options)),this.changeState("open"),this.socket.onopen=void 0}onError(y){this.emit("error",{type:"WebSocketError",error:y}),this.timeline.error(this.buildTimelineMessage({error:y.toString()}))}onClose(y){y?this.changeState("closed",{code:y.code,reason:y.reason,wasClean:y.wasClean}):this.changeState("closed"),this.unbindListeners(),this.socket=void 0}onMessage(y){this.emit("message",y)}onActivity(){this.emit("activity")}bindListeners(){this.socket.onopen=()=>{this.onOpen()},this.socket.onerror=y=>{this.onError(y)},this.socket.onclose=y=>{this.onClose(y)},this.socket.onmessage=y=>{this.onMessage(y)},this.supportsPing()&&(this.socket.onactivity=()=>{this.onActivity()})}unbindListeners(){this.socket&&(this.socket.onopen=void 0,this.socket.onerror=void 0,this.socket.onclose=void 0,this.socket.onmessage=void 0,this.supportsPing()&&(this.socket.onactivity=void 0))}changeState(y,C){this.state=y,this.timeline.info(this.buildTimelineMessage({state:y,params:C})),this.emit(y,C)}buildTimelineMessage(y){return Ae({cid:this.id},y)}}class Le{constructor(y){this.hooks=y}isSupported(y){return this.hooks.isSupported(y)}createConnection(y,C,O,I){return new ze(this.hooks,y,C,O,I)}}var ke=new Le({urls:Z,handlesActivityChecks:!1,supportsPing:!1,isInitialized:function(){return!!Be.getWebSocketAPI()},isSupported:function(){return!!Be.getWebSocketAPI()},getSocket:function(_){return Be.createWebSocket(_)}}),We={urls:be,handlesActivityChecks:!1,supportsPing:!0,isInitialized:function(){return!0}},Fe=Ae({getSocket:function(_){return Be.HTTPFactory.createStreamingSocket(_)}},We),_e=Ae({getSocket:function(_){return Be.HTTPFactory.createPollingSocket(_)}},We),Te={isSupported:function(){return Be.isXHRSupported()}},Ue=new Le(Ae({},Fe,Te)),st=new Le(Ae({},_e,Te)),At={ws:ke,xhr_streaming:Ue,xhr_polling:st};const Wt=At;var qt=new Le({file:"sockjs",urls:ve,handlesActivityChecks:!0,supportsPing:!1,isSupported:function(){return!0},isInitialized:function(){return window.SockJS!==void 0},getSocket:function(_,y){return new window.SockJS(_,null,{js_path:A.getPath("sockjs",{useTLS:y.useTLS}),ignore_null_origin:y.ignoreNullOrigin})},beforeOpen:function(_,y){_.send(JSON.stringify({path:y}))}}),qn={isSupported:function(_){var y=Be.isXDRSupported(_.useTLS);return y}},Ln=new Le(Ae({},Fe,qn)),an=new Le(Ae({},_e,qn));Wt.xdr_streaming=Ln,Wt.xdr_polling=an,Wt.sockjs=qt;const vn=Wt;class Or extends je{constructor(){super();var y=this;window.addEventListener!==void 0&&(window.addEventListener("online",function(){y.emit("online")},!1),window.addEventListener("offline",function(){y.emit("offline")},!1))}isOnline(){return window.navigator.onLine===void 0?!0:window.navigator.onLine}}var Ro=new Or;class pf{constructor(y,C,O){this.manager=y,this.transport=C,this.minPingDelay=O.minPingDelay,this.maxPingDelay=O.maxPingDelay,this.pingDelay=void 0}createConnection(y,C,O,I){I=Ae({},I,{activityTimeout:this.pingDelay});var ne=this.transport.createConnection(y,C,O,I),pe=null,Me=function(){ne.unbind("open",Me),ne.bind("closed",Ve),pe=He.now()},Ve=ot=>{if(ne.unbind("closed",Ve),ot.code===1002||ot.code===1003)this.manager.reportDeath();else if(!ot.wasClean&&pe){var pt=He.now()-pe;pt<2*this.maxPingDelay&&(this.manager.reportDeath(),this.pingDelay=Math.max(pt/2,this.minPingDelay))}};return ne.bind("open",Me),ne}isSupported(y){return this.manager.isAlive()&&this.transport.isSupported(y)}}const vc={decodeMessage:function(_){try{var y=JSON.parse(_.data),C=y.data;if(typeof C=="string")try{C=JSON.parse(y.data)}catch{}var O={event:y.event,channel:y.channel,data:C};return y.user_id&&(O.user_id=y.user_id),O}catch(I){throw{type:"MessageParseError",error:I,data:_.data}}},encodeMessage:function(_){return JSON.stringify(_)},processHandshake:function(_){var y=vc.decodeMessage(_);if(y.event==="pusher:connection_established"){if(!y.data.activity_timeout)throw"No activity timeout specified in handshake";return{action:"connected",id:y.data.socket_id,activityTimeout:y.data.activity_timeout*1e3}}else{if(y.event==="pusher:error")return{action:this.getCloseAction(y.data),error:this.getCloseError(y.data)};throw"Invalid handshake"}},getCloseAction:function(_){return _.code<4e3?_.code>=1002&&_.code<=1004?"backoff":null:_.code===4e3?"tls_only":_.code<4100?"refused":_.code<4200?"backoff":_.code<4300?"retry":"refused"},getCloseError:function(_){return _.code!==1e3&&_.code!==1001?{type:"PusherError",data:{code:_.code,message:_.reason||_.message}}:null}},Ba=vc;class bi extends je{constructor(y,C){super(),this.id=y,this.transport=C,this.activityTimeout=C.activityTimeout,this.bindListeners()}handlesActivityChecks(){return this.transport.handlesActivityChecks()}send(y){return this.transport.send(y)}send_event(y,C,O){var I={event:y,data:C};return O&&(I.channel=O),et.debug("Event sent",I),this.send(Ba.encodeMessage(I))}ping(){this.transport.supportsPing()?this.transport.ping():this.send_event("pusher:ping",{})}close(){this.transport.close()}bindListeners(){var y={message:O=>{var I;try{I=Ba.decodeMessage(O)}catch(ne){this.emit("error",{type:"MessageParseError",error:ne,data:O.data})}if(I!==void 0){switch(et.debug("Event recd",I),I.event){case"pusher:error":this.emit("error",{type:"PusherError",data:I.data});break;case"pusher:ping":this.emit("ping");break;case"pusher:pong":this.emit("pong");break}this.emit("message",I)}},activity:()=>{this.emit("activity")},error:O=>{this.emit("error",O)},closed:O=>{C(),O&&O.code&&this.handleCloseEvent(O),this.transport=null,this.emit("closed")}},C=()=>{_t(y,(O,I)=>{this.transport.unbind(I,O)})};_t(y,(O,I)=>{this.transport.bind(I,O)})}handleCloseEvent(y){var C=Ba.getCloseAction(y),O=Ba.getCloseError(y);O&&this.emit("error",O),C&&this.emit(C,{action:C,error:O})}}class ko{constructor(y,C){this.transport=y,this.callback=C,this.bindListeners()}close(){this.unbindListeners(),this.transport.close()}bindListeners(){this.onMessage=y=>{this.unbindListeners();var C;try{C=Ba.processHandshake(y)}catch(O){this.finish("error",{error:O}),this.transport.close();return}C.action==="connected"?this.finish("connected",{connection:new bi(C.id,this.transport),activityTimeout:C.activityTimeout}):(this.finish(C.action,{error:C.error}),this.transport.close())},this.onClosed=y=>{this.unbindListeners();var C=Ba.getCloseAction(y)||"backoff",O=Ba.getCloseError(y);this.finish(C,{error:O})},this.transport.bind("message",this.onMessage),this.transport.bind("closed",this.onClosed)}unbindListeners(){this.transport.unbind("message",this.onMessage),this.transport.unbind("closed",this.onClosed)}finish(y,C){this.callback(Ae({transport:this.transport,action:y},C))}}class Lr{constructor(y,C){this.timeline=y,this.options=C||{}}send(y,C){this.timeline.isEmpty()||this.timeline.send(Be.TimelineTransport.getAgent(this,y),C)}}class Pa extends je{constructor(y,C){super(function(O,I){et.debug("No callbacks on "+y+" for "+O)}),this.name=y,this.pusher=C,this.subscribed=!1,this.subscriptionPending=!1,this.subscriptionCancelled=!1}authorize(y,C){return C(null,{auth:""})}trigger(y,C){if(y.indexOf("client-")!==0)throw new D("Event '"+y+"' does not start with 'client-'");if(!this.subscribed){var O=M.buildLogSuffix("triggeringClientEvents");et.warn(`Client event triggered before channel 'subscription_succeeded' event . ${O}`)}return this.pusher.send_event(y,C,this.name)}disconnect(){this.subscribed=!1,this.subscriptionPending=!1}handleEvent(y){var C=y.event,O=y.data;if(C==="pusher_internal:subscription_succeeded")this.handleSubscriptionSucceededEvent(y);else if(C==="pusher_internal:subscription_count")this.handleSubscriptionCountEvent(y);else if(C.indexOf("pusher_internal:")!==0){var I={};this.emit(C,O,I)}}handleSubscriptionSucceededEvent(y){this.subscriptionPending=!1,this.subscribed=!0,this.subscriptionCancelled?this.pusher.unsubscribe(this.name):this.emit("pusher:subscription_succeeded",y.data)}handleSubscriptionCountEvent(y){y.data.subscription_count&&(this.subscriptionCount=y.data.subscription_count),this.emit("pusher:subscription_count",y.data)}subscribe(){this.subscribed||(this.subscriptionPending=!0,this.subscriptionCancelled=!1,this.authorize(this.pusher.connection.socket_id,(y,C)=>{y?(this.subscriptionPending=!1,et.error(y.toString()),this.emit("pusher:subscription_error",Object.assign({},{type:"AuthError",error:y.message},y instanceof $e?{status:y.status}:{}))):this.pusher.send_event("pusher:subscribe",{auth:C.auth,channel_data:C.channel_data,channel:this.name})}))}unsubscribe(){this.subscribed=!1,this.pusher.send_event("pusher:unsubscribe",{channel:this.name})}cancelSubscription(){this.subscriptionCancelled=!0}reinstateSubscription(){this.subscriptionCancelled=!1}}class nr extends Pa{authorize(y,C){return this.pusher.config.channelAuthorizer({channelName:this.name,socketId:y},C)}}class Mr{constructor(){this.reset()}get(y){return Object.prototype.hasOwnProperty.call(this.members,y)?{id:y,info:this.members[y]}:null}each(y){_t(this.members,(C,O)=>{y(this.get(O))})}setMyID(y){this.myID=y}onSubscription(y){this.members=y.presence.hash,this.count=y.presence.count,this.me=this.get(this.myID)}addMember(y){return this.get(y.user_id)===null&&this.count++,this.members[y.user_id]=y.user_info,this.get(y.user_id)}removeMember(y){var C=this.get(y.user_id);return C&&(delete this.members[y.user_id],this.count--),C}reset(){this.members={},this.count=0,this.myID=null,this.me=null}}var Yt=function(_,y,C,O){function I(ne){return ne instanceof C?ne:new C(function(pe){pe(ne)})}return new(C||(C=Promise))(function(ne,pe){function Me(pt){try{ot(O.next(pt))}catch(Nt){pe(Nt)}}function Ve(pt){try{ot(O.throw(pt))}catch(Nt){pe(Nt)}}function ot(pt){pt.done?ne(pt.value):I(pt.value).then(Me,Ve)}ot((O=O.apply(_,y||[])).next())})};class Sc extends nr{constructor(y,C){super(y,C),this.members=new Mr}authorize(y,C){super.authorize(y,(O,I)=>Yt(this,void 0,void 0,function*(){if(!O)if(I=I,I.channel_data!=null){var ne=JSON.parse(I.channel_data);this.members.setMyID(ne.user_id)}else if(yield this.pusher.user.signinDonePromise,this.pusher.user.user_data!=null)this.members.setMyID(this.pusher.user.user_data.id);else{let pe=M.buildLogSuffix("authorizationEndpoint");et.error(`Invalid auth response for channel '${this.name}', expected 'channel_data' field. ${pe}, or the user should be signed in.`),C("Invalid auth response");return}C(O,I)}))}handleEvent(y){var C=y.event;if(C.indexOf("pusher_internal:")===0)this.handleInternalEvent(y);else{var O=y.data,I={};y.user_id&&(I.user_id=y.user_id),this.emit(C,O,I)}}handleInternalEvent(y){var C=y.event,O=y.data;switch(C){case"pusher_internal:subscription_succeeded":this.handleSubscriptionSucceededEvent(y);break;case"pusher_internal:subscription_count":this.handleSubscriptionCountEvent(y);break;case"pusher_internal:member_added":var I=this.members.addMember(O);this.emit("pusher:member_added",I);break;case"pusher_internal:member_removed":var ne=this.members.removeMember(O);ne&&this.emit("pusher:member_removed",ne);break}}handleSubscriptionSucceededEvent(y){this.subscriptionPending=!1,this.subscribed=!0,this.subscriptionCancelled?this.pusher.unsubscribe(this.name):(this.members.onSubscription(y.data),this.emit("pusher:subscription_succeeded",this.members))}disconnect(){this.members.reset(),super.disconnect()}}var wc=f(978),_a=f(594);class $r extends nr{constructor(y,C,O){super(y,C),this.key=null,this.nacl=O}authorize(y,C){super.authorize(y,(O,I)=>{if(O){C(O,I);return}let ne=I.shared_secret;if(!ne){C(new Error(`No shared_secret key in auth payload for encrypted channel: ${this.name}`),null);return}this.key=(0,_a.decode)(ne),delete I.shared_secret,C(null,I)})}trigger(y,C){throw new ge("Client events are not currently supported for encrypted channels")}handleEvent(y){var C=y.event,O=y.data;if(C.indexOf("pusher_internal:")===0||C.indexOf("pusher:")===0){super.handleEvent(y);return}this.handleEncryptedEvent(C,O)}handleEncryptedEvent(y,C){if(!this.key){et.debug("Received encrypted event before key has been retrieved from the authEndpoint");return}if(!C.ciphertext||!C.nonce){et.error("Unexpected format for encrypted event, expected object with `ciphertext` and `nonce` fields, got: "+C);return}let O=(0,_a.decode)(C.ciphertext);if(O.length{if(pe){et.error(`Failed to make a request to the authEndpoint: ${Me}. Unable to fetch new key, so dropping encrypted event`);return}if(ne=this.nacl.secretbox.open(O,I,this.key),ne===null){et.error("Failed to decrypt event with new key. Dropping encrypted event");return}this.emit(y,this.getDataToEmit(ne))});return}this.emit(y,this.getDataToEmit(ne))}getDataToEmit(y){let C=(0,wc.D4)(y);try{return JSON.parse(C)}catch{return C}}}class mf extends je{constructor(y,C){super(),this.state="initialized",this.connection=null,this.key=y,this.options=C,this.timeline=this.options.timeline,this.usingTLS=this.options.useTLS,this.errorCallbacks=this.buildErrorCallbacks(),this.connectionCallbacks=this.buildConnectionCallbacks(this.errorCallbacks),this.handshakeCallbacks=this.buildHandshakeCallbacks(this.errorCallbacks);var O=Be.getNetwork();O.bind("online",()=>{this.timeline.info({netinfo:"online"}),(this.state==="connecting"||this.state==="unavailable")&&this.retryIn(0)}),O.bind("offline",()=>{this.timeline.info({netinfo:"offline"}),this.connection&&this.sendActivityCheck()}),this.updateStrategy()}switchCluster(y){this.key=y,this.updateStrategy(),this.retryIn(0)}connect(){if(!(this.connection||this.runner)){if(!this.strategy.isSupported()){this.updateState("failed");return}this.updateState("connecting"),this.startConnecting(),this.setUnavailableTimer()}}send(y){return this.connection?this.connection.send(y):!1}send_event(y,C,O){return this.connection?this.connection.send_event(y,C,O):!1}disconnect(){this.disconnectInternally(),this.updateState("disconnected")}isUsingTLS(){return this.usingTLS}startConnecting(){var y=(C,O)=>{C?this.runner=this.strategy.connect(0,y):O.action==="error"?(this.emit("error",{type:"HandshakeError",error:O.error}),this.timeline.error({handshakeError:O.error})):(this.abortConnecting(),this.handshakeCallbacks[O.action](O))};this.runner=this.strategy.connect(0,y)}abortConnecting(){this.runner&&(this.runner.abort(),this.runner=null)}disconnectInternally(){if(this.abortConnecting(),this.clearRetryTimer(),this.clearUnavailableTimer(),this.connection){var y=this.abandonConnection();y.close()}}updateStrategy(){this.strategy=this.options.getStrategy({key:this.key,timeline:this.timeline,useTLS:this.usingTLS})}retryIn(y){this.timeline.info({action:"retry",delay:y}),y>0&&this.emit("connecting_in",Math.round(y/1e3)),this.retryTimer=new me(y||0,()=>{this.disconnectInternally(),this.connect()})}clearRetryTimer(){this.retryTimer&&(this.retryTimer.ensureAborted(),this.retryTimer=null)}setUnavailableTimer(){this.unavailableTimer=new me(this.options.unavailableTimeout,()=>{this.updateState("unavailable")})}clearUnavailableTimer(){this.unavailableTimer&&this.unavailableTimer.ensureAborted()}sendActivityCheck(){this.stopActivityCheck(),this.connection.ping(),this.activityTimer=new me(this.options.pongTimeout,()=>{this.timeline.error({pong_timed_out:this.options.pongTimeout}),this.retryIn(0)})}resetActivityCheck(){this.stopActivityCheck(),this.connection&&!this.connection.handlesActivityChecks()&&(this.activityTimer=new me(this.activityTimeout,()=>{this.sendActivityCheck()}))}stopActivityCheck(){this.activityTimer&&this.activityTimer.ensureAborted()}buildConnectionCallbacks(y){return Ae({},y,{message:C=>{this.resetActivityCheck(),this.emit("message",C)},ping:()=>{this.send_event("pusher:pong",{})},activity:()=>{this.resetActivityCheck()},error:C=>{this.emit("error",C)},closed:()=>{this.abandonConnection(),this.shouldRetry()&&this.retryIn(1e3)}})}buildHandshakeCallbacks(y){return Ae({},y,{connected:C=>{this.activityTimeout=Math.min(this.options.activityTimeout,C.activityTimeout,C.connection.activityTimeout||1/0),this.clearUnavailableTimer(),this.setConnection(C.connection),this.socket_id=this.connection.id,this.updateState("connected",{socket_id:this.socket_id})}})}buildErrorCallbacks(){let y=C=>O=>{O.error&&this.emit("error",{type:"WebSocketError",error:O.error}),C(O)};return{tls_only:y(()=>{this.usingTLS=!0,this.updateStrategy(),this.retryIn(0)}),refused:y(()=>{this.disconnect()}),backoff:y(()=>{this.retryIn(1e3)}),retry:y(()=>{this.retryIn(0)})}}setConnection(y){this.connection=y;for(var C in this.connectionCallbacks)this.connection.bind(C,this.connectionCallbacks[C]);this.resetActivityCheck()}abandonConnection(){if(this.connection){this.stopActivityCheck();for(var y in this.connectionCallbacks)this.connection.unbind(y,this.connectionCallbacks[y]);var C=this.connection;return this.connection=null,C}}updateState(y,C){var O=this.state;if(this.state=y,O!==y){var I=y;I==="connected"&&(I+=" with new socket ID "+C.socket_id),et.debug("State changed",O+" -> "+I),this.timeline.info({state:y,params:C}),this.emit("state_change",{previous:O,current:y}),this.emit(y,C)}}shouldRetry(){return this.state==="connecting"||this.state==="connected"}}class Cc{constructor(){this.channels={}}add(y,C){return this.channels[y]||(this.channels[y]=Ec(y,C)),this.channels[y]}all(){return un(this.channels)}find(y){return this.channels[y]}remove(y){var C=this.channels[y];return delete this.channels[y],C}disconnect(){_t(this.channels,function(y){y.disconnect()})}}function Ec(_,y){if(_.indexOf("private-encrypted-")===0){if(y.config.nacl)return Mn.createEncryptedChannel(_,y,y.config.nacl);let C="Tried to subscribe to a private-encrypted- channel but no nacl implementation available",O=M.buildLogSuffix("encryptedChannelSupport");throw new ge(`${C}. ${O}`)}else{if(_.indexOf("private-")===0)return Mn.createPrivateChannel(_,y);if(_.indexOf("presence-")===0)return Mn.createPresenceChannel(_,y);if(_.indexOf("#")===0)throw new U('Cannot create a channel with name "'+_+'".');return Mn.createChannel(_,y)}}var yf={createChannels(){return new Cc},createConnectionManager(_,y){return new mf(_,y)},createChannel(_,y){return new Pa(_,y)},createPrivateChannel(_,y){return new nr(_,y)},createPresenceChannel(_,y){return new Sc(_,y)},createEncryptedChannel(_,y,C){return new $r(_,y,C)},createTimelineSender(_,y){return new Lr(_,y)},createHandshake(_,y){return new ko(_,y)},createAssistantToTheTransportManager(_,y,C){return new pf(_,y,C)}};const Mn=yf;class vi{constructor(y){this.options=y||{},this.livesLeft=this.options.lives||1/0}getAssistant(y){return Mn.createAssistantToTheTransportManager(this,y,{minPingDelay:this.options.minPingDelay,maxPingDelay:this.options.maxPingDelay})}isAlive(){return this.livesLeft>0}reportDeath(){this.livesLeft-=1}}class dn{constructor(y,C){this.strategies=y,this.loop=!!C.loop,this.failFast=!!C.failFast,this.timeout=C.timeout,this.timeoutLimit=C.timeoutLimit}isSupported(){return ea(this.strategies,He.method("isSupported"))}connect(y,C){var O=this.strategies,I=0,ne=this.timeout,pe=null,Me=(Ve,ot)=>{ot?C(null,ot):(I=I+1,this.loop&&(I=I%O.length),I0&&(ne=new me(O.timeout,function(){pe.abort(),I(!0)})),pe=y.connect(C,function(Me,Ve){Me&&ne&&ne.isRunning()&&!O.failFast||(ne&&ne.ensureAborted(),I(Me,Ve))}),{abort:function(){ne&&ne.ensureAborted(),pe.abort()},forceMinPriority:function(Me){pe.forceMinPriority(Me)}}}}class Sn{constructor(y){this.strategies=y}isSupported(){return ea(this.strategies,He.method("isSupported"))}connect(y,C){return _c(this.strategies,y,function(O,I){return function(ne,pe){if(I[O].error=ne,ne){bf(I)&&C(!0);return}gt(I,function(Me){Me.forceMinPriority(pe.transport.priority)}),C(null,pe)}})}}function _c(_,y,C){var O=ja(_,function(I,ne,pe,Me){return I.connect(y,C(ne,Me))});return{abort:function(){gt(O,Do)},forceMinPriority:function(I){gt(O,function(ne){ne.forceMinPriority(I)})}}}function bf(_){return Ua(_,function(y){return!!y.error})}function Do(_){!_.error&&!_.aborted&&(_.abort(),_.aborted=!0)}class Ac{constructor(y,C,O){this.strategy=y,this.transports=C,this.ttl=O.ttl||18e5,this.usingTLS=O.useTLS,this.timeline=O.timeline}isSupported(){return this.strategy.isSupported()}connect(y,C){var O=this.usingTLS,I=vf(O),ne=I&&I.cacheSkipCount?I.cacheSkipCount:0,pe=[this.strategy];if(I&&I.timestamp+this.ttl>=He.now()){var Me=this.transports[I.transport];Me&&(["ws","wss"].includes(I.transport)||ne>3?(this.timeline.info({cached:!0,transport:I.transport,latency:I.latency}),pe.push(new dn([Me],{timeout:I.latency*2+1e3,failFast:!0}))):ne++)}var Ve=He.now(),ot=pe.pop().connect(y,function pt(Nt,Ra){Nt?(ds(O),pe.length>0?(Ve=He.now(),ot=pe.pop().connect(y,pt)):C(Nt)):($n(O,Ra.transport.name,He.now()-Ve,ne),C(null,Ra))});return{abort:function(){ot.abort()},forceMinPriority:function(pt){y=pt,ot&&ot.forceMinPriority(pt)}}}}function Nr(_){return"pusherTransport"+(_?"TLS":"NonTLS")}function vf(_){var y=Be.getLocalStorage();if(y)try{var C=y[Nr(_)];if(C)return JSON.parse(C)}catch{ds(_)}return null}function $n(_,y,C,O){var I=Be.getLocalStorage();if(I)try{I[Nr(_)]=bn({timestamp:He.now(),transport:y,latency:C,cacheSkipCount:O})}catch{}}function ds(_){var y=Be.getLocalStorage();if(y)try{delete y[Nr(_)]}catch{}}class Si{constructor(y,{delay:C}){this.strategy=y,this.options={delay:C}}isSupported(){return this.strategy.isSupported()}connect(y,C){var O=this.strategy,I,ne=new me(this.options.delay,function(){I=O.connect(y,C)});return{abort:function(){ne.ensureAborted(),I&&I.abort()},forceMinPriority:function(pe){y=pe,I&&I.forceMinPriority(pe)}}}}class ar{constructor(y,C,O){this.test=y,this.trueBranch=C,this.falseBranch=O}isSupported(){var y=this.test()?this.trueBranch:this.falseBranch;return y.isSupported()}connect(y,C){var O=this.test()?this.trueBranch:this.falseBranch;return O.connect(y,C)}}class Ir{constructor(y){this.strategy=y}isSupported(){return this.strategy.isSupported()}connect(y,C){var O=this.strategy.connect(y,function(I,ne){ne&&O.abort(),C(I,ne)});return O}}function Hr(_){return function(){return _.isSupported()}}var xc=function(_,y,C){var O={};function I(Go,Uc,Bc,Uf,Bf){var Pc=C(_,Go,Uc,Bc,Uf,Bf);return O[Go]=Pc,Pc}var ne=Object.assign({},y,{hostNonTLS:_.wsHost+":"+_.wsPort,hostTLS:_.wsHost+":"+_.wssPort,httpPath:_.wsPath}),pe=Object.assign({},ne,{useTLS:!0}),Me=Object.assign({},y,{hostNonTLS:_.httpHost+":"+_.httpPort,hostTLS:_.httpHost+":"+_.httpsPort,httpPath:_.httpPath}),Ve={loop:!0,timeout:15e3,timeoutLimit:6e4},ot=new vi({minPingDelay:1e4,maxPingDelay:_.activityTimeout}),pt=new vi({lives:2,minPingDelay:1e4,maxPingDelay:_.activityTimeout}),Nt=I("ws","ws",3,ne,ot),Ra=I("wss","ws",3,pe,ot),Hf=I("sockjs","sockjs",1,Me),zc=I("xhr_streaming","xhr_streaming",1,Me,pt),zf=I("xdr_streaming","xdr_streaming",1,Me,pt),Bo=I("xhr_polling","xhr_polling",1,Me),jc=I("xdr_polling","xdr_polling",1,Me),Ur=new dn([Nt],Ve),xi=new dn([Ra],Ve),jf=new dn([Hf],Ve),Ti=new dn([new ar(Hr(zc),zc,zf)],Ve),Po=new dn([new ar(Hr(Bo),Bo,jc)],Ve),qo=new dn([new ar(Hr(Ti),new Sn([Ti,new Si(Po,{delay:4e3})]),Po)],Ve),Ri=new ar(Hr(qo),qo,jf),ki;return y.useTLS?ki=new Sn([Ur,new Si(Ri,{delay:2e3})]):ki=new Sn([Ur,new Si(xi,{delay:2e3}),new Si(Ri,{delay:5e3})]),new Ac(new Ir(new ar(Hr(Nt),ki,Ri)),O,{ttl:18e5,timeline:y.timeline,useTLS:y.useTLS})};const zr=xc;function Sf(){var _=this;_.timeline.info(_.buildTimelineMessage({transport:_.name+(_.options.useTLS?"s":"")})),_.hooks.isInitialized()?_.changeState("initialized"):_.hooks.file?(_.changeState("initializing"),A.load(_.hooks.file,{useTLS:_.options.useTLS},function(y,C){_.hooks.isInitialized()?(_.changeState("initialized"),C(!0)):(y&&_.onError(y),_.onClose(),C(!1))})):_.onClose()}var Tc={getRequest:function(_){var y=new window.XDomainRequest;return y.ontimeout=function(){_.emit("error",new j),_.close()},y.onerror=function(C){_.emit("error",C),_.close()},y.onprogress=function(){y.responseText&&y.responseText.length>0&&_.onChunk(200,y.responseText)},y.onload=function(){y.responseText&&y.responseText.length>0&&_.onChunk(200,y.responseText),_.emit("finished",200),_.close()},y},abortRequest:function(_){_.ontimeout=_.onerror=_.onprogress=_.onload=null,_.abort()}};const Rc=Tc,Oo=256*1024;class wf extends je{constructor(y,C,O){super(),this.hooks=y,this.method=C,this.url=O}start(y){this.position=0,this.xhr=this.hooks.getRequest(this),this.unloader=()=>{this.close()},Be.addUnloadListener(this.unloader),this.xhr.open(this.method,this.url,!0),this.xhr.setRequestHeader&&this.xhr.setRequestHeader("Content-Type","application/json"),this.xhr.send(y)}close(){this.unloader&&(Be.removeUnloadListener(this.unloader),this.unloader=null),this.xhr&&(this.hooks.abortRequest(this.xhr),this.xhr=null)}onChunk(y,C){for(;;){var O=this.advanceBuffer(C);if(O)this.emit("chunk",{status:y,data:O});else break}this.isBufferTooLong(C)&&this.emit("buffer_too_long")}advanceBuffer(y){var C=y.slice(this.position),O=C.indexOf(` -`);return O!==-1?(this.position+=O+1,C.slice(0,O)):null}isBufferTooLong(y){return this.position===y.length&&y.length>Oo}}var Lo;(function(_){_[_.CONNECTING=0]="CONNECTING",_[_.OPEN=1]="OPEN",_[_.CLOSED=3]="CLOSED"})(Lo||(Lo={}));const na=Lo;var Aa=1;class Mo{constructor(y,C){this.hooks=y,this.session=fs(1e3)+"/"+Dc(8),this.location=$o(C),this.readyState=na.CONNECTING,this.openStream()}send(y){return this.sendRaw(JSON.stringify([y]))}ping(){this.hooks.sendHeartbeat(this)}close(y,C){this.onClose(y,C,!0)}sendRaw(y){if(this.readyState===na.OPEN)try{return Be.createSocketRequest("POST",rr(jr(this.location,this.session))).start(y),!0}catch{return!1}else return!1}reconnect(){this.closeStream(),this.openStream()}onClose(y,C,O){this.closeStream(),this.readyState=na.CLOSED,this.onclose&&this.onclose({code:y,reason:C,wasClean:O})}onChunk(y){if(y.status===200){this.readyState===na.OPEN&&this.onActivity();var C,O=y.data.slice(0,1);switch(O){case"o":C=JSON.parse(y.data.slice(1)||"{}"),this.onOpen(C);break;case"a":C=JSON.parse(y.data.slice(1)||"[]");for(var I=0;I{this.onChunk(y)}),this.stream.bind("finished",y=>{this.hooks.onFinished(this,y)}),this.stream.bind("buffer_too_long",()=>{this.reconnect()});try{this.stream.start()}catch(y){He.defer(()=>{this.onError(y),this.onClose(1006,"Could not start streaming",!1)})}}closeStream(){this.stream&&(this.stream.unbind_all(),this.stream.close(),this.stream=null)}}function $o(_){var y=/([^\?]*)\/*(\??.*)/.exec(_);return{base:y[1],queryString:y[2]}}function jr(_,y){return _.base+"/"+y+"/xhr_send"}function rr(_){var y=_.indexOf("?")===-1?"?":"&";return _+y+"t="+ +new Date+"&n="+Aa++}function kc(_,y){var C=/(https?:\/\/)([^\/:]+)((\/|:)?.*)/.exec(_);return C[1]+y+C[3]}function fs(_){return Be.randomInt(_)}function Dc(_){for(var y=[],C=0;C<_;C++)y.push(fs(32).toString(32));return y.join("")}const wi=Mo;var xa={getReceiveURL:function(_,y){return _.base+"/"+y+"/xhr_streaming"+_.queryString},onHeartbeat:function(_){_.sendRaw("[]")},sendHeartbeat:function(_){_.sendRaw("[]")},onFinished:function(_,y){_.onClose(1006,"Connection interrupted ("+y+")",!1)}};const No=xa;var Ci={getReceiveURL:function(_,y){return _.base+"/"+y+"/xhr"+_.queryString},onHeartbeat:function(){},sendHeartbeat:function(_){_.sendRaw("[]")},onFinished:function(_,y){y===200?_.reconnect():_.onClose(1006,"Connection interrupted ("+y+")",!1)}};const qa=Ci;var Io={getRequest:function(_){var y=Be.getXHRAPI(),C=new y;return C.onreadystatechange=C.onprogress=function(){switch(C.readyState){case 3:C.responseText&&C.responseText.length>0&&_.onChunk(C.status,C.responseText);break;case 4:C.responseText&&C.responseText.length>0&&_.onChunk(C.status,C.responseText),_.emit("finished",C.status),_.close();break}},C},abortRequest:function(_){_.onreadystatechange=null,_.abort()}};const hs=Io;var Oc={createStreamingSocket(_){return this.createSocket(No,_)},createPollingSocket(_){return this.createSocket(qa,_)},createSocket(_,y){return new wi(_,y)},createXHR(_,y){return this.createRequest(hs,_,y)},createRequest(_,y,C){return new wf(_,y,C)}};const Ei=Oc;Ei.createXDR=function(_,y){return this.createRequest(Rc,_,y)};var Lc={nextAuthCallbackID:1,auth_callbacks:{},ScriptReceivers:m,DependenciesReceivers:E,getDefaultStrategy:zr,Transports:vn,transportConnectionInitializer:Sf,HTTPFactory:Ei,TimelineTransport:q,getXHRAPI(){return window.XMLHttpRequest},getWebSocketAPI(){return window.WebSocket||window.MozWebSocket},setup(_){window.Pusher=_;var y=()=>{this.onDocumentBody(_.ready)};window.JSON?y():A.load("json2",{},y)},getDocument(){return document},getProtocol(){return this.getDocument().location.protocol},getAuthorizers(){return{ajax:Xe,jsonp:En}},onDocumentBody(_){document.body?_():setTimeout(()=>{this.onDocumentBody(_)},0)},createJSONPRequest(_,y){return new Ea(_,y)},createScriptRequest(_){return new tr(_)},getLocalStorage(){try{return window.localStorage}catch{return}},createXHR(){return this.getXHRAPI()?this.createXMLHttpRequest():this.createMicrosoftXHR()},createXMLHttpRequest(){var _=this.getXHRAPI();return new _},createMicrosoftXHR(){return new ActiveXObject("Microsoft.XMLHTTP")},getNetwork(){return Ro},createWebSocket(_){var y=this.getWebSocketAPI();return new y(_)},createSocketRequest(_,y){if(this.isXHRSupported())return this.HTTPFactory.createXHR(_,y);if(this.isXDRSupported(y.indexOf("https:")===0))return this.HTTPFactory.createXDR(_,y);throw"Cross-origin HTTP requests are not supported"},isXHRSupported(){var _=this.getXHRAPI();return!!_&&new _().withCredentials!==void 0},isXDRSupported(_){var y=_?"https:":"http:",C=this.getProtocol();return!!window.XDomainRequest&&C===y},addUnloadListener(_){window.addEventListener!==void 0?window.addEventListener("unload",_,!1):window.attachEvent!==void 0&&window.attachEvent("onunload",_)},removeUnloadListener(_){window.addEventListener!==void 0?window.removeEventListener("unload",_,!1):window.detachEvent!==void 0&&window.detachEvent("onunload",_)},randomInt(_){return Math.floor(function(){return(window.crypto||window.msCrypto).getRandomValues(new Uint32Array(1))[0]/Math.pow(2,32)}()*_)}};const Be=Lc;var Ta;(function(_){_[_.ERROR=3]="ERROR",_[_.INFO=6]="INFO",_[_.DEBUG=7]="DEBUG"})(Ta||(Ta={}));const ir=Ta;class _i{constructor(y,C,O){this.key=y,this.session=C,this.events=[],this.options=O||{},this.sent=0,this.uniqueID=0}log(y,C){y<=this.options.level&&(this.events.push(Ae({},C,{timestamp:He.now()})),this.options.limit&&this.events.length>this.options.limit&&this.events.shift())}error(y){this.log(ir.ERROR,y)}info(y){this.log(ir.INFO,y)}debug(y){this.log(ir.DEBUG,y)}isEmpty(){return this.events.length===0}send(y,C){var O=Ae({session:this.session,bundle:this.sent+1,key:this.key,lib:"js",version:this.options.version,cluster:this.options.cluster,features:this.options.features,timeline:this.events},this.options.params);return this.events=[],y(O,(I,ne)=>{I||this.sent++,C&&C(I,ne)}),!0}generateUniqueID(){return this.uniqueID++,this.uniqueID}}class Cf{constructor(y,C,O,I){this.name=y,this.priority=C,this.transport=O,this.options=I||{}}isSupported(){return this.transport.isSupported({useTLS:this.options.useTLS})}connect(y,C){if(this.isSupported()){if(this.priority{O||(pt(),ne?ne.close():I.close())},forceMinPriority:Nt=>{O||this.priority{var C="socket_id="+encodeURIComponent(_.socketId);for(var O in y.params)C+="&"+encodeURIComponent(O)+"="+encodeURIComponent(y.params[O]);if(y.paramsProvider!=null){let I=y.paramsProvider();for(var O in I)C+="&"+encodeURIComponent(O)+"="+encodeURIComponent(I[O])}return C},_f=_=>{if(typeof Be.getAuthorizers()[_.transport]>"u")throw`'${_.transport}' is not a recognized auth transport`;return(y,C)=>{const O=Ef(y,_);Be.getAuthorizers()[_.transport](Be,O,_,R.UserAuthentication,C)}},jo=(_,y)=>{var C="socket_id="+encodeURIComponent(_.socketId);C+="&channel_name="+encodeURIComponent(_.channelName);for(var O in y.params)C+="&"+encodeURIComponent(O)+"="+encodeURIComponent(y.params[O]);if(y.paramsProvider!=null){let I=y.paramsProvider();for(var O in I)C+="&"+encodeURIComponent(O)+"="+encodeURIComponent(I[O])}return C},Af=_=>{if(typeof Be.getAuthorizers()[_.transport]>"u")throw`'${_.transport}' is not a recognized auth transport`;return(y,C)=>{const O=jo(y,_);Be.getAuthorizers()[_.transport](Be,O,_,R.ChannelAuthorization,C)}},xf=(_,y,C)=>{const O={authTransport:y.transport,authEndpoint:y.endpoint,auth:{params:y.params,headers:y.headers}};return(I,ne)=>{const pe=_.channel(I.channelName);C(pe,O).authorize(I.socketId,ne)}};function $c(_,y){let C={activityTimeout:_.activityTimeout||v.activityTimeout,cluster:_.cluster,httpPath:_.httpPath||v.httpPath,httpPort:_.httpPort||v.httpPort,httpsPort:_.httpsPort||v.httpsPort,pongTimeout:_.pongTimeout||v.pongTimeout,statsHost:_.statsHost||v.stats_host,unavailableTimeout:_.unavailableTimeout||v.unavailableTimeout,wsPath:_.wsPath||v.wsPath,wsPort:_.wsPort||v.wsPort,wssPort:_.wssPort||v.wssPort,enableStats:Df(_),httpHost:Tf(_),useTLS:kf(_),wsHost:Nc(_),userAuthenticator:Uo(_),channelAuthorizer:Lf(_,y)};return"disabledTransports"in _&&(C.disabledTransports=_.disabledTransports),"enabledTransports"in _&&(C.enabledTransports=_.enabledTransports),"ignoreNullOrigin"in _&&(C.ignoreNullOrigin=_.ignoreNullOrigin),"timelineParams"in _&&(C.timelineParams=_.timelineParams),"nacl"in _&&(C.nacl=_.nacl),C}function Tf(_){return _.httpHost?_.httpHost:_.cluster?`sockjs-${_.cluster}.pusher.com`:v.httpHost}function Nc(_){return _.wsHost?_.wsHost:Rf(_.cluster)}function Rf(_){return`ws-${_}.pusher.com`}function kf(_){return Be.getProtocol()==="https:"?!0:_.forceTLS!==!1}function Df(_){return"enableStats"in _?_.enableStats:"disableStats"in _?!_.disableStats:!1}const Ic=_=>"customHandler"in _&&_.customHandler!=null;function Uo(_){const y=Object.assign(Object.assign({},v.userAuthentication),_.userAuthentication);return Ic(y)?y.customHandler:_f(y)}function Of(_,y){let C;if("channelAuthorization"in _)C=Object.assign(Object.assign({},v.channelAuthorization),_.channelAuthorization);else if(C={transport:_.authTransport||v.authTransport,endpoint:_.authEndpoint||v.authEndpoint},"auth"in _&&("params"in _.auth&&(C.params=_.auth.params),"headers"in _.auth&&(C.headers=_.auth.headers)),"authorizer"in _)return{customHandler:xf(y,C,_.authorizer)};return C}function Lf(_,y){const C=Of(_,y);return Ic(C)?C.customHandler:Af(C)}class Mf extends je{constructor(y){super(function(C,O){et.debug(`No callbacks on watchlist events for ${C}`)}),this.pusher=y,this.bindWatchlistInternalEvent()}handleEvent(y){y.data.events.forEach(C=>{this.emit(C.name,C)})}bindWatchlistInternalEvent(){this.pusher.connection.bind("message",y=>{var C=y.event;C==="pusher_internal:watchlist_events"&&this.handleEvent(y)})}}function Hc(){let _,y;return{promise:new Promise((O,I)=>{_=O,y=I}),resolve:_,reject:y}}const $f=Hc;class Nf extends je{constructor(y){super(function(C,O){et.debug("No callbacks on user for "+C)}),this.signin_requested=!1,this.user_data=null,this.serverToUserChannel=null,this.signinDonePromise=null,this._signinDoneResolve=null,this._onAuthorize=(C,O)=>{if(C){et.warn(`Error during signin: ${C}`),this._cleanup();return}this.pusher.send_event("pusher:signin",{auth:O.auth,user_data:O.user_data})},this.pusher=y,this.pusher.connection.bind("state_change",({previous:C,current:O})=>{C!=="connected"&&O==="connected"&&this._signin(),C==="connected"&&O!=="connected"&&(this._cleanup(),this._newSigninPromiseIfNeeded())}),this.watchlist=new Mf(y),this.pusher.connection.bind("message",C=>{var O=C.event;O==="pusher:signin_success"&&this._onSigninSuccess(C.data),this.serverToUserChannel&&this.serverToUserChannel.name===C.channel&&this.serverToUserChannel.handleEvent(C)})}signin(){this.signin_requested||(this.signin_requested=!0,this._signin())}_signin(){this.signin_requested&&(this._newSigninPromiseIfNeeded(),this.pusher.connection.state==="connected"&&this.pusher.config.userAuthenticator({socketId:this.pusher.connection.socket_id},this._onAuthorize))}_onSigninSuccess(y){try{this.user_data=JSON.parse(y.user_data)}catch{et.error(`Failed parsing user data after signin: ${y.user_data}`),this._cleanup();return}if(typeof this.user_data.id!="string"||this.user_data.id===""){et.error(`user_data doesn't contain an id. user_data: ${this.user_data}`),this._cleanup();return}this._signinDoneResolve(),this._subscribeChannels()}_subscribeChannels(){const y=C=>{C.subscriptionPending&&C.subscriptionCancelled?C.reinstateSubscription():!C.subscriptionPending&&this.pusher.connection.state==="connected"&&C.subscribe()};this.serverToUserChannel=new Pa(`#server-to-user-${this.user_data.id}`,this.pusher),this.serverToUserChannel.bind_global((C,O)=>{C.indexOf("pusher_internal:")===0||C.indexOf("pusher:")===0||this.emit(C,O)}),y(this.serverToUserChannel)}_cleanup(){this.user_data=null,this.serverToUserChannel&&(this.serverToUserChannel.unbind_all(),this.serverToUserChannel.disconnect(),this.serverToUserChannel=null),this.signin_requested&&this._signinDoneResolve()}_newSigninPromiseIfNeeded(){if(!this.signin_requested||this.signinDonePromise&&!this.signinDonePromise.done)return;const{promise:y,resolve:C}=$f();y.done=!1;const O=()=>{y.done=!0};y.then(O).catch(O),this.signinDonePromise=y,this._signinDoneResolve=C}}class rn{static ready(){rn.isReady=!0;for(var y=0,C=rn.instances.length;yBe.getDefaultStrategy(this.config,I,Ai);this.connection=Mn.createConnectionManager(this.key,{getStrategy:O,timeline:this.timeline,activityTimeout:this.config.activityTimeout,pongTimeout:this.config.pongTimeout,unavailableTimeout:this.config.unavailableTimeout,useTLS:!!this.config.useTLS}),this.connection.bind("connected",()=>{this.subscribeAll(),this.timelineSender&&this.timelineSender.send(this.connection.isUsingTLS())}),this.connection.bind("message",I=>{var ne=I.event,pe=ne.indexOf("pusher_internal:")===0;if(I.channel){var Me=this.channel(I.channel);Me&&Me.handleEvent(I)}pe||this.global_emitter.emit(I.event,I.data)}),this.connection.bind("connecting",()=>{this.channels.disconnect()}),this.connection.bind("disconnected",()=>{this.channels.disconnect()}),this.connection.bind("error",I=>{et.warn(I)}),rn.instances.push(this),this.timeline.info({instances:rn.instances.length}),this.user=new Nf(this),rn.isReady&&this.connect()}switchCluster(y){const{appKey:C,cluster:O}=y;this.key=C,this.options=Object.assign(Object.assign({},this.options),{cluster:O}),this.config=$c(this.options,this),this.connection.switchCluster(this.key)}channel(y){return this.channels.find(y)}allChannels(){return this.channels.all()}connect(){if(this.connection.connect(),this.timelineSender&&!this.timelineSenderTimer){var y=this.connection.isUsingTLS(),C=this.timelineSender;this.timelineSenderTimer=new Ne(6e4,function(){C.send(y)})}}disconnect(){this.connection.disconnect(),this.timelineSenderTimer&&(this.timelineSenderTimer.ensureAborted(),this.timelineSenderTimer=null)}bind(y,C,O){return this.global_emitter.bind(y,C,O),this}unbind(y,C,O){return this.global_emitter.unbind(y,C,O),this}bind_global(y){return this.global_emitter.bind_global(y),this}unbind_global(y){return this.global_emitter.unbind_global(y),this}unbind_all(y){return this.global_emitter.unbind_all(),this}subscribeAll(){var y;for(y in this.channels.channels)this.channels.channels.hasOwnProperty(y)&&this.subscribe(y)}subscribe(y){var C=this.channels.add(y,this);return C.subscriptionPending&&C.subscriptionCancelled?C.reinstateSubscription():!C.subscriptionPending&&this.connection.state==="connected"&&C.subscribe(),C}unsubscribe(y){var C=this.channels.find(y);C&&C.subscriptionPending?C.cancelSubscription():(C=this.channels.remove(y),C&&C.subscribed&&C.unsubscribe())}send_event(y,C,O){return this.connection.send_event(y,C,O)}shouldUseTLS(){return this.config.useTLS}signin(){this.user.signin()}}rn.instances=[],rn.isReady=!1,rn.logToConsole=!1,rn.Runtime=Be,rn.ScriptReceivers=Be.ScriptReceivers,rn.DependenciesReceivers=Be.DependenciesReceivers,rn.auth_callbacks=Be.auth_callbacks;const ms=rn;function If(_){if(_==null)throw"You must pass your app key when you instantiate Pusher."}Be.setup(rn)}},r={};function i(u){var d=r[u];if(d!==void 0)return d.exports;var f=r[u]={exports:{}};return a[u].call(f.exports,f,f.exports,i),f.exports}i.d=(u,d)=>{for(var f in d)i.o(d,f)&&!i.o(u,f)&&Object.defineProperty(u,f,{enumerable:!0,get:d[f]})},i.o=(u,d)=>Object.prototype.hasOwnProperty.call(u,d);var l=i(721);return l})())})(lf)),lf.exports}var L_=O_();const ty=Ya(L_),Ht=ct("WebSocketManager");class M_{constructor(){$(this,"echo",null);$(this,"subscriptions",new Map);$(this,"initialized",!1);$(this,"config",null)}configure(e){if(this.initialized){Ht.warn("[WebSocketManager] 이미 초기화되어 설정을 변경할 수 없습니다.");return}this.config=e,Ht.log("[WebSocketManager] 설정 완료:",{appKey:e.appKey?"***":"(없음)",host:e.host,port:e.port,scheme:e.scheme})}initialize(){if(this.initialized)return;if(!this.config||!this.config.appKey){Ht.warn("[WebSocketManager] WebSocket 설정이 없습니다. initTemplateApp에서 websocket 옵션을 전달해주세요.");return}const{appKey:e,host:a="localhost",port:r=80,scheme:i="https",authEndpoint:l="/api/broadcasting/auth"}=this.config,u=Number(r)||80,d=i==="https";Ht.log("[WebSocketManager] 연결 설정:",{host:a,port:u,scheme:i,useTLS:d,authEndpoint:l}),window.Pusher=ty;const f=localStorage.getItem("auth_token"),g={wsHost:a,wsPort:u,wssPort:u,forceTLS:d,disableStats:!0,enabledTransports:["ws","wss"],cluster:"mt1",authEndpoint:l,auth:{headers:{Authorization:f?`Bearer ${f}`:"",Accept:"application/json"}}};Ht.log("[WebSocketManager] Pusher 옵션:",g);const m=new ty(e,g);m.connection.bind("connecting",()=>{Ht.log("[WebSocketManager] 연결 시도 중...")}),m.connection.bind("connected",()=>{Ht.log("[WebSocketManager] 연결 성공! Socket ID:",m.connection.socket_id)}),m.connection.bind("failed",()=>{Ht.error("[WebSocketManager] 연결 실패 - WebSocket을 사용할 수 없습니다.")}),m.connection.bind("error",b=>{Ht.error("[WebSocketManager] 연결 오류:",b)}),m.connection.bind("state_change",b=>{Ht.log(`[WebSocketManager] 상태 변경: ${b.previous} → ${b.current}`)}),m.connection.bind("unavailable",()=>{Ht.error("[WebSocketManager] WebSocket 사용 불가 - 연결할 수 없습니다.")}),m.connection.bind("disconnected",()=>{Ht.warn("[WebSocketManager] 연결이 끊어졌습니다.")}),Ht.log("[WebSocketManager] 초기 연결 상태:",m.connection.state),this.echo=new D_({broadcaster:"reverb",client:m}),Ht.log("[WebSocketManager] 연결 시작 시도..."),m.connect(),window.Echo=this.echo,this.initialized=!0,Ht.log("[WebSocketManager] Echo 초기화 완료")}subscribe(e,a,r,i={}){if(this.initialize(),!this.echo)return Ht.warn("[WebSocketManager] Echo가 초기화되지 않았습니다."),"";const{channelType:l="private"}=i,u=`${e}:${a}`;if(this.subscriptions.has(u))return Ht.log(`[WebSocketManager] 이미 구독 중: ${u}`),u;let d;switch(l){case"public":d=this.echo.channel(e);break;case"presence":d=this.echo.join(e);break;default:d=this.echo.private(e)}return d.listen(`.${a}`,r),this.subscriptions.set(u,d),Ht.log(`[WebSocketManager] 구독 완료: ${u} (${l})`),u}unsubscribe(e){const a=this.subscriptions.get(e);if(!a)return;const r=e.lastIndexOf(":"),i=r>=0?e.substring(r+1):"";if(i)try{a.stopListening(`.${i}`)}catch(l){Ht.warn(`[WebSocketManager] stopListening 실패: ${e}`,l)}this.subscriptions.delete(e),Ht.log(`[WebSocketManager] 구독 해제: ${e}`)}leaveChannel(e){if(!this.echo)return;this.echo.leave(e);const a=[];this.subscriptions.forEach((r,i)=>{i.startsWith(`${e}:`)&&a.push(i)}),a.forEach(r=>this.subscriptions.delete(r)),Ht.log(`[WebSocketManager] 채널 구독 해제: ${e}`)}disconnect(){this.echo&&(this.echo.disconnect(),this.subscriptions.clear(),this.initialized=!1,Ht.log("[WebSocketManager] 연결 종료"))}getEcho(){return this.echo}isInitialized(){return this.initialized}isConfigured(){return this.config!==null&&!!this.config.appKey}getSubscriptionCount(){return this.subscriptions.size}}const hc=new M_,bt=ct("DataSourceManager"),$_=new wn;function gc(o,e){const a=o.match(/^\{\{(.+)\}\}$/);if(a){const r=a[1].trim();try{return $_.evaluateExpression(r,e)}catch(i){return bt.error("Failed to evaluate param expression:",r,i),o}}return Ji(o,e,{skipCache:!0})}function ny(o){const e={};for(const a of o.keys()){if(a in e)continue;const r=o.getAll(a);r.length>1?e[a]=r:r.length===1&&(a.endsWith("[]")?e[a]=r:e[a]=r[0])}return e}function N_(){try{return window.G7Core?.devTools}catch{return}}const bc=class bc{constructor(e={}){$(this,"options");$(this,"dataCache",new Map);$(this,"bindingEngine");$(this,"globalHeaders",[]);this.options=e,this.bindingEngine=new wn}setGlobalHeaders(e){this.globalHeaders=e||[]}matchesPattern(e,a){if(a==="*")return!0;const r=a.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(e)}toFormData(e){const a=new FormData;for(const[r,i]of Object.entries(e))i instanceof File||i instanceof Blob?a.append(r,i):i!=null&&a.append(r,typeof i=="object"?JSON.stringify(i):String(i));return a}getMatchingGlobalHeaders(e,a){const r={};for(const i of this.globalHeaders)this.matchesPattern(e,i.pattern)&&Object.entries(i.headers).forEach(([l,u])=>{const d=gc(u,a);d!=null&&d!==""&&(r[l]=String(d))});return r}filterByCondition(e,a={}){const r=new Set,i=[];for(const l of e){if(r.has(l.id))continue;if(!l.if&&!l.conditions){r.add(l.id),i.push(l);continue}Xi({if:l.if,conditions:l.conditions},a,this.bindingEngine,`data_source:${l.id}`)&&(r.add(l.id),i.push(l))}return i}checkErrorCondition(e,a){if(!e.errorCondition?.if||e.errorCondition?.errorCode===void 0)return null;try{const r={response:a};if(Xi({if:e.errorCondition.if},r,this.bindingEngine,`errorCondition:${e.id}`))return bt.log(`errorCondition matched for ${e.id}, triggering error ${e.errorCondition.errorCode}`),e.errorCondition.errorCode}catch(r){bt.error(`Failed to evaluate errorCondition for ${e.id}:`,r)}return null}async fetchDataSources(e,a={},r=new URLSearchParams,i,l){const u={},d=!!this.options.sampleProvider,f=e.filter(g=>(d||g.auto_fetch!==!1)&&g.type!=="websocket");return await Promise.all(f.map(async g=>{try{const m=await this.fetchDataSource(g,a,r,i,l);u[g.id]=m,this.dataCache.set(g.id,{data:m,timestamp:Date.now()});const b=this.checkErrorCondition(g,m);if(b!==null){const v={status:b,message:`Error condition matched for ${g.id}`,data:m},S=pa(),E=S.resolve(b,{errorHandling:g.errorHandling,onError:g.onError});if(E.handler)try{await S.execute(E.handler,v)}catch(A){bt.error(`Error executing errorCondition handler for ${g.id}:`,A)}g.fallback!==void 0&&(u[g.id]=g.fallback,this.dataCache.set(g.id,{data:g.fallback,timestamp:Date.now()}),bt.log(`Using fallback data for ${g.id} (errorCondition)`));return}if(g.onSuccess)try{const v={data:m,sourceId:g.id};await this.executeOnSuccessHandler(g.onSuccess,v)}catch(v){bt.error(`Error executing onSuccess handler for ${g.id}:`,v)}}catch(m){bt.error(`Failed to fetch data source: ${g.id}`,m);const b=m?.response?.status||m?.status||500,v=m?.response?.data,S=v?.message||m.message||"Unknown error",E={status:b,message:S,errors:v?.errors,data:v,statusText:m?.response?.statusText},A=pa(),T=A.resolve(b,{errorHandling:g.errorHandling,onError:g.onError});if(T.handler)try{await A.execute(T.handler,E)}catch(L){bt.error(`Error executing error handler for ${g.id}:`,L)}g.fallback!==void 0&&(u[g.id]=g.fallback,this.dataCache.set(g.id,{data:g.fallback,timestamp:Date.now()}),bt.log(`Using fallback data for ${g.id}`)),this.options.onError&&this.options.onError(m,g)}})),u}async fetchDataSourcesWithResults(e,a={},r=new URLSearchParams,i,l,u){if(e.some(m=>m.type==="websocket")){const m=e.filter(b=>b.type==="websocket").map(b=>b.id).join(", ");bt.warn(`fetchDataSourcesWithResults received WebSocket sources (caller should filter them out before calling): ${m}. WebSocket sources are event listeners, not data providers — they should not be passed to fetch.`)}const f=u?.ignoreAutoFetch?e.filter(m=>m.type!=="websocket"):e.filter(m=>m.auto_fetch!==!1&&m.type!=="websocket");return await Promise.all(f.map(async m=>{try{const b=await this.fetchDataSource(m,a,r,i,l);this.dataCache.set(m.id,{data:b,timestamp:Date.now()});const v=this.checkErrorCondition(m,b);if(v!==null){const S={status:v,message:`Error condition matched for ${m.id}`,data:b},E=pa(),A=E.resolve(v,{errorHandling:m.errorHandling,onError:m.onError});let T=!1;if(A.handler)if(m.loading_strategy==="blocking")E.execute(A.handler,S).catch(L=>{bt.error(`Error executing errorCondition handler for ${m.id}:`,L)}),T=!0;else try{await E.execute(A.handler,S),T=!0}catch(L){bt.error(`Error executing errorCondition handler for ${m.id}:`,L)}return m.fallback!==void 0?(this.dataCache.set(m.id,{data:m.fallback,timestamp:Date.now()}),bt.log(`Using fallback data for ${m.id} (errorCondition)`),{id:m.id,state:"success",data:m.fallback}):{id:m.id,state:"error",error:new Error(`Error condition matched: ${v}`),errorCode:v,errorHandled:T}}if(m.onSuccess)try{const S={data:b,sourceId:m.id};await this.executeOnSuccessHandler(m.onSuccess,S)}catch(S){bt.error(`Error executing onSuccess handler for ${m.id}:`,S)}return{id:m.id,state:"success",data:b}}catch(b){bt.error(`Failed to fetch data source: ${m.id}`,b);const v=b?.response?.status||b?.status||500,S=b?.response?.data,E=S?.message||b.message||"Unknown error",A={status:v,message:E,errors:S?.errors,data:S,statusText:b?.response?.statusText},T=pa(),L=T.resolve(v,{errorHandling:m.errorHandling,onError:m.onError});let M=!1;if(L.handler)if(m.loading_strategy==="blocking")T.execute(L.handler,A).catch(R=>{bt.error(`Error executing error handler for ${m.id}:`,R)}),M=!0;else try{await T.execute(L.handler,A),M=!0}catch(R){bt.error(`Error executing error handler for ${m.id}:`,R)}return m.fallback!==void 0?(this.dataCache.set(m.id,{data:m.fallback,timestamp:Date.now()}),bt.log(`Using fallback data for ${m.id}`),{id:m.id,state:"success",data:m.fallback}):(this.options.onError&&this.options.onError(b,m),{id:m.id,state:"error",error:b,errorCode:v,errorHandled:M})}}))}fetchDataSourcesInBackground(e,a={},r=new URLSearchParams,i){e.filter(u=>u.auto_fetch!==!1&&u.loading_strategy==="background"&&u.type!=="websocket").forEach(u=>{this.fetchDataSource(u,a,r).then(async d=>{this.dataCache.set(u.id,{data:d,timestamp:Date.now()});const f=this.checkErrorCondition(u,d);if(f!==null){const g={status:f,message:`Error condition matched for ${u.id}`,data:d},m=pa(),b=m.resolve(f,{errorHandling:u.errorHandling,onError:u.onError});if(b.handler)try{await m.execute(b.handler,g)}catch(v){bt.error(`Error executing errorCondition handler for ${u.id}:`,v)}u.fallback!==void 0&&(this.dataCache.set(u.id,{data:u.fallback,timestamp:Date.now()}),bt.log(`Using fallback data for ${u.id} (errorCondition)`),i&&i(u.id,u.fallback));return}if(u.onSuccess)try{const g={data:d,sourceId:u.id};await this.executeOnSuccessHandler(u.onSuccess,g)}catch(g){bt.error(`Error executing onSuccess handler for ${u.id}:`,g)}i&&i(u.id,d)}).catch(async d=>{bt.error(`Background fetch failed: ${u.id}`,d);const f=d?.response?.status||d?.status||500,g=d?.response?.data,m=g?.message||d.message||"Unknown error",b={status:f,message:m,errors:g?.errors,data:g,statusText:d?.response?.statusText},v=pa(),S=v.resolve(f,{errorHandling:u.errorHandling,onError:u.onError});if(S.handler)try{await v.execute(S.handler,b)}catch(E){bt.error(`Error executing error handler for ${u.id}:`,E)}if(u.fallback!==void 0){this.dataCache.set(u.id,{data:u.fallback,timestamp:Date.now()}),bt.log(`Using fallback data for ${u.id}`),i&&i(u.id,u.fallback);return}this.options.onError&&this.options.onError(d,u)})})}async fetchDataSource(e,a,r,i,l){switch(e.type){case"api":return this.fetchApiDataSource(e,a,r,i,l);case"static":return e.data;case"route_params":return a;case"query_params":return ny(r);default:throw new Error(`Unknown data source type: ${e.type}`)}}async fetchApiDataSource(e,a,r,i,l){if(this.options.sampleProvider?.has(e.id))return await Promise.resolve(this.options.sampleProvider.resolve(e));if(!e.endpoint)throw new Error(`API data source ${e.id} has no endpoint`);const u={route:a,query:ny(r)};i&&(u._global=i),l&&(u._local=l);let d=Ji(e.endpoint,u,{skipCache:!0});const f=e.method||"GET",m=(e.contentType?typeof e.contentType=="string"&&e.contentType.includes("{{")?Ji(e.contentType,u,{skipCache:!0}):e.contentType:"application/json")==="multipart/form-data";let b=m?{...e.params||{}}:JSON.parse(JSON.stringify(e.params||{}));Object.entries(b).forEach(([E,A])=>{typeof A=="string"&&(b[E]=gc(A,u))}),Object.keys(b).forEach(E=>{b[E]===""&&delete b[E]});const v=N_();let S=null;if(v?.isEnabled()){v.trackDataSourceDefinition({id:e.id,type:e.type,endpoint:d,method:f,autoFetch:e.auto_fetch,initLocal:e.initLocal,initGlobal:e.initGlobal});let E=d;if(f==="GET"&&Object.keys(b).length>0){const A=new URLSearchParams;Object.entries(b).forEach(([L,M])=>{Array.isArray(M)?M.forEach(R=>A.append(L,String(R))):M!=null&&A.append(L,String(M))});const T=A.toString();E=T?`${d}?${T}`:d}S=v.trackRequest(E,f,{requestBody:f!=="GET"?b:void 0,dataSourceId:e.id}),v.trackDataSourceLoading(e.id)}try{let E;const A=e.auth_mode??(e.auth_required===!0?"required":"none"),T=ha.getInstance().isAuthenticated();if(A==="required"&&!T){bt.log(`[DataSourceManager] Skipping ${e.id}: auth_mode is 'required' but no token available`),v?.isEnabled()&&(v.trackDataSourceError(e.id,"Skipped: auth_mode required but not authenticated"),S&&v.failRequest(S,"Skipped: not authenticated"));const M=new Error("Auth required but not authenticated");throw M.response={status:401,statusText:"Unauthorized",data:null},M.status=401,M._authSkipped=!0,M}const L=A==="required"||A==="optional"&&T;if(L){const M=$a(),R=d.startsWith("/api/")?d.substring(4):d.startsWith("/api")?d.substring(4)||"/":d;this.options.onError&&bt.log(`[DataSourceManager] Normalized endpoint: ${d} -> ${R}`);const D=this.getMatchingGlobalHeaders(d,u),U={};e.headers&&Object.entries(e.headers).forEach(([ge,Ee])=>{const Ce=gc(Ee,u);Ce!=null&&Ce!==""&&(U[ge]=String(Ce))});const j={...D,...U},P=Object.keys(j).length>0,X=m?this.toFormData(b):b;switch(f){case"GET":E=await M.get(R,{params:b,...P&&{headers:j}});break;case"POST":P?E=await M.post(R,X,{headers:j}):E=await M.post(R,X);break;case"PUT":P?E=await M.put(R,X,{headers:j}):E=await M.put(R,X);break;case"PATCH":P?E=await M.patch(R,X,{headers:j}):E=await M.patch(R,X);break;case"DELETE":E=await M.delete(R,{params:b,...P&&{headers:j}});break;default:throw new Error(`Unsupported HTTP method: ${f}`)}}else{let M=d;if(f==="GET"){const X=new URLSearchParams(b).toString();M=X?`${d}?${X}`:d}const R={...m?{}:{"Content-Type":"application/json"},Accept:"application/json"};if(typeof window<"u"){const X=localStorage.getItem("g7_locale");X&&(R["Accept-Language"]=X)}const D=this.getMatchingGlobalHeaders(d,u);Object.assign(R,D),e.headers&&Object.entries(e.headers).forEach(([X,ge])=>{const Ee=gc(ge,u);Ee!=null&&Ee!==""&&(R[X]=String(Ee))});let U;f!=="GET"&&(m?(U=this.toFormData(b),delete R["Content-Type"]):U=JSON.stringify(b));const j=await fetch(M,{method:f,headers:R,body:U});let P;try{P=await j.json()}catch{P=null}if(S&&v?.isEnabled()&&(v.completeRequest(S,j.status,P),S=null),!j.ok){v?.isEnabled()&&v.trackDataSourceError(e.id,`HTTP ${j.status}: ${j.statusText}`);const X=new Error(`HTTP error! status: ${j.status}`);throw X.response={status:j.status,statusText:j.statusText,data:P},X.status=j.status,X}E=P,v?.isEnabled()&&v.trackDataSourceLoaded(e.id,E)}return L&&S&&v?.isEnabled()&&(v.completeRequest(S,200,E),v.trackDataSourceLoaded(e.id,E)),E}catch(E){if(S&&v?.isEnabled()){const A=E;A?.response?v.completeRequest(S,A.response.status,A.response.data):v.failRequest(S,E instanceof Error?E.message:String(E)),v.trackDataSourceError(e.id,E instanceof Error?E.message:String(E))}throw E}}getCachedData(e){const a=this.dataCache.get(e);if(!a)return;if(Date.now()-a.timestamp>bc.DATA_CACHE_TTL){this.dataCache.delete(e);return}return a.data}clearCache(){this.dataCache.clear()}subscribeWebSockets(e,a,r={}){const i=[],l=e.filter(u=>u.type==="websocket");return l.length===0||l.forEach(u=>{if(!u.channel||!u.event){bt.warn(`WebSocket source ${u.id} missing channel or event`);return}let d,f;try{d=Ji(u.channel,r,{skipCache:!0}),f=Ji(u.event,r,{skipCache:!0})}catch(b){bt.error(`Failed to resolve WebSocket channel/event for source ${u.id}:`,b);return}const g=b=>!!(!b||b.trim()===""||b.includes("{{")||b.endsWith(".")||b.endsWith(":")||b.startsWith(".")||b.startsWith(":")||b.includes("..")||b.includes("::"));if(g(d)||g(f)){bt.warn(`WebSocket source ${u.id} has invalid channel/event after expression resolution, skipping. Original channel="${u.channel}", resolved="${d}". Original event="${u.event}", resolved="${f}". Available context keys: [${Object.keys(r).join(", ")}]`);return}const m=hc.subscribe(d,f,b=>{const v=u.target_source||u.id;this.dataCache.set(v,{data:b,timestamp:Date.now()}),a(v,b)},{channelType:u.channel_type||"private"});m&&i.push(m)}),i}unsubscribeWebSockets(e){e.length!==0&&e.forEach(a=>{hc.unsubscribe(a)})}async executeOnSuccessHandler(e,a){const r=this.options.actionDispatcher??Zp();if(!r){bt.warn("ActionDispatcher not available, skipping onSuccess handler");return}const i=Array.isArray(e)?e:[e];for(const l of i)try{await r.dispatchAction({type:"click",...l},{data:{response:a}})}catch(u){throw bt.error("Failed to execute onSuccess handler:",u),u}}};$(bc,"DATA_CACHE_TTL",3e5);let va=bc;const I_=new va,gi=ct("ModalDataSourceWrapper");function H_(o,e){if(!o||!e)return o;const r=e.replace(/\?\./g,".").split(/\.(?![^\[]*\])/).flatMap(l=>{const u=l.match(/^([^\[]*)((?:\[\d+\])*)$/);if(u){const[,d,f]=u,g=[];d&&g.push(d);const m=f.match(/\[\d+\]/g);return m&&g.push(...m),g}return[l]}).filter(l=>l!=="");let i=o;for(const l of r){if(i==null)return;if(l.startsWith("[")&&l.endsWith("]")){const u=parseInt(l.slice(1,-1),10);i=i[u]}else i=i[l]}return i}const ay=({isOpen:o,modalId:e,dataSources:a,dataContext:r,globalStateUpdater:i,bindingEngine:l,debug:u=!1,children:d})=>{const[f,g]=N.useState(!1),[m,b]=N.useState(!1),v=N.useRef(!1),S=N.useRef(null);S.current||(S.current=new va);const E=N.useCallback(async()=>{if(!(!a||a.length===0)&&S.current){g(!0);try{const A=r.route||{},T=new URLSearchParams(window.location.search),L=a.map(R=>{let D={...R};if(R.endpoint&&l){const U=l.resolveBindings(R.endpoint,r,{skipCache:!0});D.endpoint=U}if(R.params&&l){const U={};Object.entries(R.params).forEach(([j,P])=>{typeof P=="string"?U[j]=l.resolveBindings(P,r,{skipCache:!0}):U[j]=P}),D.params=U}return D});u&&gi.log(`[ModalDataSourceWrapper] Modal "${e}" fetching data sources:`,L.map(R=>({id:R.id,endpoint:R.endpoint})));const M=await S.current.fetchDataSourcesWithResults(L,A,T);i&&M.forEach(R=>{if(R.state==="success"&&R.data!==void 0){const D=L.find(U=>U.id===R.id);if(D?.initGlobal){const U=R.data?.data??R.data,j=Array.isArray(D.initGlobal)?D.initGlobal:[D.initGlobal];for(const P of j)if(typeof P=="string")i({[P]:U}),u&&gi.log(`[ModalDataSourceWrapper] Modal "${e}" initGlobal: ${R.id}.data -> _global.${P}`);else if(typeof P=="object"&&P.key){const{key:X,path:ge}=P,Ee=ge?H_(U,ge):U;i({[X]:Ee}),u&&gi.log(`Modal "${e}" initGlobal: ${R.id}.data${ge?"."+ge:""} -> _global.${X}`)}}}else R.state==="error"&&gi.error(`Modal "${e}" data source error:`,R.id,R.error)}),u&&gi.log(`Modal "${e}" data sources fetched successfully`)}catch(A){gi.error(`Modal "${e}" data source fetch error:`,A)}finally{g(!1),b(!0)}}},[a,r,i,l,e,u]);return N.useEffect(()=>{if(!a||a.length===0)return;const A=window.__templateApp;return A?.registerModalDataSources&&A.registerModalDataSources(e,a),()=>{A?.unregisterModalDataSources&&A.unregisterModalDataSources(e)}},[e,a]),N.useEffect(()=>{!o&&v.current&&(b(!1),u&&gi.log(`[ModalDataSourceWrapper] Modal "${e}" closed, reset fetch state`)),o&&!v.current&&a&&a.length>0&&!m&&E(),v.current=o},[o,a,m,E,e,u]),ut.jsx(ut.Fragment,{children:d})};class pc extends Error{constructor(a,r,i={}){super(r);$(this,"code");$(this,"userMessageKey");$(this,"showStack");$(this,"icon");$(this,"recoverable");this.name="TemplateEngineError",this.code=a,this.userMessageKey=r,this.showStack=i.showStack??!0,this.icon=i.icon??"fa-circle-exclamation",this.recoverable=i.recoverable??!0,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}getUserMessage(a,r){if(!r||!a)return this.userMessageKey;try{return r.translate(this.userMessageKey,a)}catch{return this.userMessageKey}}}class z_ extends pc{constructor(){super("TEMPLATE_NOT_FOUND","$t:core.errors.template_not_found",{showStack:!1,icon:"fa-paint-brush",recoverable:!1}),this.name="TemplateNotFoundError"}}function ry(o){if(o instanceof pc)return o;if(o instanceof Error){const e=new pc("TEMPLATE_INIT_ERROR",o.message||"$t:core.errors.template_init_error",{showStack:!0,icon:"fa-circle-exclamation",recoverable:!0});return e.stack=o.stack,e}return new pc("TEMPLATE_INIT_ERROR","$t:core.errors.template_init_error",{showStack:!1,icon:"fa-circle-exclamation",recoverable:!0})}const j_=ct("ErrorDisplay");class cf{static render(e,a){const r=document.getElementById(e);if(!r){j_.error(`Container #${e} not found`);return}const i=a.debug&&a.showStack&&a.stackTrace,l=window.matchMedia("(prefers-color-scheme: dark)").matches,u={container:` + `,Gn.error("Error state rendered:",i,r)}getCurrentLayout(){return this.currentLayout}clear(){this.currentLayout=null,this.layoutCache.clear(),Gn.log("Layout data and cache cleared")}}const I_=dt("TranslationContext"),of=I.createContext(null),hc=({children:o,translationEngine:e,translationContext:n})=>{const r=I.useMemo(()=>(l,u)=>{if(u){const d="|"+Object.entries(u).map(([f,g])=>`${f}=${g}`).join("|");return e.translate(l,n,d)}return e.translate(l,n)},[e,n]),i=I.useMemo(()=>({translationEngine:e,translationContext:n,t:r}),[e,n,r]);return ft.jsx(of.Provider,{value:i,children:o})},ty=()=>{const o=I.useContext(of);return o||(I_.warn("TranslationProvider 외부에서 호출되었습니다. 키를 그대로 반환합니다."),{t:e=>e,translationEngine:null,translationContext:null})},Rr=dt("SlotContext"),H_={registerToSlot:()=>{Rr.warn("SlotContext not available: registerToSlot called outside SlotProvider")},unregisterFromSlot:()=>{Rr.warn("SlotContext not available: unregisterFromSlot called outside SlotProvider")},getSlotComponents:()=>[],subscribeToSlot:()=>()=>{},clearAllSlots:()=>{},isEnabled:!1},z_=I.createContext(H_),lf=({children:o})=>{const e=I.useRef(new Map),n=I.useRef(new Map),r=I.useCallback(m=>{const b=n.current.get(m);b&&b.forEach(v=>{try{v()}catch(S){Rr.error(`Slot subscriber error (slotId: ${m}):`,S)}})},[]),i=I.useCallback((m,b,v)=>{if(!m||!b){Rr.warn("registerToSlot: slotId and componentId are required");return}e.current.has(m)||e.current.set(m,new Map);const S=e.current.get(m),_=S.get(b);_&&_.registrationKey===v.registrationKey||(S.set(b,v),Rr.log(`Component registered to slot: ${b} -> ${m} (order: ${v.order})`),r(m))},[r]),l=I.useCallback((m,b)=>{const v=e.current.get(m);v&&v.has(b)&&(v.delete(b),Rr.log(`Component unregistered from slot: ${b} <- ${m}`),v.size===0&&e.current.delete(m),r(m))},[r]),u=I.useCallback(m=>{const b=e.current.get(m);return b?Array.from(b.values()).sort((v,S)=>v.order-S.order):[]},[]),d=I.useCallback((m,b)=>{n.current.has(m)||n.current.set(m,new Set);const v=n.current.get(m);return v.add(b),()=>{v.delete(b),v.size===0&&n.current.delete(m)}},[]),f=I.useCallback(()=>{e.current.forEach((m,b)=>{r(b)}),e.current.clear(),n.current.clear(),Rr.log("All slots cleared")},[r]),g=I.useMemo(()=>({registerToSlot:i,unregisterFromSlot:l,getSlotComponents:u,subscribeToSlot:d,clearAllSlots:f,isEnabled:!0}),[i,l,u,d,f]);return I.useLayoutEffect(()=>{typeof window<"u"&&(window.__slotContextValue=g,Rr.log("SlotContext exposed to window.__slotContextValue"))},[g]),ft.jsx(z_.Provider,{value:g,children:o})};class cf{constructor(){this.notificationCreatedEvent=".Illuminate\\Notifications\\Events\\BroadcastNotificationCreated"}listenForWhisper(e,n){return this.listen(".client-"+e,n)}notification(e){return this.listen(this.notificationCreatedEvent,e)}stopListeningForNotification(e){return this.stopListening(this.notificationCreatedEvent,e)}stopListeningForWhisper(e,n){return this.stopListening(".client-"+e,n)}}class ny{constructor(e){this.namespace=e}format(e){return[".","\\"].includes(e.charAt(0))?e.substring(1):(this.namespace&&(e=this.namespace+"."+e),e.replace(/\./g,"\\"))}setNamespace(e){this.namespace=e}}function j_(o){try{return Reflect.construct(String,[],o),!0}catch{return!1}}class uf extends cf{constructor(e,n,r){super(),this.name=n,this.pusher=e,this.options=r,this.eventFormatter=new ny(this.options.namespace),this.subscribe()}subscribe(){this.subscription=this.pusher.subscribe(this.name)}unsubscribe(){this.pusher.unsubscribe(this.name)}listen(e,n){return this.on(this.eventFormatter.format(e),n),this}listenToAll(e){return this.subscription.bind_global((n,r)=>{if(n.startsWith("pusher:"))return;let i=String(this.options.namespace??"").replace(/\./g,"\\"),l=n.startsWith(i)?n.substring(i.length+1):"."+n;e(l,r)}),this}stopListening(e,n){return n?this.subscription.unbind(this.eventFormatter.format(e),n):this.subscription.unbind(this.eventFormatter.format(e)),this}stopListeningToAll(e){return e?this.subscription.unbind_global(e):this.subscription.unbind_global(),this}subscribed(e){return this.on("pusher:subscription_succeeded",()=>{e()}),this}error(e){return this.on("pusher:subscription_error",n=>{e(n)}),this}on(e,n){return this.subscription.bind(e,n),this}}class ay extends uf{whisper(e,n){return this.pusher.channels.channels[this.name].trigger(`client-${e}`,n),this}}class U_ extends uf{whisper(e,n){return this.pusher.channels.channels[this.name].trigger(`client-${e}`,n),this}}class B_ extends ay{here(e){return this.on("pusher:subscription_succeeded",n=>{e(Object.keys(n.members).map(r=>n.members[r]))}),this}joining(e){return this.on("pusher:member_added",n=>{e(n.info)}),this}whisper(e,n){return this.pusher.channels.channels[this.name].trigger(`client-${e}`,n),this}leaving(e){return this.on("pusher:member_removed",n=>{e(n.info)}),this}}class ry extends cf{constructor(e,n,r){super(),this.events={},this.listeners={},this.name=n,this.socket=e,this.options=r,this.eventFormatter=new ny(this.options.namespace),this.subscribe()}subscribe(){this.socket.emit("subscribe",{channel:this.name,auth:this.options.auth||{}})}unsubscribe(){this.unbind(),this.socket.emit("unsubscribe",{channel:this.name,auth:this.options.auth||{}})}listen(e,n){return this.on(this.eventFormatter.format(e),n),this}stopListening(e,n){return this.unbindEvent(this.eventFormatter.format(e),n),this}subscribed(e){return this.on("connect",n=>{e(n)}),this}error(e){return this}on(e,n){return this.listeners[e]=this.listeners[e]||[],this.events[e]||(this.events[e]=(r,i)=>{this.name===r&&this.listeners[e]&&this.listeners[e].forEach(l=>l(i))},this.socket.on(e,this.events[e])),this.listeners[e].push(n),this}unbind(){Object.keys(this.events).forEach(e=>{this.unbindEvent(e)})}unbindEvent(e,n){this.listeners[e]=this.listeners[e]||[],n&&(this.listeners[e]=this.listeners[e].filter(r=>r!==n)),(!n||this.listeners[e].length===0)&&(this.events[e]&&(this.socket.removeListener(e,this.events[e]),delete this.events[e]),delete this.listeners[e])}}class iy extends ry{whisper(e,n){return this.socket.emit("client event",{channel:this.name,event:`client-${e}`,data:n}),this}}class P_ extends iy{here(e){return this.on("presence:subscribed",n=>{e(n.map(r=>r.user_info))}),this}joining(e){return this.on("presence:joining",n=>e(n.user_info)),this}whisper(e,n){return this.socket.emit("client event",{channel:this.name,event:`client-${e}`,data:n}),this}leaving(e){return this.on("presence:leaving",n=>e(n.user_info)),this}}class gc extends cf{subscribe(){}unsubscribe(){}listen(e,n){return this}listenToAll(e){return this}stopListening(e,n){return this}subscribed(e){return this}error(e){return this}on(e,n){return this}}class sy extends gc{whisper(e,n){return this}}class q_ extends gc{whisper(e,n){return this}}class G_ extends sy{here(e){return this}joining(e){return this}whisper(e,n){return this}leaving(e){return this}}const wc=class wc{constructor(e){this.setOptions(e),this.connect()}setOptions(e){this.options={...wc._defaultOptions,...e,broadcaster:e.broadcaster};let n=this.csrfToken();n&&(this.options.auth.headers["X-CSRF-TOKEN"]=n,this.options.userAuthentication.headers["X-CSRF-TOKEN"]=n),n=this.options.bearerToken,n&&(this.options.auth.headers.Authorization="Bearer "+n,this.options.userAuthentication.headers.Authorization="Bearer "+n)}csrfToken(){return typeof window<"u"&&window.Laravel?.csrfToken?window.Laravel.csrfToken:this.options.csrfToken?this.options.csrfToken:typeof document<"u"&&typeof document.querySelector=="function"?document.querySelector('meta[name="csrf-token"]')?.getAttribute("content")??null:null}};wc._defaultOptions={auth:{headers:{}},authEndpoint:"/broadcasting/auth",userAuthentication:{endpoint:"/broadcasting/user-auth",headers:{}},csrfToken:null,bearerToken:null,host:null,key:null,namespace:"App.Events"};let Eo=wc;class pc extends Eo{constructor(){super(...arguments),this.channels={}}connect(){if(typeof this.options.client<"u")this.pusher=this.options.client;else if(this.options.Pusher)this.pusher=new this.options.Pusher(this.options.key,this.options);else if(typeof window<"u"&&typeof window.Pusher<"u")this.pusher=new window.Pusher(this.options.key,this.options);else throw new Error("Pusher client not found. Should be globally available or passed via options.client")}signin(){this.pusher.signin()}listen(e,n,r){return this.channel(e).listen(n,r)}channel(e){return this.channels[e]||(this.channels[e]=new uf(this.pusher,e,this.options)),this.channels[e]}privateChannel(e){return this.channels["private-"+e]||(this.channels["private-"+e]=new ay(this.pusher,"private-"+e,this.options)),this.channels["private-"+e]}encryptedPrivateChannel(e){return this.channels["private-encrypted-"+e]||(this.channels["private-encrypted-"+e]=new U_(this.pusher,"private-encrypted-"+e,this.options)),this.channels["private-encrypted-"+e]}presenceChannel(e){return this.channels["presence-"+e]||(this.channels["presence-"+e]=new B_(this.pusher,"presence-"+e,this.options)),this.channels["presence-"+e]}leave(e){[e,"private-"+e,"private-encrypted-"+e,"presence-"+e].forEach(n=>{this.leaveChannel(n)})}leaveChannel(e){this.channels[e]&&(this.channels[e].unsubscribe(),delete this.channels[e])}socketId(){return this.pusher.connection.socket_id}connectionStatus(){const e=this.pusher.connection.state;switch(e){case"connected":case"connecting":return e;case"failed":case"unavailable":return"failed";default:return"disconnected"}}onConnectionChange(e){const n=()=>{e(this.connectionStatus())},r=["state_change","connected","disconnected"];return r.forEach(i=>{this.pusher.connection.bind(i,n)}),()=>{r.forEach(i=>{this.pusher.connection.unbind(i,n)})}}disconnect(){this.pusher.disconnect()}}class V_ extends Eo{constructor(){super(...arguments),this.channels={}}connect(){const e=this.getSocketIO();this.socket=e(this.options.host??void 0,this.options),this.socket.io.on("reconnect",()=>{Object.values(this.channels).forEach(n=>{n.subscribe()})})}getSocketIO(){if(typeof this.options.client<"u")return this.options.client;if(typeof window<"u"&&typeof window.io<"u")return window.io;throw new Error("Socket.io client not found. Should be globally available or passed via options.client")}listen(e,n,r){return this.channel(e).listen(n,r)}channel(e){return this.channels[e]||(this.channels[e]=new ry(this.socket,e,this.options)),this.channels[e]}privateChannel(e){return this.channels["private-"+e]||(this.channels["private-"+e]=new iy(this.socket,"private-"+e,this.options)),this.channels["private-"+e]}presenceChannel(e){return this.channels["presence-"+e]||(this.channels["presence-"+e]=new P_(this.socket,"presence-"+e,this.options)),this.channels["presence-"+e]}leave(e){[e,"private-"+e,"presence-"+e].forEach(n=>{this.leaveChannel(n)})}leaveChannel(e){this.channels[e]&&(this.channels[e].unsubscribe(),delete this.channels[e])}socketId(){return this.socket.id}connectionStatus(){return this.socket.connected?"connected":this.socket.io._reconnecting?"reconnecting":this.socket.id!==void 0?"disconnected":"connecting"}onConnectionChange(e){const n=()=>{e(this.connectionStatus())},r=["connect","disconnect","connect_error","reconnect_attempt","reconnect","reconnect_error","reconnect_failed"];return r.forEach(i=>{this.socket.on(i,n)}),()=>{r.forEach(i=>{this.socket.off(i,n)})}}disconnect(){this.socket.disconnect()}}class oy extends Eo{constructor(){super(...arguments),this.channels={}}connect(){}listen(e,n,r){return new gc}channel(e){return new gc}privateChannel(e){return new sy}encryptedPrivateChannel(e){return new q_}presenceChannel(e){return new G_}leave(e){}leaveChannel(e){}socketId(){return"fake-socket-id"}connectionStatus(){return"connected"}onConnectionChange(e){return()=>{}}disconnect(){}}class F_{constructor(e){this.options=e,this.connect(),this.options.withoutInterceptors||this.registerInterceptors()}channel(e){return this.connector.channel(e)}connect(){if(this.options.broadcaster==="reverb")this.connector=new pc({...this.options,cluster:""});else if(this.options.broadcaster==="pusher")this.connector=new pc(this.options);else if(this.options.broadcaster==="ably")this.connector=new pc({...this.options,cluster:"",broadcaster:"pusher"});else if(this.options.broadcaster==="socket.io")this.connector=new V_(this.options);else if(this.options.broadcaster==="null")this.connector=new oy(this.options);else if(typeof this.options.broadcaster=="function"&&j_(this.options.broadcaster))this.connector=new this.options.broadcaster(this.options);else throw new Error(`Broadcaster ${typeof this.options.broadcaster} ${String(this.options.broadcaster)} is not supported.`)}disconnect(){this.connector.disconnect()}join(e){return this.connector.presenceChannel(e)}leave(e){this.connector.leave(e)}leaveChannel(e){this.connector.leaveChannel(e)}leaveAllChannels(){for(const e in this.connector.channels)this.leaveChannel(e)}listen(e,n,r){return this.connector.listen(e,n,r)}private(e){return this.connector.privateChannel(e)}encryptedPrivate(e){if(this.connectorSupportsEncryptedPrivateChannels(this.connector))return this.connector.encryptedPrivateChannel(e);throw new Error(`Broadcaster ${typeof this.options.broadcaster} ${String(this.options.broadcaster)} does not support encrypted private channels.`)}connectorSupportsEncryptedPrivateChannels(e){return e instanceof pc||e instanceof oy}socketId(){return this.connector.socketId()}connectionStatus(){return this.connector.connectionStatus()}registerInterceptors(){typeof Vue<"u"&&Vue?.http&&this.registerVueRequestInterceptor(),typeof axios=="function"&&this.registerAxiosRequestInterceptor(),typeof jQuery=="function"&&this.registerjQueryAjaxSetup(),typeof Turbo=="object"&&this.registerTurboRequestInterceptor()}registerVueRequestInterceptor(){Vue.http.interceptors.push((e,n)=>{this.socketId()&&e.headers.set("X-Socket-ID",this.socketId()),n()})}registerAxiosRequestInterceptor(){axios.interceptors.request.use(e=>(this.socketId()&&(e.headers["X-Socket-Id"]=this.socketId()),e))}registerjQueryAjaxSetup(){typeof jQuery.ajax<"u"&&jQuery.ajaxPrefilter((e,n,r)=>{this.socketId()&&r.setRequestHeader("X-Socket-Id",this.socketId())})}registerTurboRequestInterceptor(){document.addEventListener("turbo:before-fetch-request",e=>{e.detail.fetchOptions.headers["X-Socket-Id"]=this.socketId()})}}var df={exports:{}};var ly;function K_(){return ly||(ly=1,(function(o,e){(function(r,i){o.exports=i()})(self,()=>(()=>{var n={594(u,d){var f=this&&this.__extends||(function(){var M=function(T,D){return M=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(j,H){j.__proto__=H}||function(j,H){for(var P in H)H.hasOwnProperty(P)&&(j[P]=H[P])},M(T,D)};return function(T,D){M(T,D);function j(){this.constructor=T}T.prototype=D===null?Object.create(D):(j.prototype=D.prototype,new j)}})();Object.defineProperty(d,"__esModule",{value:!0});var g=256,m=(function(){function M(T){T===void 0&&(T="="),this._paddingCharacter=T}return M.prototype.encodedLength=function(T){return this._paddingCharacter?(T+2)/3*4|0:(T*8+5)/6|0},M.prototype.encode=function(T){for(var D="",j=0;j>>18&63),D+=this._encodeByte(H>>>12&63),D+=this._encodeByte(H>>>6&63),D+=this._encodeByte(H>>>0&63)}var P=T.length-j;if(P>0){var H=T[j]<<16|(P===2?T[j+1]<<8:0);D+=this._encodeByte(H>>>18&63),D+=this._encodeByte(H>>>12&63),P===2?D+=this._encodeByte(H>>>6&63):D+=this._paddingCharacter||"",D+=this._paddingCharacter||""}return D},M.prototype.maxDecodedLength=function(T){return this._paddingCharacter?T/4*3|0:(T*6+7)/8|0},M.prototype.decodedLength=function(T){return this.maxDecodedLength(T.length-this._getPaddingLength(T))},M.prototype.decode=function(T){if(T.length===0)return new Uint8Array(0);for(var D=this._getPaddingLength(T),j=T.length-D,H=new Uint8Array(this.maxDecodedLength(j)),P=0,X=0,pe=0,_e=0,we=0,Me=0,qe=0;X>>4,H[P++]=we<<4|Me>>>2,H[P++]=Me<<6|qe,pe|=_e&g,pe|=we&g,pe|=Me&g,pe|=qe&g;if(X>>4,pe|=_e&g,pe|=we&g),X>>2,pe|=Me&g),X>>8&6,D+=51-T>>>8&-75,D+=61-T>>>8&-15,D+=62-T>>>8&3,String.fromCharCode(D)},M.prototype._decodeChar=function(T){var D=g;return D+=(42-T&T-44)>>>8&-g+T-43+62,D+=(46-T&T-48)>>>8&-g+T-47+63,D+=(47-T&T-58)>>>8&-g+T-48+52,D+=(64-T&T-91)>>>8&-g+T-65+0,D+=(96-T&T-123)>>>8&-g+T-97+26,D},M.prototype._getPaddingLength=function(T){var D=0;if(this._paddingCharacter){for(var j=T.length-1;j>=0&&T[j]===this._paddingCharacter;j--)D++;if(T.length<4||D>2)throw new Error("Base64Coder: incorrect padding")}return D},M})();d.Coder=m;var b=new m;function v(M){return b.encode(M)}d.encode=v;function S(M){return b.decode(M)}d.decode=S;var _=(function(M){f(T,M);function T(){return M!==null&&M.apply(this,arguments)||this}return T.prototype._encodeByte=function(D){var j=D;return j+=65,j+=25-D>>>8&6,j+=51-D>>>8&-75,j+=61-D>>>8&-13,j+=62-D>>>8&49,String.fromCharCode(j)},T.prototype._decodeChar=function(D){var j=g;return j+=(44-D&D-46)>>>8&-g+D-45+62,j+=(94-D&D-96)>>>8&-g+D-95+63,j+=(47-D&D-58)>>>8&-g+D-48+52,j+=(64-D&D-91)>>>8&-g+D-65+0,j+=(96-D&D-123)>>>8&-g+D-97+26,j},T})(m);d.URLSafeCoder=_;var x=new _;function k(M){return x.encode(M)}d.encodeURLSafe=k;function O(M){return x.decode(M)}d.decodeURLSafe=O,d.encodedLength=function(M){return b.encodedLength(M)},d.maxDecodedLength=function(M){return b.maxDecodedLength(M)},d.decodedLength=function(M){return b.decodedLength(M)}},978(u,d){var f="utf8: invalid source encoding";function g(m){for(var b=[],v=0;v=m.length)throw new Error(f);var x=m[++v];if((x&192)!==128)throw new Error(f);S=(S&31)<<6|x&63,_=128}else if(S<240){if(v>=m.length-1)throw new Error(f);var x=m[++v],k=m[++v];if((x&192)!==128||(k&192)!==128)throw new Error(f);S=(S&15)<<12|(x&63)<<6|k&63,_=2048}else if(S<248){if(v>=m.length-2)throw new Error(f);var x=m[++v],k=m[++v],O=m[++v];if((x&192)!==128||(k&192)!==128||(O&192)!==128)throw new Error(f);S=(S&15)<<18|(x&63)<<12|(k&63)<<6|O&63,_=65536}else throw new Error(f);if(S<_||S>=55296&&S<=57343)throw new Error(f);if(S>=65536){if(S>1114111)throw new Error(f);S-=65536,b.push(String.fromCharCode(55296|S>>10)),S=56320|S&1023}}b.push(String.fromCharCode(S))}return b.join("")}d.D4=g},721(u,d,f){u.exports=f(207).default},207(u,d,f){f.d(d,{default:()=>Ss});class g{constructor(y,w){this.lastId=0,this.prefix=y,this.name=w}create(y){this.lastId++;var w=this.lastId,L=this.prefix+w,N=this.name+"["+w+"]",te=!1,ye=function(){te||(y.apply(null,arguments),te=!0)};return this[w]=ye,{number:w,id:L,name:N,callback:ye}}remove(y){delete this[y.number]}}var m=new g("_pusher_script_","Pusher.ScriptReceivers"),b={VERSION:"8.6.0",PROTOCOL:7,wsPort:80,wssPort:443,wsPath:"",httpHost:"sockjs.pusher.com",httpPort:80,httpsPort:443,httpPath:"/pusher",stats_host:"stats.pusher.com",authEndpoint:"/pusher/auth",authTransport:"ajax",activityTimeout:12e4,pongTimeout:3e4,unavailableTimeout:1e4,userAuthentication:{endpoint:"/pusher/user-auth",transport:"ajax"},channelAuthorization:{endpoint:"/pusher/auth",transport:"ajax"},cdn_http:"http://js.pusher.com",cdn_https:"https://js.pusher.com",dependency_suffix:""};const v=b;class S{constructor(y){this.options=y,this.receivers=y.receivers||m,this.loading={}}load(y,w,L){var N=this;if(N.loading[y]&&N.loading[y].length>0)N.loading[y].push(L);else{N.loading[y]=[L];var te=Be.createScriptRequest(N.getPath(y,w)),ye=N.receivers.create(function(Ne){if(N.receivers.remove(ye),N.loading[y]){var Fe=N.loading[y];delete N.loading[y];for(var lt=function(jt){jt||te.cleanup()},pt=0;pt>>6)+Q(128|y&63):Q(224|y>>>12&15)+Q(128|y>>>6&63)+Q(128|y&63)},ae=function(E){return E.replace(/[^\x00-\x7F]/g,ve)},ge=function(E){var y=[0,2,1][E.length%3],w=E.charCodeAt(0)<<16|(E.length>1?E.charCodeAt(1):0)<<8|(E.length>2?E.charCodeAt(2):0),L=[fe.charAt(w>>>18),fe.charAt(w>>>12&63),y>=2?"=":fe.charAt(w>>>6&63),y>=1?"=":fe.charAt(w&63)];return L.join("")},A=typeof window<"u"&&window.btoa||function(E){return E.replace(/[\s\S]{1,3}/g,ge)};class K{constructor(y,w,L,N){this.clear=w,this.timer=y(()=>{this.timer&&(this.timer=N(this.timer))},L)}isRunning(){return this.timer!==null}ensureAborted(){this.timer&&(this.clear(this.timer),this.timer=null)}}const ue=K;function he(E){window.clearTimeout(E)}function le(E){window.clearInterval(E)}class de extends ue{constructor(y,w){super(setTimeout,he,y,function(L){return w(),null})}}class Oe extends ue{constructor(y,w){super(setInterval,le,y,function(L){return w(),L})}}var He={now(){return Date.now?Date.now():new Date().valueOf()},defer(E){return new de(0,E)},method(E,...y){var w=Array.prototype.slice.call(arguments,1);return function(L){return L[E].apply(L,w.concat(arguments))}}};const Pe=He;function ke(E,...y){for(var w=0;w{window.console&&window.console.log&&window.console.log(y)}}debug(...y){this.log(this.globalLog,y)}warn(...y){this.log(this.globalLogWarn,y)}error(...y){this.log(this.globalLogError,y)}globalLogWarn(y){window.console&&window.console.warn?window.console.warn(y):this.globalLog(y)}globalLogError(y){window.console&&window.console.error?window.console.error(y):this.globalLogWarn(y)}log(y,...w){var L=Ot.apply(this,arguments);Ss.log?Ss.log(L):Ss.logToConsole&&y.bind(this)(L)}}const tt=new sn;var na=function(E,y,w,L,N){(w.headers!==void 0||w.headersProvider!=null)&&tt.warn(`To send headers with the ${L.toString()} request, you must use AJAX, rather than JSONP.`);var te=E.nextAuthCallbackID.toString();E.nextAuthCallbackID++;var ye=E.getDocument(),Ne=ye.createElement("script");E.auth_callbacks[te]=function(pt){N(null,pt)};var Fe="Pusher.auth_callbacks['"+te+"']";Ne.src=w.endpoint+"?callback="+encodeURIComponent(Fe)+"&"+y;var lt=ye.getElementsByTagName("head")[0]||ye.documentElement;lt.insertBefore(Ne,lt.firstChild)};const kn=na;class nr{constructor(y){this.src=y}send(y){var w=this,L="Error loading "+w.src;w.script=document.createElement("script"),w.script.id=y.id,w.script.src=w.src,w.script.type="text/javascript",w.script.charset="UTF-8",w.script.addEventListener?(w.script.onerror=function(){y.callback(L)},w.script.onload=function(){y.callback(null)}):w.script.onreadystatechange=function(){(w.script.readyState==="loaded"||w.script.readyState==="complete")&&y.callback(null)},w.script.async===void 0&&document.attachEvent&&/opera/i.test(navigator.userAgent)?(w.errorScript=document.createElement("script"),w.errorScript.id=y.id+"_error",w.errorScript.text=y.name+"('"+L+"');",w.script.async=w.errorScript.async=!1):w.script.async=!0;var N=document.getElementsByTagName("head")[0];N.insertBefore(w.script,N.firstChild),w.errorScript&&N.insertBefore(w.errorScript,w.script.nextSibling)}cleanup(){this.script&&(this.script.onload=this.script.onerror=null,this.script.onreadystatechange=null),this.script&&this.script.parentNode&&this.script.parentNode.removeChild(this.script),this.errorScript&&this.errorScript.parentNode&&this.errorScript.parentNode.removeChild(this.errorScript),this.script=null,this.errorScript=null}}class _a{constructor(y,w){this.url=y,this.data=w}send(y){if(!this.request){var w=Dr(this.data),L=this.url+"/"+y.number+"?"+w;this.request=Be.createScriptRequest(L),this.request.send(y)}}cleanup(){this.request&&this.request.cleanup()}}var on=function(E,y){return function(w,L){var N="http"+(y?"s":"")+"://",te=N+(E.host||E.options.host)+E.options.path,ye=Be.createJSONPRequest(te,w),Ne=Be.ScriptReceivers.create(function(Fe,lt){m.remove(Ne),ye.cleanup(),lt&<.host&&(E.host=lt.host),L&&L(Fe,lt)});ye.send(Ne)}},Dn={name:"jsonp",getAgent:on};const q=Dn;function ie(E,y,w){var L=E+(y.useTLS?"s":""),N=y.useTLS?y.hostTLS:y.hostNonTLS;return L+"://"+N+w}function oe(E,y){var w="/app/"+E,L="?protocol="+v.PROTOCOL+"&client=js&version="+v.VERSION+(y?"&"+y:"");return w+L}var Z={getInitial:function(E,y){var w=(y.httpPath||"")+oe(E,"flash=false");return ie("ws",y,w)}},be={getInitial:function(E,y){var w=(y.httpPath||"/pusher")+oe(E);return ie("http",y,w)}},me={getInitial:function(E,y){return ie("http",y,y.httpPath||"/pusher")},getPath:function(E,y){return oe(E)}};class Te{constructor(){this._callbacks={}}get(y){return this._callbacks[xe(y)]}add(y,w,L){var N=xe(y);this._callbacks[N]=this._callbacks[N]||[],this._callbacks[N].push({fn:w,context:L})}remove(y,w,L){if(!y&&!w&&!L){this._callbacks={};return}var N=y?[xe(y)]:vt(this._callbacks);w||L?this.removeCallback(N,w,L):this.removeAllCallbacks(N)}removeCallback(y,w,L){Ee(y,function(N){this._callbacks[N]=qt(this._callbacks[N]||[],function(te){return w&&w!==te.fn||L&&L!==te.context}),this._callbacks[N].length===0&&delete this._callbacks[N]},this)}removeAllCallbacks(y){Ee(y,function(w){delete this._callbacks[w]},this)}}function xe(E){return"_"+E}class je{constructor(y){this.callbacks=new Te,this.global_callbacks=[],this.failThrough=y}bind(y,w,L){return this.callbacks.add(y,w,L),this}bind_global(y){return this.global_callbacks.push(y),this}unbind(y,w,L){return this.callbacks.remove(y,w,L),this}unbind_global(y){return y?(this.global_callbacks=qt(this.global_callbacks||[],w=>w!==y),this):(this.global_callbacks=[],this)}unbind_all(){return this.unbind(),this.unbind_global(),this}emit(y,w,L){for(var N=0;N0)for(var N=0;N{this.onError(w),this.changeState("closed")}),!1}return this.bindListeners(),tt.debug("Connecting",{transport:this.name,url:y}),this.changeState("connecting"),!0}close(){return this.socket?(this.socket.close(),!0):!1}send(y){return this.state==="open"?(Pe.defer(()=>{this.socket&&this.socket.send(y)}),!0):!1}ping(){this.state==="open"&&this.supportsPing()&&this.socket.ping()}onOpen(){this.hooks.beforeOpen&&this.hooks.beforeOpen(this.socket,this.hooks.urls.getPath(this.key,this.options)),this.changeState("open"),this.socket.onopen=void 0}onError(y){this.emit("error",{type:"WebSocketError",error:y}),this.timeline.error(this.buildTimelineMessage({error:y.toString()}))}onClose(y){y?this.changeState("closed",{code:y.code,reason:y.reason,wasClean:y.wasClean}):this.changeState("closed"),this.unbindListeners(),this.socket=void 0}onMessage(y){this.emit("message",y)}onActivity(){this.emit("activity")}bindListeners(){this.socket.onopen=()=>{this.onOpen()},this.socket.onerror=y=>{this.onError(y)},this.socket.onclose=y=>{this.onClose(y)},this.socket.onmessage=y=>{this.onMessage(y)},this.supportsPing()&&(this.socket.onactivity=()=>{this.onActivity()})}unbindListeners(){this.socket&&(this.socket.onopen=void 0,this.socket.onerror=void 0,this.socket.onclose=void 0,this.socket.onmessage=void 0,this.supportsPing()&&(this.socket.onactivity=void 0))}changeState(y,w){this.state=y,this.timeline.info(this.buildTimelineMessage({state:y,params:w})),this.emit(y,w)}buildTimelineMessage(y){return ke({cid:this.id},y)}}class $e{constructor(y){this.hooks=y}isSupported(y){return this.hooks.isSupported(y)}createConnection(y,w,L,N){return new ze(this.hooks,y,w,L,N)}}var De=new $e({urls:Z,handlesActivityChecks:!1,supportsPing:!1,isInitialized:function(){return!!Be.getWebSocketAPI()},isSupported:function(){return!!Be.getWebSocketAPI()},getSocket:function(E){return Be.createWebSocket(E)}}),Ye={urls:be,handlesActivityChecks:!1,supportsPing:!0,isInitialized:function(){return!0}},Ke=ke({getSocket:function(E){return Be.HTTPFactory.createStreamingSocket(E)}},Ye),Ae=ke({getSocket:function(E){return Be.HTTPFactory.createPollingSocket(E)}},Ye),Re={isSupported:function(){return Be.isXHRSupported()}},Ue=new $e(ke({},Ke,Re)),ot=new $e(ke({},Ae,Re)),At={ws:De,xhr_streaming:Ue,xhr_polling:ot};const Qt=At;var Kt=new $e({file:"sockjs",urls:me,handlesActivityChecks:!0,supportsPing:!1,isSupported:function(){return!0},isInitialized:function(){return window.SockJS!==void 0},getSocket:function(E,y){return new window.SockJS(E,null,{js_path:x.getPath("sockjs",{useTLS:y.useTLS}),ignore_null_origin:y.ignoreNullOrigin})},beforeOpen:function(E,y){E.send(JSON.stringify({path:y}))}}),Fn={isSupported:function(E){var y=Be.isXDRSupported(E.useTLS);return y}},Nn=new $e(ke({},Ke,Fn)),ln=new $e(ke({},Ae,Fn));Qt.xdr_streaming=Nn,Qt.xdr_polling=ln,Qt.sockjs=Kt;const xn=Qt;class Or extends je{constructor(){super();var y=this;typeof window<"u"&&window.addEventListener!==void 0&&(window.addEventListener("online",function(){y.emit("online")},!1),window.addEventListener("offline",function(){y.emit("offline")},!1))}isOnline(){return window.navigator.onLine===void 0?!0:window.navigator.onLine}}var Lo=new Or;class bf{constructor(y,w,L){this.manager=y,this.transport=w,this.minPingDelay=L.minPingDelay,this.maxPingDelay=L.maxPingDelay,this.pingDelay=void 0}createConnection(y,w,L,N){N=ke({},N,{activityTimeout:this.pingDelay});var te=this.transport.createConnection(y,w,L,N),ye=null,Ne=function(){te.unbind("open",Ne),te.bind("closed",Fe),ye=Pe.now()},Fe=lt=>{if(te.unbind("closed",Fe),lt.code===1002||lt.code===1003)this.manager.reportDeath();else if(!lt.wasClean&&ye){var pt=Pe.now()-ye;pt<2*this.maxPingDelay&&(this.manager.reportDeath(),this.pingDelay=Math.max(pt/2,this.minPingDelay))}};return te.bind("open",Ne),te}isSupported(y){return this.manager.isAlive()&&this.transport.isSupported(y)}}const Ec={decodeMessage:function(E){try{var y=JSON.parse(E.data),w=y.data;if(typeof w=="string")try{w=JSON.parse(y.data)}catch{}var L={event:y.event,channel:y.channel,data:w};return y.user_id&&(L.user_id=y.user_id),L}catch(N){throw{type:"MessageParseError",error:N,data:E.data}}},encodeMessage:function(E){return JSON.stringify(E)},processHandshake:function(E){var y=Ec.decodeMessage(E);if(y.event==="pusher:connection_established"){if(!y.data.activity_timeout)throw"No activity timeout specified in handshake";return{action:"connected",id:y.data.socket_id,activityTimeout:y.data.activity_timeout*1e3}}else{if(y.event==="pusher:error")return{action:this.getCloseAction(y.data),error:this.getCloseError(y.data)};throw"Invalid handshake"}},getCloseAction:function(E){return E.code<4e3?E.code>=1002&&E.code<=1004?"backoff":null:E.code===4e3?"tls_only":E.code<4100?"refused":E.code<4200?"backoff":E.code<4300?"retry":"refused"},getCloseError:function(E){return E.code!==1e3&&E.code!==1001?{type:"PusherError",data:{code:E.code,message:E.reason||E.message}}:null}},Pa=Ec;class vi extends je{constructor(y,w){super(),this.id=y,this.transport=w,this.activityTimeout=w.activityTimeout,this.bindListeners()}handlesActivityChecks(){return this.transport.handlesActivityChecks()}send(y){return this.transport.send(y)}send_event(y,w,L){var N={event:y,data:w};return L&&(N.channel=L),tt.debug("Event sent",N),this.send(Pa.encodeMessage(N))}ping(){this.transport.supportsPing()?this.transport.ping():this.send_event("pusher:ping",{})}close(){this.transport.close()}bindListeners(){var y={message:L=>{var N;try{N=Pa.decodeMessage(L)}catch(te){this.emit("error",{type:"MessageParseError",error:te,data:L.data})}if(N!==void 0){switch(tt.debug("Event recd",N),N.event){case"pusher:error":this.emit("error",{type:"PusherError",data:N.data});break;case"pusher:ping":this.emit("ping");break;case"pusher:pong":this.emit("pong");break}this.emit("message",N)}},activity:()=>{this.emit("activity")},error:L=>{this.emit("error",L)},closed:L=>{w(),L&&L.code&&this.handleCloseEvent(L),this.transport=null,this.emit("closed")}},w=()=>{Ct(y,(L,N)=>{this.transport.unbind(N,L)})};Ct(y,(L,N)=>{this.transport.bind(N,L)})}handleCloseEvent(y){var w=Pa.getCloseAction(y),L=Pa.getCloseError(y);L&&this.emit("error",L),w&&this.emit(w,{action:w,error:L})}}class Mo{constructor(y,w){this.transport=y,this.callback=w,this.bindListeners()}close(){this.unbindListeners(),this.transport.close()}bindListeners(){this.onMessage=y=>{this.unbindListeners();var w;try{w=Pa.processHandshake(y)}catch(L){this.finish("error",{error:L}),this.transport.close();return}w.action==="connected"?this.finish("connected",{connection:new vi(w.id,this.transport),activityTimeout:w.activityTimeout}):(this.finish(w.action,{error:w.error}),this.transport.close())},this.onClosed=y=>{this.unbindListeners();var w=Pa.getCloseAction(y)||"backoff",L=Pa.getCloseError(y);this.finish(w,{error:L})},this.transport.bind("message",this.onMessage),this.transport.bind("closed",this.onClosed)}unbindListeners(){this.transport.unbind("message",this.onMessage),this.transport.unbind("closed",this.onClosed)}finish(y,w){this.callback(ke({transport:this.transport,action:y},w))}}class Lr{constructor(y,w){this.timeline=y,this.options=w||{}}send(y,w){this.timeline.isEmpty()||this.timeline.send(Be.TimelineTransport.getAgent(this,y),w)}}class qa extends je{constructor(y,w){super(function(L,N){tt.debug("No callbacks on "+y+" for "+L)}),this.name=y,this.pusher=w,this.subscribed=!1,this.subscriptionPending=!1,this.subscriptionCancelled=!1}authorize(y,w){return w(null,{auth:""})}trigger(y,w){if(y.indexOf("client-")!==0)throw new D("Event '"+y+"' does not start with 'client-'");if(!this.subscribed){var L=M.buildLogSuffix("triggeringClientEvents");tt.warn(`Client event triggered before channel 'subscription_succeeded' event . ${L}`)}return this.pusher.send_event(y,w,this.name)}disconnect(){this.subscribed=!1,this.subscriptionPending=!1}handleEvent(y){var w=y.event,L=y.data;if(w==="pusher_internal:subscription_succeeded")this.handleSubscriptionSucceededEvent(y);else if(w==="pusher_internal:subscription_count")this.handleSubscriptionCountEvent(y);else if(w.indexOf("pusher_internal:")!==0){var N={};this.emit(w,L,N)}}handleSubscriptionSucceededEvent(y){this.subscriptionPending=!1,this.subscribed=!0,this.subscriptionCancelled?this.pusher.unsubscribe(this.name):this.emit("pusher:subscription_succeeded",y.data)}handleSubscriptionCountEvent(y){y.data.subscription_count&&(this.subscriptionCount=y.data.subscription_count),this.emit("pusher:subscription_count",y.data)}subscribe(){this.subscribed||(this.subscriptionPending=!0,this.subscriptionCancelled=!1,this.authorize(this.pusher.connection.socket_id,(y,w)=>{y?(this.subscriptionPending=!1,tt.error(y.toString()),this.emit("pusher:subscription_error",Object.assign({},{type:"AuthError",error:y.message},y instanceof Me?{status:y.status}:{}))):this.pusher.send_event("pusher:subscribe",{auth:w.auth,channel_data:w.channel_data,channel:this.name})}))}unsubscribe(){this.subscribed=!1,this.pusher.send_event("pusher:unsubscribe",{channel:this.name})}cancelSubscription(){this.subscriptionCancelled=!0}reinstateSubscription(){this.subscriptionCancelled=!1}}class ar extends qa{authorize(y,w){return this.pusher.config.channelAuthorizer({channelName:this.name,socketId:y},w)}}class Mr{constructor(){this.reset()}get(y){return Object.prototype.hasOwnProperty.call(this.members,y)?{id:y,info:this.members[y]}:null}each(y){Ct(this.members,(w,L)=>{y(this.get(L))})}setMyID(y){this.myID=y}onSubscription(y){this.members=y.presence.hash,this.count=y.presence.count,this.me=this.get(this.myID)}addMember(y){return this.get(y.user_id)===null&&this.count++,this.members[y.user_id]=y.user_info,this.get(y.user_id)}removeMember(y){var w=this.get(y.user_id);return w&&(delete this.members[y.user_id],this.count--),w}reset(){this.members={},this.count=0,this.myID=null,this.me=null}}var Zt=function(E,y,w,L){function N(te){return te instanceof w?te:new w(function(ye){ye(te)})}return new(w||(w=Promise))(function(te,ye){function Ne(pt){try{lt(L.next(pt))}catch(jt){ye(jt)}}function Fe(pt){try{lt(L.throw(pt))}catch(jt){ye(jt)}}function lt(pt){pt.done?te(pt.value):N(pt.value).then(Ne,Fe)}lt((L=L.apply(E,y||[])).next())})};class _c extends ar{constructor(y,w){super(y,w),this.members=new Mr}authorize(y,w){super.authorize(y,(L,N)=>Zt(this,void 0,void 0,function*(){if(!L)if(N=N,N.channel_data!=null){var te=JSON.parse(N.channel_data);this.members.setMyID(te.user_id)}else if(yield this.pusher.user.signinDonePromise,this.pusher.user.user_data!=null)this.members.setMyID(this.pusher.user.user_data.id);else{let ye=M.buildLogSuffix("authorizationEndpoint");tt.error(`Invalid auth response for channel '${this.name}', expected 'channel_data' field. ${ye}, or the user should be signed in.`),w("Invalid auth response");return}w(L,N)}))}handleEvent(y){var w=y.event;if(w.indexOf("pusher_internal:")===0)this.handleInternalEvent(y);else{var L=y.data,N={};y.user_id&&(N.user_id=y.user_id),this.emit(w,L,N)}}handleInternalEvent(y){var w=y.event,L=y.data;switch(w){case"pusher_internal:subscription_succeeded":this.handleSubscriptionSucceededEvent(y);break;case"pusher_internal:subscription_count":this.handleSubscriptionCountEvent(y);break;case"pusher_internal:member_added":var N=this.members.addMember(L);this.emit("pusher:member_added",N);break;case"pusher_internal:member_removed":var te=this.members.removeMember(L);te&&this.emit("pusher:member_removed",te);break}}handleSubscriptionSucceededEvent(y){this.subscriptionPending=!1,this.subscribed=!0,this.subscriptionCancelled?this.pusher.unsubscribe(this.name):(this.members.onSubscription(y.data),this.emit("pusher:subscription_succeeded",this.members))}disconnect(){this.members.reset(),super.disconnect()}}var Ac=f(978),Aa=f(594);class $r extends ar{constructor(y,w,L){super(y,w),this.key=null,this.nacl=L}authorize(y,w){super.authorize(y,(L,N)=>{if(L){w(L,N);return}let te=N.shared_secret;if(!te){w(new Error(`No shared_secret key in auth payload for encrypted channel: ${this.name}`),null);return}this.key=(0,Aa.decode)(te),delete N.shared_secret,w(null,N)})}trigger(y,w){throw new pe("Client events are not currently supported for encrypted channels")}handleEvent(y){var w=y.event,L=y.data;if(w.indexOf("pusher_internal:")===0||w.indexOf("pusher:")===0){super.handleEvent(y);return}this.handleEncryptedEvent(w,L)}handleEncryptedEvent(y,w){if(!this.key){tt.debug("Received encrypted event before key has been retrieved from the authEndpoint");return}if(!w.ciphertext||!w.nonce){tt.error("Unexpected format for encrypted event, expected object with `ciphertext` and `nonce` fields, got: "+w);return}let L=(0,Aa.decode)(w.ciphertext);if(L.length{if(ye){tt.error(`Failed to make a request to the authEndpoint: ${Ne}. Unable to fetch new key, so dropping encrypted event`);return}if(te=this.nacl.secretbox.open(L,N,this.key),te===null){tt.error("Failed to decrypt event with new key. Dropping encrypted event");return}this.emit(y,this.getDataToEmit(te))});return}this.emit(y,this.getDataToEmit(te))}getDataToEmit(y){let w=(0,Ac.D4)(y);try{return JSON.parse(w)}catch{return w}}}class vf extends je{constructor(y,w){super(),this.state="initialized",this.connection=null,this.key=y,this.options=w,this.timeline=this.options.timeline,this.usingTLS=this.options.useTLS,this.errorCallbacks=this.buildErrorCallbacks(),this.connectionCallbacks=this.buildConnectionCallbacks(this.errorCallbacks),this.handshakeCallbacks=this.buildHandshakeCallbacks(this.errorCallbacks);var L=Be.getNetwork();L.bind("online",()=>{this.timeline.info({netinfo:"online"}),(this.state==="connecting"||this.state==="unavailable")&&this.retryIn(0)}),L.bind("offline",()=>{this.timeline.info({netinfo:"offline"}),this.connection&&this.sendActivityCheck()}),this.updateStrategy()}switchCluster(y){this.key=y,this.updateStrategy(),this.retryIn(0)}connect(){if(!(this.connection||this.runner)){if(!this.strategy.isSupported()){this.updateState("failed");return}this.updateState("connecting"),this.startConnecting(),this.setUnavailableTimer()}}send(y){return this.connection?this.connection.send(y):!1}send_event(y,w,L){return this.connection?this.connection.send_event(y,w,L):!1}disconnect(){this.disconnectInternally(),this.updateState("disconnected")}isUsingTLS(){return this.usingTLS}startConnecting(){var y=(w,L)=>{w?this.runner=this.strategy.connect(0,y):L.action==="error"?(this.emit("error",{type:"HandshakeError",error:L.error}),this.timeline.error({handshakeError:L.error})):(this.abortConnecting(),this.handshakeCallbacks[L.action](L))};this.runner=this.strategy.connect(0,y)}abortConnecting(){this.runner&&(this.runner.abort(),this.runner=null)}disconnectInternally(){if(this.abortConnecting(),this.clearRetryTimer(),this.clearUnavailableTimer(),this.connection){var y=this.abandonConnection();y.close()}}updateStrategy(){this.strategy=this.options.getStrategy({key:this.key,timeline:this.timeline,useTLS:this.usingTLS})}retryIn(y){this.timeline.info({action:"retry",delay:y}),y>0&&this.emit("connecting_in",Math.round(y/1e3)),this.retryTimer=new de(y||0,()=>{this.disconnectInternally(),this.connect()})}clearRetryTimer(){this.retryTimer&&(this.retryTimer.ensureAborted(),this.retryTimer=null)}setUnavailableTimer(){this.unavailableTimer=new de(this.options.unavailableTimeout,()=>{this.updateState("unavailable")})}clearUnavailableTimer(){this.unavailableTimer&&this.unavailableTimer.ensureAborted()}sendActivityCheck(){this.stopActivityCheck(),this.connection.ping(),this.activityTimer=new de(this.options.pongTimeout,()=>{this.timeline.error({pong_timed_out:this.options.pongTimeout}),this.retryIn(0)})}resetActivityCheck(){this.stopActivityCheck(),this.connection&&!this.connection.handlesActivityChecks()&&(this.activityTimer=new de(this.activityTimeout,()=>{this.sendActivityCheck()}))}stopActivityCheck(){this.activityTimer&&this.activityTimer.ensureAborted()}buildConnectionCallbacks(y){return ke({},y,{message:w=>{this.resetActivityCheck(),this.emit("message",w)},ping:()=>{this.send_event("pusher:pong",{})},activity:()=>{this.resetActivityCheck()},error:w=>{this.emit("error",w)},closed:()=>{this.abandonConnection(),this.shouldRetry()&&this.retryIn(1e3)}})}buildHandshakeCallbacks(y){return ke({},y,{connected:w=>{this.activityTimeout=Math.min(this.options.activityTimeout,w.activityTimeout,w.connection.activityTimeout||1/0),this.clearUnavailableTimer(),this.setConnection(w.connection),this.socket_id=this.connection.id,this.updateState("connected",{socket_id:this.socket_id})}})}buildErrorCallbacks(){let y=w=>L=>{L.error&&this.emit("error",{type:"WebSocketError",error:L.error}),w(L)};return{tls_only:y(()=>{this.usingTLS=!0,this.updateStrategy(),this.retryIn(0)}),refused:y(()=>{this.disconnect()}),backoff:y(()=>{this.retryIn(1e3)}),retry:y(()=>{this.retryIn(0)})}}setConnection(y){this.connection=y;for(var w in this.connectionCallbacks)this.connection.bind(w,this.connectionCallbacks[w]);this.resetActivityCheck()}abandonConnection(){if(this.connection){this.stopActivityCheck();for(var y in this.connectionCallbacks)this.connection.unbind(y,this.connectionCallbacks[y]);var w=this.connection;return this.connection=null,w}}updateState(y,w){var L=this.state;if(this.state=y,L!==y){var N=y;N==="connected"&&(N+=" with new socket ID "+w.socket_id),tt.debug("State changed",L+" -> "+N),this.timeline.info({state:y,params:w}),this.emit("state_change",{previous:L,current:y}),this.emit(y,w)}}shouldRetry(){return this.state==="connecting"||this.state==="connected"}}class xc{constructor(){this.channels={}}add(y,w){return this.channels[y]||(this.channels[y]=Tc(y,w)),this.channels[y]}all(){return kt(this.channels)}find(y){return this.channels[y]}remove(y){var w=this.channels[y];return delete this.channels[y],w}disconnect(){Ct(this.channels,function(y){y.disconnect()})}}function Tc(E,y){if(E.indexOf("private-encrypted-")===0){if(y.config.nacl)return In.createEncryptedChannel(E,y,y.config.nacl);let w="Tried to subscribe to a private-encrypted- channel but no nacl implementation available",L=M.buildLogSuffix("encryptedChannelSupport");throw new pe(`${w}. ${L}`)}else{if(E.indexOf("private-")===0)return In.createPrivateChannel(E,y);if(E.indexOf("presence-")===0)return In.createPresenceChannel(E,y);if(E.indexOf("#")===0)throw new j('Cannot create a channel with name "'+E+'".');return In.createChannel(E,y)}}var Sf={createChannels(){return new xc},createConnectionManager(E,y){return new vf(E,y)},createChannel(E,y){return new qa(E,y)},createPrivateChannel(E,y){return new ar(E,y)},createPresenceChannel(E,y){return new _c(E,y)},createEncryptedChannel(E,y,w){return new $r(E,y,w)},createTimelineSender(E,y){return new Lr(E,y)},createHandshake(E,y){return new Mo(E,y)},createAssistantToTheTransportManager(E,y,w){return new bf(E,y,w)}};const In=Sf;class Si{constructor(y){this.options=y||{},this.livesLeft=this.options.lives||1/0}getAssistant(y){return In.createAssistantToTheTransportManager(this,y,{minPingDelay:this.options.minPingDelay,maxPingDelay:this.options.maxPingDelay})}isAlive(){return this.livesLeft>0}reportDeath(){this.livesLeft-=1}}class mn{constructor(y,w){this.strategies=y,this.loop=!!w.loop,this.failFast=!!w.failFast,this.timeout=w.timeout,this.timeoutLimit=w.timeoutLimit}isSupported(){return hn(this.strategies,Pe.method("isSupported"))}connect(y,w){var L=this.strategies,N=0,te=this.timeout,ye=null,Ne=(Fe,lt)=>{lt?w(null,lt):(N=N+1,this.loop&&(N=N%L.length),N0&&(te=new de(L.timeout,function(){ye.abort(),N(!0)})),ye=y.connect(w,function(Ne,Fe){Ne&&te&&te.isRunning()&&!L.failFast||(te&&te.ensureAborted(),N(Ne,Fe))}),{abort:function(){te&&te.ensureAborted(),ye.abort()},forceMinPriority:function(Ne){ye.forceMinPriority(Ne)}}}}class Tn{constructor(y){this.strategies=y}isSupported(){return hn(this.strategies,Pe.method("isSupported"))}connect(y,w){return Rc(this.strategies,y,function(L,N){return function(te,ye){if(N[L].error=te,te){wf(N)&&w(!0);return}Ee(N,function(Ne){Ne.forceMinPriority(ye.transport.priority)}),w(null,ye)}})}}function Rc(E,y,w){var L=Nt(E,function(N,te,ye,Ne){return N.connect(y,w(te,Ne))});return{abort:function(){Ee(L,$o)},forceMinPriority:function(N){Ee(L,function(te){te.forceMinPriority(N)})}}}function wf(E){return Ba(E,function(y){return!!y.error})}function $o(E){!E.error&&!E.aborted&&(E.abort(),E.aborted=!0)}class kc{constructor(y,w,L){this.strategy=y,this.transports=w,this.ttl=L.ttl||18e5,this.usingTLS=L.useTLS,this.timeline=L.timeline}isSupported(){return this.strategy.isSupported()}connect(y,w){var L=this.usingTLS,N=Cf(L),te=N&&N.cacheSkipCount?N.cacheSkipCount:0,ye=[this.strategy];if(N&&N.timestamp+this.ttl>=Pe.now()){var Ne=this.transports[N.transport];Ne&&(["ws","wss"].includes(N.transport)||te>3?(this.timeline.info({cached:!0,transport:N.transport,latency:N.latency}),ye.push(new mn([Ne],{timeout:N.latency*2+1e3,failFast:!0}))):te++)}var Fe=Pe.now(),lt=ye.pop().connect(y,function pt(jt,ka){jt?(ps(L),ye.length>0?(Fe=Pe.now(),lt=ye.pop().connect(y,pt)):w(jt)):(Hn(L,ka.transport.name,Pe.now()-Fe,te),w(null,ka))});return{abort:function(){lt.abort()},forceMinPriority:function(pt){y=pt,lt&<.forceMinPriority(pt)}}}}function Nr(E){return"pusherTransport"+(E?"TLS":"NonTLS")}function Cf(E){var y=Be.getLocalStorage();if(y)try{var w=y[Nr(E)];if(w)return JSON.parse(w)}catch{ps(E)}return null}function Hn(E,y,w,L){var N=Be.getLocalStorage();if(N)try{N[Nr(E)]=An({timestamp:Pe.now(),transport:y,latency:w,cacheSkipCount:L})}catch{}}function ps(E){var y=Be.getLocalStorage();if(y)try{delete y[Nr(E)]}catch{}}class wi{constructor(y,{delay:w}){this.strategy=y,this.options={delay:w}}isSupported(){return this.strategy.isSupported()}connect(y,w){var L=this.strategy,N,te=new de(this.options.delay,function(){N=L.connect(y,w)});return{abort:function(){te.ensureAborted(),N&&N.abort()},forceMinPriority:function(ye){y=ye,N&&N.forceMinPriority(ye)}}}}class rr{constructor(y,w,L){this.test=y,this.trueBranch=w,this.falseBranch=L}isSupported(){var y=this.test()?this.trueBranch:this.falseBranch;return y.isSupported()}connect(y,w){var L=this.test()?this.trueBranch:this.falseBranch;return L.connect(y,w)}}class Ir{constructor(y){this.strategy=y}isSupported(){return this.strategy.isSupported()}connect(y,w){var L=this.strategy.connect(y,function(N,te){te&&L.abort(),w(N,te)});return L}}function Hr(E){return function(){return E.isSupported()}}var Dc=function(E,y,w){var L={};function N(Wo,Gc,Vc,qf,Gf){var Fc=w(E,Wo,Gc,Vc,qf,Gf);return L[Wo]=Fc,Fc}var te=Object.assign({},y,{hostNonTLS:E.wsHost+":"+E.wsPort,hostTLS:E.wsHost+":"+E.wssPort,httpPath:E.wsPath}),ye=Object.assign({},te,{useTLS:!0}),Ne=Object.assign({},y,{hostNonTLS:E.httpHost+":"+E.httpPort,hostTLS:E.httpHost+":"+E.httpsPort,httpPath:E.httpPath}),Fe={loop:!0,timeout:15e3,timeoutLimit:6e4},lt=new Si({minPingDelay:1e4,maxPingDelay:E.activityTimeout}),pt=new Si({lives:2,minPingDelay:1e4,maxPingDelay:E.activityTimeout}),jt=N("ws","ws",3,te,lt),ka=N("wss","ws",3,ye,lt),Uf=N("sockjs","sockjs",1,Ne),Pc=N("xhr_streaming","xhr_streaming",1,Ne,pt),Bf=N("xdr_streaming","xdr_streaming",1,Ne,pt),Vo=N("xhr_polling","xhr_polling",1,Ne),qc=N("xdr_polling","xdr_polling",1,Ne),Ur=new mn([jt],Fe),Ti=new mn([ka],Fe),Pf=new mn([Uf],Fe),Ri=new mn([new rr(Hr(Pc),Pc,Bf)],Fe),Fo=new mn([new rr(Hr(Vo),Vo,qc)],Fe),Ko=new mn([new rr(Hr(Ri),new Tn([Ri,new wi(Fo,{delay:4e3})]),Fo)],Fe),ki=new rr(Hr(Ko),Ko,Pf),Di;return y.useTLS?Di=new Tn([Ur,new wi(ki,{delay:2e3})]):Di=new Tn([Ur,new wi(Ti,{delay:2e3}),new wi(ki,{delay:5e3})]),new kc(new Ir(new rr(Hr(jt),Di,ki)),L,{ttl:18e5,timeline:y.timeline,useTLS:y.useTLS})};const zr=Dc;function Ef(){var E=this;E.timeline.info(E.buildTimelineMessage({transport:E.name+(E.options.useTLS?"s":"")})),E.hooks.isInitialized()?E.changeState("initialized"):E.hooks.file?(E.changeState("initializing"),x.load(E.hooks.file,{useTLS:E.options.useTLS},function(y,w){E.hooks.isInitialized()?(E.changeState("initialized"),w(!0)):(y&&E.onError(y),E.onClose(),w(!1))})):E.onClose()}var Oc={getRequest:function(E){var y=new window.XDomainRequest;return y.ontimeout=function(){E.emit("error",new H),E.close()},y.onerror=function(w){E.emit("error",w),E.close()},y.onprogress=function(){y.responseText&&y.responseText.length>0&&E.onChunk(200,y.responseText)},y.onload=function(){y.responseText&&y.responseText.length>0&&E.onChunk(200,y.responseText),E.emit("finished",200),E.close()},y},abortRequest:function(E){E.ontimeout=E.onerror=E.onprogress=E.onload=null,E.abort()}};const Lc=Oc,No=256*1024;class _f extends je{constructor(y,w,L){super(),this.hooks=y,this.method=w,this.url=L}start(y){this.position=0,this.xhr=this.hooks.getRequest(this),this.unloader=()=>{this.close()},Be.addUnloadListener(this.unloader),this.xhr.open(this.method,this.url,!0),this.xhr.setRequestHeader&&this.xhr.setRequestHeader("Content-Type","application/json"),this.xhr.send(y)}close(){this.unloader&&(Be.removeUnloadListener(this.unloader),this.unloader=null),this.xhr&&(this.hooks.abortRequest(this.xhr),this.xhr=null)}onChunk(y,w){for(;;){var L=this.advanceBuffer(w);if(L)this.emit("chunk",{status:y,data:L});else break}this.isBufferTooLong(w)&&this.emit("buffer_too_long")}advanceBuffer(y){var w=y.slice(this.position),L=w.indexOf(` +`);return L!==-1?(this.position+=L+1,w.slice(0,L)):null}isBufferTooLong(y){return this.position===y.length&&y.length>No}}var Io;(function(E){E[E.CONNECTING=0]="CONNECTING",E[E.OPEN=1]="OPEN",E[E.CLOSED=3]="CLOSED"})(Io||(Io={}));const aa=Io;var xa=1;class Ho{constructor(y,w){this.hooks=y,this.session=ms(1e3)+"/"+$c(8),this.location=zo(w),this.readyState=aa.CONNECTING,this.openStream()}send(y){return this.sendRaw(JSON.stringify([y]))}ping(){this.hooks.sendHeartbeat(this)}close(y,w){this.onClose(y,w,!0)}sendRaw(y){if(this.readyState===aa.OPEN)try{return Be.createSocketRequest("POST",ir(jr(this.location,this.session))).start(y),!0}catch{return!1}else return!1}reconnect(){this.closeStream(),this.openStream()}onClose(y,w,L){this.closeStream(),this.readyState=aa.CLOSED,this.onclose&&this.onclose({code:y,reason:w,wasClean:L})}onChunk(y){if(y.status===200){this.readyState===aa.OPEN&&this.onActivity();var w,L=y.data.slice(0,1);switch(L){case"o":w=JSON.parse(y.data.slice(1)||"{}"),this.onOpen(w);break;case"a":w=JSON.parse(y.data.slice(1)||"[]");for(var N=0;N{this.onChunk(y)}),this.stream.bind("finished",y=>{this.hooks.onFinished(this,y)}),this.stream.bind("buffer_too_long",()=>{this.reconnect()});try{this.stream.start()}catch(y){Pe.defer(()=>{this.onError(y),this.onClose(1006,"Could not start streaming",!1)})}}closeStream(){this.stream&&(this.stream.unbind_all(),this.stream.close(),this.stream=null)}}function zo(E){var y=/([^\?]*)\/*(\??.*)/.exec(E);return{base:y[1],queryString:y[2]}}function jr(E,y){return E.base+"/"+y+"/xhr_send"}function ir(E){var y=E.indexOf("?")===-1?"?":"&";return E+y+"t="+ +new Date+"&n="+xa++}function Mc(E,y){var w=/(https?:\/\/)([^\/:]+)((\/|:)?.*)/.exec(E);return w[1]+y+w[3]}function ms(E){return Be.randomInt(E)}function $c(E){for(var y=[],w=0;w0&&E.onChunk(w.status,w.responseText);break;case 4:w.responseText&&w.responseText.length>0&&E.onChunk(w.status,w.responseText),E.emit("finished",w.status),E.close();break}},w},abortRequest:function(E){E.onreadystatechange=null,E.abort()}};const ys=Uo;var Nc={createStreamingSocket(E){return this.createSocket(jo,E)},createPollingSocket(E){return this.createSocket(Ga,E)},createSocket(E,y){return new Ci(E,y)},createXHR(E,y){return this.createRequest(ys,E,y)},createRequest(E,y,w){return new _f(E,y,w)}};const _i=Nc;_i.createXDR=function(E,y){return this.createRequest(Lc,E,y)};var Ic={nextAuthCallbackID:1,auth_callbacks:{},ScriptReceivers:m,DependenciesReceivers:_,getDefaultStrategy:zr,Transports:xn,transportConnectionInitializer:Ef,HTTPFactory:_i,TimelineTransport:q,getXHRAPI(){return window.XMLHttpRequest},getWebSocketAPI(){return window.WebSocket||window.MozWebSocket},setup(E){if(typeof window<"u"){window.Pusher=E;var y=()=>{this.onDocumentBody(E.ready)};window.JSON?y():x.load("json2",{},y)}},getDocument(){return document},getProtocol(){return this.getDocument().location.protocol},getAuthorizers(){return{ajax:Je,jsonp:kn}},onDocumentBody(E){document.body?E():setTimeout(()=>{this.onDocumentBody(E)},0)},createJSONPRequest(E,y){return new _a(E,y)},createScriptRequest(E){return new nr(E)},getLocalStorage(){try{return window.localStorage}catch{return}},createXHR(){return this.getXHRAPI()?this.createXMLHttpRequest():this.createMicrosoftXHR()},createXMLHttpRequest(){var E=this.getXHRAPI();return new E},createMicrosoftXHR(){return new ActiveXObject("Microsoft.XMLHTTP")},getNetwork(){return Lo},createWebSocket(E){var y=this.getWebSocketAPI();return new y(E)},createSocketRequest(E,y){if(this.isXHRSupported())return this.HTTPFactory.createXHR(E,y);if(this.isXDRSupported(y.indexOf("https:")===0))return this.HTTPFactory.createXDR(E,y);throw"Cross-origin HTTP requests are not supported"},isXHRSupported(){var E=this.getXHRAPI();return!!E&&new E().withCredentials!==void 0},isXDRSupported(E){var y=E?"https:":"http:",w=this.getProtocol();return!!window.XDomainRequest&&w===y},addUnloadListener(E){window.addEventListener!==void 0?window.addEventListener("pagehide",E,!1):window.attachEvent!==void 0&&window.attachEvent("onunload",E)},removeUnloadListener(E){window.addEventListener!==void 0?window.removeEventListener("pagehide",E,!1):window.detachEvent!==void 0&&window.detachEvent("onunload",E)},randomInt(E){const y=window.crypto||window.msCrypto,w=Math.floor(Math.pow(2,32)/E)*E;let L;do L=y.getRandomValues(new Uint32Array(1))[0];while(L>=w);return L%E}};const Be=Ic;var Ra;(function(E){E[E.ERROR=3]="ERROR",E[E.INFO=6]="INFO",E[E.DEBUG=7]="DEBUG"})(Ra||(Ra={}));const sr=Ra;class Ai{constructor(y,w,L){this.key=y,this.session=w,this.events=[],this.options=L||{},this.sent=0,this.uniqueID=0}log(y,w){y<=this.options.level&&(this.events.push(ke({},w,{timestamp:Pe.now()})),this.options.limit&&this.events.length>this.options.limit&&this.events.shift())}error(y){this.log(sr.ERROR,y)}info(y){this.log(sr.INFO,y)}debug(y){this.log(sr.DEBUG,y)}isEmpty(){return this.events.length===0}send(y,w){var L=ke({session:this.session,bundle:this.sent+1,key:this.key,lib:"js",version:this.options.version,cluster:this.options.cluster,features:this.options.features,timeline:this.events},this.options.params);return this.events=[],y(L,(N,te)=>{N||this.sent++,w&&w(N,te)}),!0}generateUniqueID(){return this.uniqueID++,this.uniqueID}}class Af{constructor(y,w,L,N){this.name=y,this.priority=w,this.transport=L,this.options=N||{}}isSupported(){return this.transport.isSupported({useTLS:this.options.useTLS})}connect(y,w){if(this.isSupported()){if(this.priority{L||(pt(),te?te.close():N.close())},forceMinPriority:jt=>{L||this.priority{var w="socket_id="+encodeURIComponent(E.socketId);for(var L in y.params)w+="&"+encodeURIComponent(L)+"="+encodeURIComponent(y.params[L]);if(y.paramsProvider!=null){let N=y.paramsProvider();for(var L in N)w+="&"+encodeURIComponent(L)+"="+encodeURIComponent(N[L])}return w},Tf=E=>{if(typeof Be.getAuthorizers()[E.transport]>"u")throw`'${E.transport}' is not a recognized auth transport`;return(y,w)=>{const L=xf(y,E);Be.getAuthorizers()[E.transport](Be,L,E,T.UserAuthentication,w)}},qo=(E,y)=>{var w="socket_id="+encodeURIComponent(E.socketId);w+="&channel_name="+encodeURIComponent(E.channelName);for(var L in y.params)w+="&"+encodeURIComponent(L)+"="+encodeURIComponent(y.params[L]);if(y.paramsProvider!=null){let N=y.paramsProvider();for(var L in N)w+="&"+encodeURIComponent(L)+"="+encodeURIComponent(N[L])}return w},Rf=E=>{if(typeof Be.getAuthorizers()[E.transport]>"u")throw`'${E.transport}' is not a recognized auth transport`;return(y,w)=>{const L=qo(y,E);Be.getAuthorizers()[E.transport](Be,L,E,T.ChannelAuthorization,w)}},kf=(E,y,w)=>{const L={authTransport:y.transport,authEndpoint:y.endpoint,auth:{params:y.params,headers:y.headers}};return(N,te)=>{const ye=E.channel(N.channelName);w(ye,L).authorize(N.socketId,te)}};function zc(E,y){let w={activityTimeout:E.activityTimeout||v.activityTimeout,cluster:E.cluster,httpPath:E.httpPath||v.httpPath,httpPort:E.httpPort||v.httpPort,httpsPort:E.httpsPort||v.httpsPort,pongTimeout:E.pongTimeout||v.pongTimeout,statsHost:E.statsHost||v.stats_host,unavailableTimeout:E.unavailableTimeout||v.unavailableTimeout,wsPath:E.wsPath||v.wsPath,wsPort:E.wsPort||v.wsPort,wssPort:E.wssPort||v.wssPort,enableStats:Mf(E),httpHost:Df(E),useTLS:Lf(E),wsHost:jc(E),userAuthenticator:Go(E),channelAuthorizer:Nf(E,y)};return"disabledTransports"in E&&(w.disabledTransports=E.disabledTransports),"enabledTransports"in E&&(w.enabledTransports=E.enabledTransports),"ignoreNullOrigin"in E&&(w.ignoreNullOrigin=E.ignoreNullOrigin),"timelineParams"in E&&(w.timelineParams=E.timelineParams),"nacl"in E&&(w.nacl=E.nacl),w}function Df(E){return E.httpHost?E.httpHost:E.cluster?`sockjs-${E.cluster}.pusher.com`:v.httpHost}function jc(E){return E.wsHost?E.wsHost:Of(E.cluster)}function Of(E){return`ws-${E}.pusher.com`}function Lf(E){return Be.getProtocol()==="https:"?!0:E.forceTLS!==!1}function Mf(E){return"enableStats"in E?E.enableStats:"disableStats"in E?!E.disableStats:!1}const Uc=E=>"customHandler"in E&&E.customHandler!=null;function Go(E){const y=Object.assign(Object.assign({},v.userAuthentication),E.userAuthentication);return Uc(y)?y.customHandler:Tf(y)}function $f(E,y){let w;return"channelAuthorization"in E?w=Object.assign(Object.assign({},v.channelAuthorization),E.channelAuthorization):(w={transport:E.authTransport||v.authTransport,endpoint:E.authEndpoint||v.authEndpoint},"auth"in E&&("params"in E.auth&&(w.params=E.auth.params),"headers"in E.auth&&(w.headers=E.auth.headers)),"authorizer"in E&&(w.customHandler=kf(y,w,E.authorizer))),w}function Nf(E,y){const w=$f(E,y);return Uc(w)?w.customHandler:Rf(w)}class If extends je{constructor(y){super(function(w,L){tt.debug(`No callbacks on watchlist events for ${w}`)}),this.pusher=y,this.bindWatchlistInternalEvent()}handleEvent(y){y.data.events.forEach(w=>{this.emit(w.name,w)})}bindWatchlistInternalEvent(){this.pusher.connection.bind("message",y=>{var w=y.event;w==="pusher_internal:watchlist_events"&&this.handleEvent(y)})}}function Bc(){let E,y;return{promise:new Promise((L,N)=>{E=L,y=N}),resolve:E,reject:y}}const Hf=Bc;class zf extends je{constructor(y){super(function(w,L){tt.debug("No callbacks on user for "+w)}),this.signin_requested=!1,this.user_data=null,this.serverToUserChannel=null,this.signinDonePromise=null,this._signinDoneResolve=null,this._onAuthorize=(w,L)=>{if(w){tt.warn(`Error during signin: ${w}`),this.emit("pusher:signin_error",Object.assign({},{type:"AuthError",error:w.message},w instanceof Me?{status:w.status}:{})),this._cleanup();return}this.pusher.send_event("pusher:signin",{auth:L.auth,user_data:L.user_data})},this.pusher=y,this.pusher.connection.bind("state_change",({previous:w,current:L})=>{w!=="connected"&&L==="connected"&&this._signin(),w==="connected"&&L!=="connected"&&(this._cleanup(),this._newSigninPromiseIfNeeded())}),this.watchlist=new If(y),this.pusher.connection.bind("message",w=>{var L=w.event;L==="pusher:signin_success"&&this._onSigninSuccess(w.data),this.serverToUserChannel&&this.serverToUserChannel.name===w.channel&&this.serverToUserChannel.handleEvent(w)})}signin(){this.signin_requested||(this.signin_requested=!0,this._signin())}_signin(){this.signin_requested&&(this._newSigninPromiseIfNeeded(),this.pusher.connection.state==="connected"&&this.pusher.config.userAuthenticator({socketId:this.pusher.connection.socket_id},this._onAuthorize))}_onSigninSuccess(y){try{this.user_data=JSON.parse(y.user_data)}catch{tt.error(`Failed parsing user data after signin: ${y.user_data}`),this._cleanup();return}if(typeof this.user_data.id!="string"||this.user_data.id===""){tt.error(`user_data doesn't contain an id. user_data: ${this.user_data}`),this._cleanup();return}this._signinDoneResolve(),this._subscribeChannels()}_subscribeChannels(){const y=w=>{w.subscriptionPending&&w.subscriptionCancelled?w.reinstateSubscription():!w.subscriptionPending&&this.pusher.connection.state==="connected"&&w.subscribe()};this.serverToUserChannel=new qa(`#server-to-user-${this.user_data.id}`,this.pusher),this.serverToUserChannel.bind_global((w,L)=>{w.indexOf("pusher_internal:")===0||w.indexOf("pusher:")===0||this.emit(w,L)}),y(this.serverToUserChannel)}_cleanup(){this.user_data=null,this.serverToUserChannel&&(this.serverToUserChannel.unbind_all(),this.serverToUserChannel.disconnect(),this.serverToUserChannel=null),this.signin_requested&&this._signinDoneResolve()}_newSigninPromiseIfNeeded(){if(!this.signin_requested||this.signinDonePromise&&!this.signinDonePromise.done)return;const{promise:y,resolve:w}=Hf();y.done=!1;const L=()=>{y.done=!0};y.then(L).catch(L),this.signinDonePromise=y,this._signinDoneResolve=w}}class cn{static ready(){cn.isReady=!0;for(var y=0,w=cn.instances.length;yBe.getDefaultStrategy(this.config,N,xi);this.connection=In.createConnectionManager(this.key,{getStrategy:L,timeline:this.timeline,activityTimeout:this.config.activityTimeout,pongTimeout:this.config.pongTimeout,unavailableTimeout:this.config.unavailableTimeout,useTLS:!!this.config.useTLS}),this.connection.bind("connected",()=>{this.subscribeAll(),this.timelineSender&&this.timelineSender.send(this.connection.isUsingTLS())}),this.connection.bind("message",N=>{var te=N.event,ye=te.indexOf("pusher_internal:")===0;if(N.channel){var Ne=this.channel(N.channel);Ne&&Ne.handleEvent(N)}ye||this.global_emitter.emit(N.event,N.data)}),this.connection.bind("connecting",()=>{this.channels.disconnect()}),this.connection.bind("disconnected",()=>{this.channels.disconnect()}),this.connection.bind("error",N=>{tt.warn(N)}),cn.instances.push(this),this.timeline.info({instances:cn.instances.length}),this.user=new zf(this),cn.isReady&&this.connect()}switchCluster(y){const{appKey:w,cluster:L}=y;this.key=w,this.options=Object.assign(Object.assign({},this.options),{cluster:L}),this.config=zc(this.options,this),this.connection.switchCluster(this.key)}channel(y){return this.channels.find(y)}allChannels(){return this.channels.all()}connect(){if(this.connection.connect(),this.timelineSender&&!this.timelineSenderTimer){var y=this.connection.isUsingTLS(),w=this.timelineSender;this.timelineSenderTimer=new Oe(6e4,function(){w.send(y)})}}disconnect(){this.connection.disconnect(),this.timelineSenderTimer&&(this.timelineSenderTimer.ensureAborted(),this.timelineSenderTimer=null)}bind(y,w,L){return this.global_emitter.bind(y,w,L),this}unbind(y,w,L){return this.global_emitter.unbind(y,w,L),this}bind_global(y){return this.global_emitter.bind_global(y),this}unbind_global(y){return this.global_emitter.unbind_global(y),this}unbind_all(y){return this.global_emitter.unbind_all(),this}subscribeAll(){var y;for(y in this.channels.channels)this.channels.channels.hasOwnProperty(y)&&this.subscribe(y)}subscribe(y){var w=this.channels.add(y,this);return w.subscriptionPending&&w.subscriptionCancelled?w.reinstateSubscription():!w.subscriptionPending&&this.connection.state==="connected"&&w.subscribe(),w}unsubscribe(y){var w=this.channels.find(y);w&&w.subscriptionPending?w.cancelSubscription():(w=this.channels.remove(y),w&&w.subscribed&&w.unsubscribe())}send_event(y,w,L){return this.connection.send_event(y,w,L)}shouldUseTLS(){return this.config.useTLS}signin(){this.user.signin()}}cn.instances=[],cn.isReady=!1,cn.logToConsole=!1,cn.Runtime=Be,cn.ScriptReceivers=Be.ScriptReceivers,cn.DependenciesReceivers=Be.DependenciesReceivers,cn.auth_callbacks=Be.auth_callbacks;const Ss=cn;function jf(E){if(E==null)throw"You must pass your app key when you instantiate Pusher."}Be.setup(cn)}},r={};function i(u){var d=r[u];if(d!==void 0)return d.exports;var f=r[u]={exports:{}};return n[u].call(f.exports,f,f.exports,i),f.exports}i.d=(u,d)=>{for(var f in d)i.o(d,f)&&!i.o(u,f)&&Object.defineProperty(u,f,{enumerable:!0,get:d[f]})},i.o=(u,d)=>Object.prototype.hasOwnProperty.call(u,d);var l=i(721);return l})())})(df)),df.exports}var W_=K_();const cy=Xa(W_),Bt=dt("WebSocketManager");class Y_{constructor(){$(this,"echo",null);$(this,"subscriptions",new Map);$(this,"initialized",!1);$(this,"config",null)}configure(e){if(this.initialized){Bt.warn("[WebSocketManager] 이미 초기화되어 설정을 변경할 수 없습니다.");return}this.config=e,Bt.log("[WebSocketManager] 설정 완료:",{appKey:e.appKey?"***":"(없음)",host:e.host,port:e.port,scheme:e.scheme})}initialize(){if(this.initialized)return;if(!this.config||!this.config.appKey){Bt.warn("[WebSocketManager] WebSocket 설정이 없습니다. initTemplateApp에서 websocket 옵션을 전달해주세요.");return}const{appKey:e,host:n="localhost",port:r=80,scheme:i="https",authEndpoint:l="/api/broadcasting/auth"}=this.config,u=Number(r)||80,d=i==="https";Bt.log("[WebSocketManager] 연결 설정:",{host:n,port:u,scheme:i,useTLS:d,authEndpoint:l}),window.Pusher=cy;const f=localStorage.getItem("auth_token"),g={wsHost:n,wsPort:u,wssPort:u,forceTLS:d,disableStats:!0,enabledTransports:["ws","wss"],cluster:"mt1",authEndpoint:l,auth:{headers:{Authorization:f?`Bearer ${f}`:"",Accept:"application/json"}}};Bt.log("[WebSocketManager] Pusher 옵션:",g);const m=new cy(e,g);m.connection.bind("connecting",()=>{Bt.log("[WebSocketManager] 연결 시도 중...")}),m.connection.bind("connected",()=>{Bt.log("[WebSocketManager] 연결 성공! Socket ID:",m.connection.socket_id)}),m.connection.bind("failed",()=>{Bt.error("[WebSocketManager] 연결 실패 - WebSocket을 사용할 수 없습니다.")}),m.connection.bind("error",b=>{Bt.error("[WebSocketManager] 연결 오류:",b)}),m.connection.bind("state_change",b=>{Bt.log(`[WebSocketManager] 상태 변경: ${b.previous} → ${b.current}`)}),m.connection.bind("unavailable",()=>{Bt.error("[WebSocketManager] WebSocket 사용 불가 - 연결할 수 없습니다.")}),m.connection.bind("disconnected",()=>{Bt.warn("[WebSocketManager] 연결이 끊어졌습니다.")}),Bt.log("[WebSocketManager] 초기 연결 상태:",m.connection.state),this.echo=new F_({broadcaster:"reverb",client:m}),Bt.log("[WebSocketManager] 연결 시작 시도..."),m.connect(),window.Echo=this.echo,this.initialized=!0,Bt.log("[WebSocketManager] Echo 초기화 완료")}subscribe(e,n,r,i={}){if(this.initialize(),!this.echo)return Bt.warn("[WebSocketManager] Echo가 초기화되지 않았습니다."),"";const{channelType:l="private"}=i,u=`${e}:${n}`;if(this.subscriptions.has(u))return Bt.log(`[WebSocketManager] 이미 구독 중: ${u}`),u;let d;switch(l){case"public":d=this.echo.channel(e);break;case"presence":d=this.echo.join(e);break;default:d=this.echo.private(e)}return d.listen(`.${n}`,r),this.subscriptions.set(u,d),Bt.log(`[WebSocketManager] 구독 완료: ${u} (${l})`),u}unsubscribe(e){const n=this.subscriptions.get(e);if(!n)return;const r=e.lastIndexOf(":"),i=r>=0?e.substring(r+1):"";if(i)try{n.stopListening(`.${i}`)}catch(l){Bt.warn(`[WebSocketManager] stopListening 실패: ${e}`,l)}this.subscriptions.delete(e),Bt.log(`[WebSocketManager] 구독 해제: ${e}`)}leaveChannel(e){if(!this.echo)return;this.echo.leave(e);const n=[];this.subscriptions.forEach((r,i)=>{i.startsWith(`${e}:`)&&n.push(i)}),n.forEach(r=>this.subscriptions.delete(r)),Bt.log(`[WebSocketManager] 채널 구독 해제: ${e}`)}disconnect(){this.echo&&(this.echo.disconnect(),this.subscriptions.clear(),this.initialized=!1,Bt.log("[WebSocketManager] 연결 종료"))}getEcho(){return this.echo}isInitialized(){return this.initialized}isConfigured(){return this.config!==null&&!!this.config.appKey}getSubscriptionCount(){return this.subscriptions.size}}const mc=new Y_,bt=dt("DataSourceManager"),X_=new Rn;function yc(o,e){const n=o.match(/^\{\{(.+)\}\}$/);if(n){const r=n[1].trim();try{return X_.evaluateExpression(r,e)}catch(i){return bt.error("Failed to evaluate param expression:",r,i),o}}return Zi(o,e,{skipCache:!0})}function uy(o){const e={};for(const n of o.keys()){if(n in e)continue;const r=o.getAll(n);r.length>1?e[n]=r:r.length===1&&(n.endsWith("[]")?e[n]=r:e[n]=r[0])}return e}function J_(){try{return window.G7Core?.devTools}catch{return}}const Cc=class Cc{constructor(e={}){$(this,"options");$(this,"dataCache",new Map);$(this,"bindingEngine");$(this,"globalHeaders",[]);this.options=e,this.bindingEngine=new Rn}setGlobalHeaders(e){this.globalHeaders=e||[]}matchesPattern(e,n){if(n==="*")return!0;const r=n.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(e)}toFormData(e){const n=new FormData;for(const[r,i]of Object.entries(e))i instanceof File||i instanceof Blob?n.append(r,i):i!=null&&n.append(r,typeof i=="object"?JSON.stringify(i):String(i));return n}getMatchingGlobalHeaders(e,n){const r={};for(const i of this.globalHeaders)this.matchesPattern(e,i.pattern)&&Object.entries(i.headers).forEach(([l,u])=>{const d=yc(u,n);d!=null&&d!==""&&(r[l]=String(d))});return r}filterByCondition(e,n={}){const r=new Set,i=[];for(const l of e){if(r.has(l.id))continue;if(!l.if&&!l.conditions){r.add(l.id),i.push(l);continue}Qi({if:l.if,conditions:l.conditions},n,this.bindingEngine,`data_source:${l.id}`)&&(r.add(l.id),i.push(l))}return i}checkErrorCondition(e,n){if(!e.errorCondition?.if||e.errorCondition?.errorCode===void 0)return null;try{const r={response:n};if(Qi({if:e.errorCondition.if},r,this.bindingEngine,`errorCondition:${e.id}`))return bt.log(`errorCondition matched for ${e.id}, triggering error ${e.errorCondition.errorCode}`),e.errorCondition.errorCode}catch(r){bt.error(`Failed to evaluate errorCondition for ${e.id}:`,r)}return null}async fetchDataSources(e,n={},r=new URLSearchParams,i,l){const u={},d=!!this.options.sampleProvider,f=e.filter(g=>(d||g.auto_fetch!==!1)&&g.type!=="websocket");return await Promise.all(f.map(async g=>{try{const m=await this.fetchDataSource(g,n,r,i,l);u[g.id]=m,this.dataCache.set(g.id,{data:m,timestamp:Date.now()});const b=this.checkErrorCondition(g,m);if(b!==null){const v={status:b,message:`Error condition matched for ${g.id}`,data:m},S=ma(),_=S.resolve(b,{errorHandling:g.errorHandling,onError:g.onError});if(_.handler)try{await S.execute(_.handler,v)}catch(x){bt.error(`Error executing errorCondition handler for ${g.id}:`,x)}g.fallback!==void 0&&(u[g.id]=g.fallback,this.dataCache.set(g.id,{data:g.fallback,timestamp:Date.now()}),bt.log(`Using fallback data for ${g.id} (errorCondition)`));return}if(g.onSuccess)try{const v={data:m,sourceId:g.id};await this.executeOnSuccessHandler(g.onSuccess,v)}catch(v){bt.error(`Error executing onSuccess handler for ${g.id}:`,v)}}catch(m){bt.error(`Failed to fetch data source: ${g.id}`,m);const b=m?.response?.status||m?.status||500,v=m?.response?.data,S=v?.message||m.message||"Unknown error",_={status:b,message:S,errors:v?.errors,data:v,statusText:m?.response?.statusText},x=ma(),k=x.resolve(b,{errorHandling:g.errorHandling,onError:g.onError});if(k.handler)try{await x.execute(k.handler,_)}catch(O){bt.error(`Error executing error handler for ${g.id}:`,O)}g.fallback!==void 0&&(u[g.id]=g.fallback,this.dataCache.set(g.id,{data:g.fallback,timestamp:Date.now()}),bt.log(`Using fallback data for ${g.id}`)),this.options.onError&&this.options.onError(m,g)}})),u}async fetchDataSourcesWithResults(e,n={},r=new URLSearchParams,i,l,u){if(e.some(m=>m.type==="websocket")){const m=e.filter(b=>b.type==="websocket").map(b=>b.id).join(", ");bt.warn(`fetchDataSourcesWithResults received WebSocket sources (caller should filter them out before calling): ${m}. WebSocket sources are event listeners, not data providers — they should not be passed to fetch.`)}const f=u?.ignoreAutoFetch?e.filter(m=>m.type!=="websocket"):e.filter(m=>m.auto_fetch!==!1&&m.type!=="websocket");return await Promise.all(f.map(async m=>{try{const b=await this.fetchDataSource(m,n,r,i,l);this.dataCache.set(m.id,{data:b,timestamp:Date.now()});const v=this.checkErrorCondition(m,b);if(v!==null){const S={status:v,message:`Error condition matched for ${m.id}`,data:b},_=ma(),x=_.resolve(v,{errorHandling:m.errorHandling,onError:m.onError});let k=!1;if(x.handler)if(m.loading_strategy==="blocking")_.execute(x.handler,S).catch(O=>{bt.error(`Error executing errorCondition handler for ${m.id}:`,O)}),k=!0;else try{await _.execute(x.handler,S),k=!0}catch(O){bt.error(`Error executing errorCondition handler for ${m.id}:`,O)}return m.fallback!==void 0?(this.dataCache.set(m.id,{data:m.fallback,timestamp:Date.now()}),bt.log(`Using fallback data for ${m.id} (errorCondition)`),{id:m.id,state:"success",data:m.fallback}):{id:m.id,state:"error",error:new Error(`Error condition matched: ${v}`),errorCode:v,errorHandled:k}}if(m.onSuccess)try{const S={data:b,sourceId:m.id};await this.executeOnSuccessHandler(m.onSuccess,S)}catch(S){bt.error(`Error executing onSuccess handler for ${m.id}:`,S)}return{id:m.id,state:"success",data:b}}catch(b){bt.error(`Failed to fetch data source: ${m.id}`,b);const v=b?.response?.status||b?.status||500,S=b?.response?.data,_=S?.message||b.message||"Unknown error",x={status:v,message:_,errors:S?.errors,data:S,statusText:b?.response?.statusText},k=ma(),O=k.resolve(v,{errorHandling:m.errorHandling,onError:m.onError});let M=!1;if(O.handler)if(m.loading_strategy==="blocking")k.execute(O.handler,x).catch(T=>{bt.error(`Error executing error handler for ${m.id}:`,T)}),M=!0;else try{await k.execute(O.handler,x),M=!0}catch(T){bt.error(`Error executing error handler for ${m.id}:`,T)}return m.fallback!==void 0?(this.dataCache.set(m.id,{data:m.fallback,timestamp:Date.now()}),bt.log(`Using fallback data for ${m.id}`),{id:m.id,state:"success",data:m.fallback}):(this.options.onError&&this.options.onError(b,m),{id:m.id,state:"error",error:b,errorCode:v,errorHandled:M})}}))}fetchDataSourcesInBackground(e,n={},r=new URLSearchParams,i){e.filter(u=>u.auto_fetch!==!1&&u.loading_strategy==="background"&&u.type!=="websocket").forEach(u=>{this.fetchDataSource(u,n,r).then(async d=>{this.dataCache.set(u.id,{data:d,timestamp:Date.now()});const f=this.checkErrorCondition(u,d);if(f!==null){const g={status:f,message:`Error condition matched for ${u.id}`,data:d},m=ma(),b=m.resolve(f,{errorHandling:u.errorHandling,onError:u.onError});if(b.handler)try{await m.execute(b.handler,g)}catch(v){bt.error(`Error executing errorCondition handler for ${u.id}:`,v)}u.fallback!==void 0&&(this.dataCache.set(u.id,{data:u.fallback,timestamp:Date.now()}),bt.log(`Using fallback data for ${u.id} (errorCondition)`),i&&i(u.id,u.fallback));return}if(u.onSuccess)try{const g={data:d,sourceId:u.id};await this.executeOnSuccessHandler(u.onSuccess,g)}catch(g){bt.error(`Error executing onSuccess handler for ${u.id}:`,g)}i&&i(u.id,d)}).catch(async d=>{bt.error(`Background fetch failed: ${u.id}`,d);const f=d?.response?.status||d?.status||500,g=d?.response?.data,m=g?.message||d.message||"Unknown error",b={status:f,message:m,errors:g?.errors,data:g,statusText:d?.response?.statusText},v=ma(),S=v.resolve(f,{errorHandling:u.errorHandling,onError:u.onError});if(S.handler)try{await v.execute(S.handler,b)}catch(_){bt.error(`Error executing error handler for ${u.id}:`,_)}if(u.fallback!==void 0){this.dataCache.set(u.id,{data:u.fallback,timestamp:Date.now()}),bt.log(`Using fallback data for ${u.id}`),i&&i(u.id,u.fallback);return}this.options.onError&&this.options.onError(d,u)})})}async fetchDataSource(e,n,r,i,l){switch(e.type){case"api":return this.fetchApiDataSource(e,n,r,i,l);case"static":return e.data;case"route_params":return n;case"query_params":return uy(r);default:throw new Error(`Unknown data source type: ${e.type}`)}}async fetchApiDataSource(e,n,r,i,l){if(this.options.sampleProvider?.has(e.id))return await Promise.resolve(this.options.sampleProvider.resolve(e));if(!e.endpoint)throw new Error(`API data source ${e.id} has no endpoint`);const u={route:n,query:uy(r)};i&&(u._global=i),l&&(u._local=l);let d=Zi(e.endpoint,u,{skipCache:!0});const f=e.method||"GET",m=(e.contentType?typeof e.contentType=="string"&&e.contentType.includes("{{")?Zi(e.contentType,u,{skipCache:!0}):e.contentType:"application/json")==="multipart/form-data";let b=m?{...e.params||{}}:JSON.parse(JSON.stringify(e.params||{}));Object.entries(b).forEach(([_,x])=>{typeof x=="string"&&(b[_]=yc(x,u))}),Object.keys(b).forEach(_=>{b[_]===""&&delete b[_]});const v=J_();let S=null;if(v?.isEnabled()){v.trackDataSourceDefinition({id:e.id,type:e.type,endpoint:d,method:f,autoFetch:e.auto_fetch,initLocal:e.initLocal,initGlobal:e.initGlobal});let _=d;if(f==="GET"&&Object.keys(b).length>0){const x=new URLSearchParams;Object.entries(b).forEach(([O,M])=>{Array.isArray(M)?M.forEach(T=>x.append(O,String(T))):M!=null&&x.append(O,String(M))});const k=x.toString();_=k?`${d}?${k}`:d}S=v.trackRequest(_,f,{requestBody:f!=="GET"?b:void 0,dataSourceId:e.id}),v.trackDataSourceLoading(e.id)}try{let _;const x=e.auth_mode??(e.auth_required===!0?"required":"none"),k=ga.getInstance().isAuthenticated();if(x==="required"&&!k){bt.log(`[DataSourceManager] Skipping ${e.id}: auth_mode is 'required' but no token available`),v?.isEnabled()&&(v.trackDataSourceError(e.id,"Skipped: auth_mode required but not authenticated"),S&&v.failRequest(S,"Skipped: not authenticated"));const M=new Error("Auth required but not authenticated");throw M.response={status:401,statusText:"Unauthorized",data:null},M.status=401,M._authSkipped=!0,M}const O=x==="required"||x==="optional"&&k;if(O){const M=Ia(),T=d.startsWith("/api/")?d.substring(4):d.startsWith("/api")?d.substring(4)||"/":d;this.options.onError&&bt.log(`[DataSourceManager] Normalized endpoint: ${d} -> ${T}`);const D=this.getMatchingGlobalHeaders(d,u),j={};e.headers&&Object.entries(e.headers).forEach(([pe,_e])=>{const we=yc(_e,u);we!=null&&we!==""&&(j[pe]=String(we))});const H={...D,...j},P=Object.keys(H).length>0,X=m?this.toFormData(b):b;switch(f){case"GET":_=await M.get(T,{params:b,...P&&{headers:H}});break;case"POST":P?_=await M.post(T,X,{headers:H}):_=await M.post(T,X);break;case"PUT":P?_=await M.put(T,X,{headers:H}):_=await M.put(T,X);break;case"PATCH":P?_=await M.patch(T,X,{headers:H}):_=await M.patch(T,X);break;case"DELETE":_=await M.delete(T,{params:b,...P&&{headers:H}});break;default:throw new Error(`Unsupported HTTP method: ${f}`)}}else{let M=d;if(f==="GET"){const X=new URLSearchParams(b).toString();M=X?`${d}?${X}`:d}const T={...m?{}:{"Content-Type":"application/json"},Accept:"application/json"};if(typeof window<"u"){const X=localStorage.getItem("g7_locale");X&&(T["Accept-Language"]=X)}const D=this.getMatchingGlobalHeaders(d,u);Object.assign(T,D),e.headers&&Object.entries(e.headers).forEach(([X,pe])=>{const _e=yc(pe,u);_e!=null&&_e!==""&&(T[X]=String(_e))});let j;f!=="GET"&&(m?(j=this.toFormData(b),delete T["Content-Type"]):j=JSON.stringify(b));const H=await fetch(M,{method:f,headers:T,body:j});let P;try{P=await H.json()}catch{P=null}if(S&&v?.isEnabled()&&(v.completeRequest(S,H.status,P),S=null),!H.ok){v?.isEnabled()&&v.trackDataSourceError(e.id,`HTTP ${H.status}: ${H.statusText}`);const X=new Error(`HTTP error! status: ${H.status}`);throw X.response={status:H.status,statusText:H.statusText,data:P},X.status=H.status,X}_=P,v?.isEnabled()&&v.trackDataSourceLoaded(e.id,_)}return O&&S&&v?.isEnabled()&&(v.completeRequest(S,200,_),v.trackDataSourceLoaded(e.id,_)),_}catch(_){if(S&&v?.isEnabled()){const x=_;x?.response?v.completeRequest(S,x.response.status,x.response.data):v.failRequest(S,_ instanceof Error?_.message:String(_)),v.trackDataSourceError(e.id,_ instanceof Error?_.message:String(_))}throw _}}getCachedData(e){const n=this.dataCache.get(e);if(!n)return;if(Date.now()-n.timestamp>Cc.DATA_CACHE_TTL){this.dataCache.delete(e);return}return n.data}clearCache(){this.dataCache.clear()}subscribeWebSockets(e,n,r={}){const i=[],l=e.filter(u=>u.type==="websocket");return l.length===0||l.forEach(u=>{if(!u.channel||!u.event){bt.warn(`WebSocket source ${u.id} missing channel or event`);return}let d,f;try{d=Zi(u.channel,r,{skipCache:!0}),f=Zi(u.event,r,{skipCache:!0})}catch(b){bt.error(`Failed to resolve WebSocket channel/event for source ${u.id}:`,b);return}const g=b=>!!(!b||b.trim()===""||b.includes("{{")||b.endsWith(".")||b.endsWith(":")||b.startsWith(".")||b.startsWith(":")||b.includes("..")||b.includes("::"));if(g(d)||g(f)){bt.warn(`WebSocket source ${u.id} has invalid channel/event after expression resolution, skipping. Original channel="${u.channel}", resolved="${d}". Original event="${u.event}", resolved="${f}". Available context keys: [${Object.keys(r).join(", ")}]`);return}const m=mc.subscribe(d,f,b=>{const v=u.target_source||u.id;this.dataCache.set(v,{data:b,timestamp:Date.now()}),n(v,b)},{channelType:u.channel_type||"private"});m&&i.push(m)}),i}unsubscribeWebSockets(e){e.length!==0&&e.forEach(n=>{mc.unsubscribe(n)})}async executeOnSuccessHandler(e,n){const r=this.options.actionDispatcher??lm();if(!r){bt.warn("ActionDispatcher not available, skipping onSuccess handler");return}const i=Array.isArray(e)?e:[e];for(const l of i)try{await r.dispatchAction({type:"click",...l},{data:{response:n}})}catch(u){throw bt.error("Failed to execute onSuccess handler:",u),u}}};$(Cc,"DATA_CACHE_TTL",3e5);let Sa=Cc;const Q_=new Sa,pi=dt("ModalDataSourceWrapper");function Z_(o,e){if(!o||!e)return o;const r=e.replace(/\?\./g,".").split(/\.(?![^\[]*\])/).flatMap(l=>{const u=l.match(/^([^\[]*)((?:\[\d+\])*)$/);if(u){const[,d,f]=u,g=[];d&&g.push(d);const m=f.match(/\[\d+\]/g);return m&&g.push(...m),g}return[l]}).filter(l=>l!=="");let i=o;for(const l of r){if(i==null)return;if(l.startsWith("[")&&l.endsWith("]")){const u=parseInt(l.slice(1,-1),10);i=i[u]}else i=i[l]}return i}const dy=({isOpen:o,modalId:e,dataSources:n,dataContext:r,globalStateUpdater:i,bindingEngine:l,debug:u=!1,children:d})=>{const[f,g]=I.useState(!1),[m,b]=I.useState(!1),v=I.useRef(!1),S=I.useRef(null);S.current||(S.current=new Sa);const _=I.useCallback(async()=>{if(!(!n||n.length===0)&&S.current){g(!0);try{const x=r.route||{},k=new URLSearchParams(window.location.search),O=n.map(T=>{let D={...T};if(T.endpoint&&l){const j=l.resolveBindings(T.endpoint,r,{skipCache:!0});D.endpoint=j}if(T.params&&l){const j={};Object.entries(T.params).forEach(([H,P])=>{typeof P=="string"?j[H]=l.resolveBindings(P,r,{skipCache:!0}):j[H]=P}),D.params=j}return D});u&&pi.log(`[ModalDataSourceWrapper] Modal "${e}" fetching data sources:`,O.map(T=>({id:T.id,endpoint:T.endpoint})));const M=await S.current.fetchDataSourcesWithResults(O,x,k);i&&M.forEach(T=>{if(T.state==="success"&&T.data!==void 0){const D=O.find(j=>j.id===T.id);if(D?.initGlobal){const j=T.data?.data??T.data,H=Array.isArray(D.initGlobal)?D.initGlobal:[D.initGlobal];for(const P of H)if(typeof P=="string")i({[P]:j}),u&&pi.log(`[ModalDataSourceWrapper] Modal "${e}" initGlobal: ${T.id}.data -> _global.${P}`);else if(typeof P=="object"&&P.key){const{key:X,path:pe}=P,_e=pe?Z_(j,pe):j;i({[X]:_e}),u&&pi.log(`Modal "${e}" initGlobal: ${T.id}.data${pe?"."+pe:""} -> _global.${X}`)}}}else T.state==="error"&&pi.error(`Modal "${e}" data source error:`,T.id,T.error)}),u&&pi.log(`Modal "${e}" data sources fetched successfully`)}catch(x){pi.error(`Modal "${e}" data source fetch error:`,x)}finally{g(!1),b(!0)}}},[n,r,i,l,e,u]);return I.useEffect(()=>{if(!n||n.length===0)return;const x=window.__templateApp;return x?.registerModalDataSources&&x.registerModalDataSources(e,n),()=>{x?.unregisterModalDataSources&&x.unregisterModalDataSources(e)}},[e,n]),I.useEffect(()=>{!o&&v.current&&(b(!1),u&&pi.log(`[ModalDataSourceWrapper] Modal "${e}" closed, reset fetch state`)),o&&!v.current&&n&&n.length>0&&!m&&_(),v.current=o},[o,n,m,_,e,u]),ft.jsx(ft.Fragment,{children:d})};class bc extends Error{constructor(n,r,i={}){super(r);$(this,"code");$(this,"userMessageKey");$(this,"showStack");$(this,"icon");$(this,"recoverable");this.name="TemplateEngineError",this.code=n,this.userMessageKey=r,this.showStack=i.showStack??!0,this.icon=i.icon??"fa-circle-exclamation",this.recoverable=i.recoverable??!0,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}getUserMessage(n,r){if(!r||!n)return this.userMessageKey;try{return r.translate(this.userMessageKey,n)}catch{return this.userMessageKey}}}class eA extends bc{constructor(){super("TEMPLATE_NOT_FOUND","$t:core.errors.template_not_found",{showStack:!1,icon:"fa-paint-brush",recoverable:!1}),this.name="TemplateNotFoundError"}}function fy(o){if(o instanceof bc)return o;if(o instanceof Error){const e=new bc("TEMPLATE_INIT_ERROR",o.message||"$t:core.errors.template_init_error",{showStack:!0,icon:"fa-circle-exclamation",recoverable:!0});return e.stack=o.stack,e}return new bc("TEMPLATE_INIT_ERROR","$t:core.errors.template_init_error",{showStack:!1,icon:"fa-circle-exclamation",recoverable:!0})}const tA=dt("ErrorDisplay");class ff{static render(e,n){const r=document.getElementById(e);if(!r){tA.error(`Container #${e} not found`);return}const i=n.debug&&n.showStack&&n.stackTrace,l=window.matchMedia("(prefers-color-scheme: dark)").matches,u={container:` display: flex; align-items: center; justify-content: center; @@ -178,23 +178,23 @@ Error generating stack: `+c.message+`
- +

- ${this.escapeHtml(a.title)} + ${this.escapeHtml(n.title)}

- ${this.escapeHtml(a.message)} + ${this.escapeHtml(n.message)}

- ${a.detailMessage?` + ${n.detailMessage?`

- ${this.escapeHtml(a.detailMessage)} + ${this.escapeHtml(n.detailMessage)}

`:`
`} @@ -204,12 +204,12 @@ Error generating stack: `+c.message+`

Stack Trace:

-
${this.escapeHtml(a.stackTrace)}
+
${this.escapeHtml(n.stackTrace)}
`:""} - ${a.showReloadButton?` + ${n.showReloadButton?`
- `}static renderFromError(e,a,r,i=!1,l,u,d){let f,g;if(a.userMessageKey.startsWith("$t:"))if(u&&l)try{f=u.translate(a.userMessageKey,l)}catch{f=a.userMessageKey.replace("$t:","")}else f=a.userMessageKey.replace("$t:","");else f=a.userMessageKey;if(d){const m=d;m.details?.apiMessage?g=m.details.apiMessage:m.response?.data?.message&&(g=m.response.data.message)}this.render(e,{title:r,message:f,detailMessage:g,icon:a.icon,showStack:a.showStack,stackTrace:a.stack,showReloadButton:a.recoverable,debug:i})}static escapeHtml(e){if(!e)return"";const a=document.createElement("div");return a.textContent=e,a.innerHTML}}const os=ct("Router");class U_{constructor(e){$(this,"routes",[]);$(this,"templateIdentifier");$(this,"eventHandlers",new Map);$(this,"pendingNavigation",null);$(this,"isNavigating",!1);$(this,"handlePopState",()=>{this.navigateToCurrentPath()});this.templateIdentifier=e,this.initPopstateListener()}initPopstateListener(){window.addEventListener("popstate",this.handlePopState)}on(e,a){this.eventHandlers.has(e)||this.eventHandlers.set(e,[]),this.eventHandlers.get(e).push(a)}async emit(e,...a){const r=this.eventHandlers.get(e);r&&await Promise.all(r.map(i=>i(...a)))}async loadRoutes(e){try{const a=e!==void 0&&e>0?e:null,r=await fetch(La(`/api/templates/${this.templateIdentifier}/routes`,"json",a));if(!r.ok)throw new Error(`Failed to load routes: ${r.statusText}`);const i=await r.json();if(!i.success)throw new Error("Failed to load routes from API");if(i.data&&Array.isArray(i.data.routes))this.routes=i.data.routes,os.log(`Loaded ${this.routes.length} routes${e?` (v=${e})`:""}`);else throw new Error("Invalid routes data format")}catch(a){throw os.error("Error loading routes:",a),a}}setRoutes(e){this.routes=e,os.log(`Set ${this.routes.length} routes`)}match(e){const a=this.normalizePathname(e);for(const r of this.routes){const i=this.matchPattern(r.path,a);if(i!==null)return{route:r,params:i}}return null}normalizePathname(e){return e.length>1&&e.endsWith("/")?e.replace(/\/+$/,"")||"/":e}matchPattern(e,a){const r=[];let i=e.replace(/:([^/]+)/g,(f,g)=>(r.push(g),"([^/]+)"));i.startsWith("*/")&&(i="(?:/[^/]+)?"+i.slice(1)),i=i.replace(/\//g,"\\/");const l=new RegExp(`^${i}$`),u=a.match(l);if(!u)return null;const d={};return r.forEach((f,g)=>{d[f]=u[g+1]}),d}getRoutes(){return[...this.routes]}getAuthType(e,a){return e.auth_type?e.auth_type:a.startsWith("/admin")?"admin":"user"}async navigateToCurrentPath(){const e=window.location.pathname,a=window.location.search,r=this.match(e);if(!r){os.warn(`No route matched for path: ${e}`),this.emit("routeNotFound",e);return}if(r.route.redirect){os.log(`Redirecting from ${e} to ${r.route.redirect}`),this.navigate(r.route.redirect);return}if(r.route.auth_required){const u=this.getAuthType(r.route,e),d=ha.getInstance();let f=d.isAuthenticated()&&d.getAuthType()===u;if(f||(f=await d.checkAuth(u)),!f){const g=d.getLoginRedirectUrl(u,e+a);os.log(`Not authenticated, redirecting to: ${g}`),window.location.href=g;return}}const i=new URLSearchParams(a),l={};for(const u of i.keys()){if(u in l)continue;const d=i.getAll(u);d.length>1?l[u]=d:d.length===1&&(u.endsWith("[]")?l[u]=d:l[u]=d[0])}await this.emit("routeChange",{path:e,layout:r.route.layout,endpoint:r.route.endpoint,params:{...r.route.params||{},...r.params},query:l,auth_required:r.route.auth_required,auth_type:r.route.auth_type,meta:r.route.meta})}navigate(e){if(this.isNavigating){this.pendingNavigation=e;return}this.executeNavigation(e)}async executeNavigation(e){this.isNavigating=!0,this.pendingNavigation=null;try{window.history.pushState({},"",e),await this.navigateToCurrentPath()}finally{if(this.isNavigating=!1,this.pendingNavigation){const a=this.pendingNavigation;this.executeNavigation(a)}}}}const B_=/^\/admin\/layout-editor\/([^/?#]+)\/?$/;function iy(o){const e=B_.exec(o);return e?{templateIdentifier:e[1]}:null}const zt=ct("ErrorPageHandler");class P_{constructor(e){$(this,"templateId");$(this,"layoutLoader");$(this,"locale");$(this,"debug");$(this,"renderFunction");$(this,"dataSourceManager");$(this,"globalState");$(this,"errorConfig",null);$(this,"configLoaded",!1);this.templateId=e.templateId,this.layoutLoader=e.layoutLoader,this.locale=e.locale,this.debug=e.debug,this.renderFunction=e.renderFunction,this.dataSourceManager=e.dataSourceManager,this.globalState=e.globalState||{}}async loadConfig(){if(this.configLoaded)return this.errorConfig;try{const e=await fetch(La(`/api/templates/${this.templateId}/config`,"json"));if(!e.ok)return this.debug&&zt.warn("Failed to load template config:",e.statusText),this.configLoaded=!0,null;const a=await e.json();if(!a.success||!a.data)return this.debug&&zt.warn("Invalid template config response"),this.configLoaded=!0,null;const r=a.data;return!r.error_config||!r.error_config.layouts?(this.debug&&zt.warn("No error_config found in template.json"),this.configLoaded=!0,null):(this.errorConfig=r.error_config,this.configLoaded=!0,this.debug&&zt.log("Error config loaded:",this.errorConfig),this.errorConfig)}catch(e){return zt.error("Failed to load error config:",e),this.configLoaded=!0,null}}async renderError(e,a="app"){try{const r=await this.loadConfig();if(!r)return this.debug&&zt.warn("No error config available, cannot render error page"),!1;const i=r.layouts[e]||r.layouts[String(e)];if(!i)return this.debug&&zt.warn(`No layout defined for error code: ${e}`),!1;this.debug&&zt.log(`Loading error layout: ${i} for code: ${e}`);const l=await this.layoutLoader.loadLayout(this.templateId,i);if(!l)return this.debug&&zt.error(`Failed to load error layout: ${i}`),!1;this.debug&&zt.log("Error layout loaded:",l);let u={};const d=l.data_sources||[];if(d.length>0){this.debug&&zt.log("Fetching data sources:",d.map(S=>S.id));const m=d.filter(S=>S.loading_strategy==="blocking"),b=d.filter(S=>!S.loading_strategy||S.loading_strategy==="progressive"),v=[...m,...b];if(v.length>0)try{u=await this.dataSourceManager.fetchDataSources(v,{},new URLSearchParams),this.debug&&zt.log("Data sources fetched:",Object.keys(u))}catch(S){zt.error("Failed to fetch data sources:",S)}}const f={};d.length>0&&(this.processInitOptions(d,u,f),this.debug&&zt.log("initOptions processed:",{globalKeys:Object.keys(this.globalState),localKeys:Object.keys(f)}));const g={...u,errorCode:e,_global:{...this.globalState},_local:{...f}};return await this.renderFunction({containerId:a,layoutJson:l,dataContext:g,translationContext:{templateId:this.templateId,locale:this.locale}}),this.debug&&zt.log(`Error page ${e} rendered successfully`),!0}catch(r){return zt.error(`Failed to render error page ${e}:`,r),!1}}processInitOptions(e,a,r){for(const i of e){const l=a[i.id];if(!l)continue;const u=l?.data??l;if(i.initLocal){if(typeof i.initLocal=="string")r[i.initLocal]=u,zt.log(`initLocal: ${i.id}.data -> _local.${i.initLocal}`);else if(typeof i.initLocal=="object"&&"key"in i.initLocal){const{key:d,path:f}=i.initLocal;r[d]=f?this.getValueByPath(u,f):u,zt.log(`initLocal: ${i.id}.data${f?"."+f:""} -> _local.${d}`)}}if(i.initGlobal){const d=Array.isArray(i.initGlobal)?i.initGlobal:[i.initGlobal];for(const f of d)if(typeof f=="string")this.globalState[f]=u,zt.log(`initGlobal: ${i.id}.data -> _global.${f}`);else if(typeof f=="object"&&f!==null&&"key"in f){const{key:g,path:m}=f;this.globalState[g]=m?this.getValueByPath(u,m):u,zt.log(`initGlobal: ${i.id}.data${m?"."+m:""} -> _global.${g}`)}}}}getValueByPath(e,a){return a.split(".").reduce((r,i)=>r?.[i],e)}updateGlobalState(e){this.globalState={...this.globalState,...e}}updateLocale(e){this.locale=e,this.debug&&zt.log("Locale updated:",e)}isConfigLoaded(){return this.configLoaded}async hasErrorLayout(e){const a=await this.loadConfig();return a?!!(a.layouts[e]||a.layouts[String(e)]):!1}clearConfigCache(){this.errorConfig=null,this.configLoaded=!1,this.debug&&zt.log("Config cache cleared")}}const $t=ct("ModuleAssetLoader");class q_{constructor(){$(this,"loadedAssets",new Map);$(this,"loadingPromises",new Map);$(this,"failedJsAssets",new Set)}hasFailedJsAssets(){return this.failedJsAssets.size>0}getFailedJsAssets(){return[...this.failedJsAssets]}async loadActiveExtensionAssets(e){if(!e||e.length===0){$t.log("No module assets to load");return}const a=[...e].sort((d,f)=>d.priority-f.priority);$t.log("Loading module assets:",a.map(d=>d.identifier));const r=a.filter(d=>d.css).map(d=>this.loadCSS(d.identifier,d.css)),i=a.filter(d=>d.js).map(d=>this.loadJS(d.identifier,d.js)),l=await Promise.allSettled([...r,...i]),u=l.filter(d=>d.status==="rejected");if(u.length>0){$t.warn(`Some module assets failed to load (${u.length}/${l.length}); continuing with the rest`,this.getFailedJsAssets());return}$t.log("All module assets loaded successfully")}async loadBundle(e,a,r){const i=[];if(r&&i.push(this.loadBundleCss(e,r)),a&&i.push(this.loadBundleJs(e,a)),i.length===0){$t.log(`No bundle assets to load for: ${e}`);return}await Promise.all(i)}async loadBundleCss(e,a){const r=`ext-bundle-css-${e}`;if(document.getElementById(r)){$t.log(`Bundle CSS already loaded: ${e}`);return}return new Promise(i=>{const l=document.createElement("link");l.rel="stylesheet",l.href=a,l.id=r,l.onload=()=>{$t.log(`Bundle CSS loaded: ${e}`),this.registerLoadedAsset(`bundle-${e}`,{type:"css",element:l}),i()},l.onerror=()=>{$t.warn(`Failed to load bundle CSS: ${e} (${a})`),i()},document.head.appendChild(l)})}async loadBundleJs(e,a){const r=`ext-bundle-js-${e}`;if(document.getElementById(r)){$t.log(`Bundle JS already loaded: ${e}`);return}const i=this.loadingPromises.get(r);if(i)return $t.log(`Bundle JS already loading: ${e}`),i;const l=Xg(a,{id:r},{label:`bundle JS: ${e}`}).then(()=>{$t.log(`Bundle JS loaded: ${e}`);const u=document.getElementById(r);u&&this.registerLoadedAsset(`bundle-${e}`,{type:"js",element:u}),this.loadingPromises.delete(r)}).catch(u=>{throw $t.warn(`Failed to load bundle JS: ${e} (${a})`,u),this.failedJsAssets.add(e),this.loadingPromises.delete(r),u});return this.loadingPromises.set(r,l),l}async loadCSS(e,a){const r=`module-css-${e}`;if(document.getElementById(r)){$t.log(`CSS already loaded: ${e}`);return}return new Promise((i,l)=>{const u=document.createElement("link");u.rel="stylesheet",u.href=a,u.id=r,u.onload=()=>{$t.log(`CSS loaded: ${e}`),this.registerLoadedAsset(e,{type:"css",element:u}),i()},u.onerror=()=>{$t.warn(`Failed to load CSS: ${e} (${a})`),i()},document.head.appendChild(u)})}async loadJS(e,a){const r=`module-js-${e}`;if(document.getElementById(r)){$t.log(`JS already loaded: ${e}`);return}const i=this.loadingPromises.get(e);if(i)return $t.log(`JS already loading: ${e}`),i;const l=Xg(a,{id:r},{label:`JS: ${e}`}).then(()=>{$t.log(`JS loaded: ${e}`);const u=document.getElementById(r);u&&this.registerLoadedAsset(e,{type:"js",element:u}),this.loadingPromises.delete(e)}).catch(u=>{throw $t.warn(`Failed to load JS: ${e} (${a})`,u),this.failedJsAssets.add(e),this.loadingPromises.delete(e),u});return this.loadingPromises.set(e,l),l}registerLoadedAsset(e,a){const r=this.loadedAssets.get(e)||[];r.push(a),this.loadedAssets.set(e,r)}unloadExtensionAsset(e){const a=this.loadedAssets.get(e);if(!a||a.length===0){$t.log(`No assets to unload for: ${e}`);return}a.forEach(r=>{r.element.parentNode&&(r.element.parentNode.removeChild(r.element),$t.log(`${r.type.toUpperCase()} unloaded: ${e}`))}),this.loadedAssets.delete(e),$t.log(`All assets unloaded for: ${e}`)}unloadAllAssets(){Array.from(this.loadedAssets.keys()).forEach(a=>{this.unloadExtensionAsset(a)}),$t.log("All module assets unloaded")}isLoaded(e){return this.loadedAssets.has(e)}getLoadedModules(){return Array.from(this.loadedAssets.keys())}}let uf=null;function df(){return uf||(uf=new q_),uf}function G_(){if(typeof window>"u")return[];const o=window.G7Config;if(!o?.moduleAssets)return[];const e=[];for(const[a,r]of Object.entries(o.moduleAssets)){const i=r;e.push({identifier:a,js:i.js?wr(i.js):i.js,css:i.css?wr(i.css):i.css,priority:i.priority,external:i.external})}return e}function V_(){if(typeof window>"u")return null;const o=window.G7Config;if(!o?.bundleUrls)return null;const e=o.bundleUrls;return{moduleJs:e.moduleJs?wr(e.moduleJs):e.moduleJs,moduleCss:e.moduleCss?wr(e.moduleCss):e.moduleCss,pluginJs:e.pluginJs?wr(e.pluginJs):e.pluginJs,pluginCss:e.pluginCss?wr(e.pluginCss):e.pluginCss}}function F_(){if(typeof window>"u")return[];const o=window.G7Config;if(!o?.pluginAssets)return[];const e=[];for(const[a,r]of Object.entries(o.pluginAssets)){const i=r;e.push({identifier:a,js:i.js?wr(i.js):i.js,css:i.css?wr(i.css):i.css,priority:i.priority,external:i.external})}return e}const ff=ct("SystemBannerManager");class mc{static show(e){this.banners.set(e.id,e),this.render(),ff.log(`Banner shown: ${e.id}`)}static hide(e){this.banners.delete(e)&&(this.render(),ff.log(`Banner hidden: ${e}`))}static hideAll(){this.banners.clear(),this.render(),ff.log("All banners hidden")}static detectLocale(){try{const a=window.G7Core;if(a?.locale?.current)return a.locale.current()}catch{}return(navigator.language||"ko").split("-")[0]}static resolveMessage(e,a){return typeof e=="string"?e:e[a]||e.en||e.ko||Object.values(e)[0]||""}static render(){if(typeof document>"u")return;let e=document.getElementById(this.containerId);if(this.banners.size===0){e&&(e.remove(),this.adjustAppPadding(0));return}e||(e=document.createElement("div"),e.id=this.containerId,e.style.cssText="position:fixed;top:0;left:0;right:0;z-index:99999;",document.body.prepend(e));const a=Array.from(this.banners.values()).sort((i,l)=>(i.order??0)-(l.order??0)),r=this.detectLocale();e.innerHTML=a.map(i=>{const l=this.resolveMessage(i.message,r),u=i.background||"#f59e0b",d=i.color||"white";return`
${l}
`}).join(""),requestAnimationFrame(()=>{e&&this.adjustAppPadding(e.offsetHeight)})}static adjustAppPadding(e){const a=document.getElementById("app");a&&(a.style.paddingTop=e>0?`${e}px`:"")}}$(mc,"banners",new Map),$(mc,"containerId","g7-system-banners");const B=ct("TemplateApp");function sy(o){const e={};for(const a of o.keys()){if(a in e)continue;const r=o.getAll(a);r.length>1?e[a]=r:r.length===1&&(a.endsWith("[]")?e[a]=r:e[a]=r[0])}return e}const Ca=class Ca{constructor(e){$(this,"router",null);$(this,"layoutLoader",null);$(this,"errorPageHandler",null);$(this,"config");$(this,"globalState");$(this,"globalStateListeners",new Set);$(this,"currentRouteChangeId",0);$(this,"currentDataSources",[]);$(this,"currentRawDataSources",[]);$(this,"currentRouteParams",{});$(this,"currentQueryParams",new URLSearchParams);$(this,"currentFetchedData",{});$(this,"currentLayoutName","");$(this,"templateErrorHandling",null);$(this,"currentWebSocketSubscriptions",[]);$(this,"extensionCacheVersion",0);$(this,"currentGlobalHeaders",[]);$(this,"transitionOverlayEl",null);$(this,"skeletonOverlayRoot",null);$(this,"skeletonOverlayContainer",null);$(this,"_spinnerState",null);$(this,"modalDataSources",new Map);this.globalState={sidebarOpen:!1},this.loadG7Config(),this.migrateLocaleStorage();const a=this.loadLocaleFromStorage(),r=a||e.locale||"ko";this.config={...e,locale:r},!a&&e.locale&&this.saveLocaleToStorage(e.locale)}loadG7Config(){if(typeof window<"u"&&window.G7Config){const e=window.G7Config;e.settings&&(this.globalState.settings=e.settings,B.log("Loaded settings from G7Config:",Object.keys(e.settings)),e.settings.upload&&(this.globalState.uploadSettings=e.settings.upload)),e.plugins&&(this.globalState.plugins=e.plugins,B.log("Loaded plugin settings from G7Config:",Object.keys(e.plugins))),e.modules&&(this.globalState.modules=e.modules,B.log("Loaded module settings from G7Config:",Object.keys(e.modules))),e.appConfig&&(this.globalState.appConfig=e.appConfig,B.log("Loaded appConfig from G7Config:",Object.keys(e.appConfig)))}}resolveRouteExpressions(e){const a=new wn,r={_global:this.globalState};return e.map(i=>{const l={...i};if(l.path&&l.path.includes("{{")){const u=l.path;l.path=a.resolveBindings(l.path,r),l.path=l.path.replace(/\/\/+/g,"/")||"/",l.path.includes("{{")&&(B.warn("Route expression resolution failed, using fallback:",u),l.path=u.replace(/\{\{[^}]+\}\}/g,"").replace(/\/\/+/g,"/")||"/")}if(l.redirect&&l.redirect.includes("{{")){const u=l.redirect;l.redirect=a.resolveBindings(l.redirect,r),l.redirect=l.redirect.replace(/\/\/+/g,"/")||"/",l.redirect.includes("{{")&&(B.warn("Route redirect expression resolution failed:",u),l.redirect=u.replace(/\{\{[^}]+\}\}/g,"").replace(/\/\/+/g,"/")||"/")}return l})}migrateLocaleStorage(){const e=["locale","g7_template_locale"];for(const a of e)try{const r=localStorage.getItem(a);r&&r!==localStorage.getItem(Ca.LOCALE_STORAGE_KEY)&&(localStorage.setItem(Ca.LOCALE_STORAGE_KEY,r),B.log(`Migrated locale from '${a}' to '${Ca.LOCALE_STORAGE_KEY}'`)),localStorage.removeItem(a)}catch(r){B.warn(`Failed to migrate locale key '${a}':`,r)}}async init(){try{Ks.getInstance().setDebug(this.config.debug),B.log("Initializing with config:",this.config),US();const e=da.getInstance(),a=ha.getInstance(),r=this.loadCacheVersionFromStorage()||0,[i,l,u,d,f]=await Promise.all([Ao({templateId:this.config.templateId,templateType:this.config.templateType,locale:this.config.locale,debug:this.config.debug,cacheVersion:r}),e.loadComponents(this.config.templateId,this.config.templateType),xl(La(`/api/templates/${this.config.templateId}/routes`,"json",r>0?r:null),{label:"routes.json"}).then(A=>{if(!A.ok)throw new Error(`Failed to load routes: ${A.statusText}`);return A.json()}).then(A=>{if(!A.success)throw new Error("Failed to load routes from API");return A.data}).catch(A=>{throw B.error("Error loading routes:",A),A}),a.preloadAuth(this.config.templateType==="admin"?"admin":"user"),fetch(La(`/api/templates/${this.config.templateId}/config`,"json")).then(A=>A.ok?A.json():null).then(A=>!A?.success||!A?.data?null:A.data).catch(A=>(B.warn("Error loading template config:",A),null))]);if(B.log("Template Engine initialized"),B.log("ComponentRegistry loaded"),B.log("Routes data loaded"),B.log("User info preloaded"),B.log("Template config loaded:",f),f?.cache_version!==void 0){const A=this.loadCacheVersionFromStorage();if(this.extensionCacheVersion=f.cache_version,this.saveCacheVersionToStorage(this.extensionCacheVersion),B.log("Extension cache version:",this.extensionCacheVersion),A!==null&&A!==this.extensionCacheVersion){B.log("Cache version changed, reloading routes...");const T=await xl(La(`/api/templates/${this.config.templateId}/routes`,"json",this.extensionCacheVersion),{label:"routes.json (reload)"}).then(L=>{if(!L.ok)throw new Error(`Failed to reload routes: ${L.statusText}`);return L.json()}).then(L=>{if(!L.success)throw new Error("Failed to reload routes from API");return L.data});Array.isArray(T.routes)&&(T.routes=this.resolveRouteExpressions(T.routes),Object.assign(u,T),B.log("Routes reloaded with new cache version"));try{const{TranslationEngine:L}=await Promise.resolve().then(()=>tp),M=L.getInstance();M.setCacheVersion(this.extensionCacheVersion);const R=this.config.locale||"ko",D="en";await M.loadTranslations(this.config.templateId,R,"/api",!0),R!==D&&await M.loadTranslations(this.config.templateId,D,"/api",!0),B.log("Translations reloaded with new cache version")}catch(L){B.error("Failed to reload translations:",L)}}}f?.errorHandling&&(this.templateErrorHandling=f.errorHandling,pa().setTemplateConfig(this.templateErrorHandling),B.log("Template errorHandling registered:",this.templateErrorHandling)),a.on("logout",()=>{B.log("User logged out")}),a.on("authStateChange",A=>{B.log("Auth state changed:",A)}),B.log("AuthManager event handlers registered");const g=$a(),m=this.config.templateType==="admin"?"admin":"user",b=a.getConfig(m);g.setOnUnauthorized(()=>{B.log("Unauthorized - redirecting to login page"),g.removeToken();const A=window.location.pathname+window.location.search,T=a.getLoginRedirectUrl(m,A,"session_expired");window.location.href=T}),B.log("ApiClient onUnauthorized callback registered"),this.layoutLoader=new tf(e),this.extensionCacheVersion>0&&this.layoutLoader.setCacheVersion(this.extensionCacheVersion),B.log("LayoutLoader initialized:",this.layoutLoader);const v=new va({onUnauthorized:()=>{B.warn("Unauthorized request in error page")}});if(this.errorPageHandler=new P_({templateId:this.config.templateId,layoutLoader:this.layoutLoader,locale:this.config.locale,debug:this.config.debug,renderFunction:ls,dataSourceManager:v,globalState:this.globalState}),B.log("ErrorPageHandler initialized with DataSourceManager"),await this.handleServerError()){B.log("Server error handled, skipping normal initialization");return}if(this.router=new U_(this.config.templateId),Array.isArray(u.routes)){const A=this.resolveRouteExpressions(u.routes);this.router.setRoutes(A)}else throw new Error("Invalid routes data format");B.log("Router initialized:",this.router),B.log("Routes set:",this.router.getRoutes());const{getActionDispatcher:S}=await Promise.resolve().then(()=>za),E=S();if(E&&(E.setDefaultContext({navigate:A=>this.router?.navigate(A)}),E.setGlobalStateUpdater((A,T)=>this.setGlobalState(A,T)),B.log("Navigate function and setGlobalState injected to ActionDispatcher")),await this.loadExtensionAssets(),this.reinitializeTemplateHandlers(),this.router.on("routeChange",A=>this.handleRouteChange(A)),this.router.on("routeNotFound",A=>this.handleRouteNotFound(A)),typeof window<"u"&&iy(window.location.pathname)){B.log("Layout editor mode detected — skipping router match"),await ls({containerId:"app",layoutJson:{components:[]},dataContext:{},translationContext:{templateId:this.config.templateId,locale:this.config.locale}}),B.log("Template App initialized in layout editor mode");return}this.router.navigateToCurrentPath(),B.log("Template App initialized successfully")}catch(e){B.error("Initialization failed:",e),this.showInitError(e)}}async loadExtensionAssets(){try{const e=df(),a=V_();if(!a){await this.loadExtensionAssetsIndividually();return}await e.loadBundle("module",a.moduleJs,a.moduleCss),await e.loadBundle("plugin",a.pluginJs,a.pluginCss),B.log("Extension bundle assets loaded successfully")}catch(e){B.warn("Failed to load extension assets:",e)}}async loadExtensionAssetsIndividually(){const e=df(),a=G_();a.length>0&&(B.log("Loading module assets (individual fallback):",a.map(i=>i.identifier)),await e.loadActiveExtensionAssets(a));const r=F_();r.length>0&&(B.log("Loading plugin assets (individual fallback):",r.map(i=>i.identifier)),await e.loadActiveExtensionAssets(r))}async handleRouteChange(e){const a=++this.currentRouteChangeId;window.__g7ForcedLocalFields=void 0,window.__g7ActionContext=void 0,window.__g7PendingLocalState=void 0,window.__g7LastSetLocalSnapshot=void 0,window.__g7SetLocalOverrideKeys=void 0,window.__g7SequenceLocalSync=void 0,window.__g7AutoBindingPaths=new Map;try{if(B.log("Route changed:",e,"requestId:",a),!this.layoutLoader)throw new Error("LayoutLoader is not initialized");if(!e.layout)throw new Error("Route layout is not defined");let r=e.layout;const i=r==="__preview__";i&&e.params?.token&&(r=`__preview__/${e.params.token}`);const l=await this.layoutLoader.loadLayout(this.config.templateId,r);if(a!==this.currentRouteChangeId){B.log("Route change cancelled (newer request exists):",a);return}B.log("Layout loaded:",l);const u=pa();l.errorHandling?(u.setLayoutConfig(l.errorHandling),B.log("Layout errorHandling registered:",l.errorHandling)):u.clearLayoutConfig();const d=l.data_sources||[],f=e.query||{},g=new URLSearchParams;for(const[te,he]of Object.entries(f))if(Array.isArray(he))for(const x of he)g.append(te,x);else g.set(te,he);const m={route:e.params||{},query:f,_global:this.globalState};l.scripts&&Array.isArray(l.scripts)&&await this.loadLayoutScripts(l.scripts,m);const{DataSourceManager:b,getActionDispatcher:v}=await Promise.resolve().then(()=>za),S=new b;if(i){const te=v();te&&te.setPreviewMode(!0),this.setGlobalState({__isPreview:!0}),mc.show({id:"preview-mode",message:{ko:"⚠ 미리보기 모드 — 페이지 이동이 비활성화됩니다",en:"⚠ Preview Mode — Navigation is disabled"},background:"linear-gradient(90deg, #f59e0b, #d97706)",color:"white"}),B.log("Preview mode activated")}else{const te=v();te?.isPreviewMode()&&(te.setPreviewMode(!1),mc.hide("preview-mode"))}if(this.currentGlobalHeaders=l.globalHeaders||[],this.currentGlobalHeaders.length>0){S.setGlobalHeaders(this.currentGlobalHeaders);const te=v();te&&te.setGlobalHeaders(this.currentGlobalHeaders),B.log("globalHeaders set:",this.currentGlobalHeaders.map(he=>he.pattern))}if(l.named_actions&&Object.keys(l.named_actions).length>0){const te=v();te&&te.setNamedActions(l.named_actions)}const E=S.filterByCondition(d,m);d.length!==E.length&&B.log("Data sources filtered by condition:",{before:d.map(te=>te.id),after:E.map(te=>te.id)});const A=E.filter(te=>te.loading_strategy==="blocking"),T=E.filter(te=>(te.loading_strategy||"progressive")!=="blocking"&&te.type!=="websocket"),L=Array.isArray(l.transition_overlay?.wait_for)?l.transition_overlay.wait_for:[],M=L.length>0&&E.some(te=>L.includes(te.id)&&te.type!=="websocket"&&(te.loading_strategy||"progressive")!=="background");if((A.length>0||M)&&l.transition_overlay){const te=typeof l.transition_overlay=="boolean"?{enabled:l.transition_overlay,style:"opaque"}:l.transition_overlay;te.enabled&&te.style==="skeleton"&&te.skeleton?.component&&te.target?this.renderSkeletonOverlay(te.target,te.skeleton,l,te.fallback_target):te.enabled&&te.style==="spinner"&&te.target&&this.renderSpinnerOverlay(te.target,te.spinner,te.fallback_target)}let R={},D={},U={},j={};this.currentWebSocketSubscriptions.length>0&&(B.log("Unsubscribing previous WebSocket subscriptions:",this.currentWebSocketSubscriptions),S.unsubscribeWebSockets(this.currentWebSocketSubscriptions),this.currentWebSocketSubscriptions=[]),this.currentDataSources=E,this.currentRawDataSources=d,this.currentRouteParams=e.params||{},this.currentQueryParams=g,B.log(`handleRouteChange #${a} - queryObject:`,f),B.log(`handleRouteChange #${a} - queryParams:`,g.toString()),A.length>0&&(B.log("Fetching blocking data sources:",A.map(he=>he.id)),(await S.fetchDataSourcesWithResults(A,e.params||{},g)).forEach(he=>{if(he.state==="success"&&he.data!==void 0)R[he.id]=he.data;else if(he.state==="error"&&he.error){const x=he.error,K=x.response?.data?.message;D[he.id]={message:K||he.error.message,status:x.response?.status||x.status}}}),this.processInitOptions(A,R,U,j),this.currentFetchedData={...R},B.log("Blocking data loaded:",Object.keys(R)),Object.keys(D).length>0&&B.log("Data source errors:",D),Object.keys(U).length>0&&B.log("Local state init (blocking):",Object.keys(U)),Object.keys(j).length>0&&B.log("Isolated state init (blocking):",Object.keys(j)));const P=T.length>0;if(P&&(Na.setPending(!0),B.log("Transition started before rendering")),a!==this.currentRouteChangeId){B.log("Route change cancelled after blocking data (newer request exists):",a);return}const{getState:X}=await Promise.resolve().then(()=>za),ge=X().currentDataContext||{},Ee=T.map(te=>te.id),Ce={};if(P){Ee.forEach(he=>{ge[he]!==void 0?Ce[he]=ge[he]:Ce[he]=void 0});const te=Object.keys(Ce).filter(he=>Ce[he]!==void 0);te.length>0&&B.log("Preserving previous progressive data:",te),B.log("Progressive data sources initialized:",Ee)}const $e=l.defines||{},Pe={...Ce,...e.params,...R,route:{...e.params||{},path:e.path},query:f,_global:{...this.globalState},_globalSetState:te=>this.setGlobalState(te),_dataSourceErrors:Object.keys(D).length>0?D:void 0,_localInit:Object.keys(U).length>0?U:void 0,_isolatedInit:Object.keys(j).length>0?j:void 0,_defines:Object.keys($e).length>0?$e:void 0};if(l.computed&&Object.keys(l.computed).length>0){const te=this.calculateComputed(l.computed,Pe);Object.keys(te).length>0&&(Pe._computed=te,this.globalState._computed=te,B.log("Computed values calculated:",Object.keys(te))),Pe._computedDefinitions=l.computed}const Xe=l.layout_name||e.layout;this.currentLayoutName!==""&&this.currentLayoutName!==Xe&&(B.log("_local reset due to layout change:",{from:this.currentLayoutName,to:Xe}),this.globalState._local={},nC()),this.currentLayoutName=Xe;const Q=l.initLocal||l.state;if(Q&&Object.keys(Q).length>0){this.globalState._local||(this.globalState._local={});for(const[te,he]of Object.entries(Q))this.globalState._local[te]===void 0&&(this.globalState._local[te]=JSON.parse(JSON.stringify(he)));Pe._local={...this.globalState._local},B.log("initLocal applied to _local:",Object.keys(Q))}if(l.initGlobal&&Object.keys(l.initGlobal).length>0){for(const[te,he]of Object.entries(l.initGlobal))this.globalState[te]===void 0&&(this.globalState[te]=JSON.parse(JSON.stringify(he)));B.log("initGlobal applied to _global:",Object.keys(l.initGlobal))}if(l.initIsolated&&Object.keys(l.initIsolated).length>0){for(const[te,he]of Object.entries(l.initIsolated))j[te]===void 0&&(j[te]=JSON.parse(JSON.stringify(he)));B.log("initIsolated applied:",Object.keys(l.initIsolated))}Pe._global={...this.globalState,layoutWarnings:l.warnings||[]};const fe=l.initActions||l.init_actions;if(fe&&fe.length>0){await this.executeInitActions(fe,Pe),B.log("initActions executed before render");const te=this.globalState;if(te._local){if(Object.keys(U).length>0){for(const[he,x]of Object.entries(U))te._local[he]!==void 0?te._local[he]=this.deepMerge(te._local[he],x):te._local[he]=x;B.log("localInit merged into _local after initActions:",Object.keys(U))}Pe._local=te._local,B.log("_local merged into dataContext:",te._local)}if(Pe._global={...this.globalState,layoutWarnings:l.warnings||[]},B.log("_global merged into dataContext after initActions"),l.computed&&Object.keys(l.computed).length>0){const he=this.calculateComputed(l.computed,Pe);Object.keys(he).length>0&&(Pe._computed=he,this.globalState._computed=he,B.log("Computed values recalculated after init_actions:",Object.keys(he)))}if(Object.keys(this.currentFetchedData).length>0){for(const[he,x]of Object.entries(this.currentFetchedData))Pe[he]=x;B.log("Fetched data sources merged into dataContext after initActions:",Object.keys(this.currentFetchedData))}}if(l.transition_overlay&&!this.skeletonOverlayContainer&&this.showTransitionOverlay(l.transition_overlay,l),await ls({containerId:"app",layoutJson:l,dataContext:Pe,translationContext:{templateId:this.config.templateId,locale:this.config.locale}}),B.log("Initial render complete with blocking data"),this.reattachSpinnerOverlay(),T.length>0){if(a!==this.currentRouteChangeId){B.log("Route change cancelled before progressive fetch (newer request exists):",a),Na.setPending(!1),this.hideTransitionOverlay();return}B.log("Fetching progressive/background data sources:",T.map(x=>x.id));const{updateTemplateData:te,getState:he}=await Promise.resolve().then(()=>za);try{const x=T.map(async K=>{try{const de=(await S.fetchDataSourcesWithResults([K],e.params||{},g,this.globalState))[0];if(!de){B.log(`Data source ${K.id} skipped (no fetch result)`);return}if(a!==this.currentRouteChangeId){B.log(`Data source ${K.id} fetch cancelled (newer request exists)`);return}if(de.state==="success"&&de.data!==void 0){B.log(`Progressive data source loaded: ${K.id}`),this.currentFetchedData[K.id]=de.data;const ie={};this.processInitOptions([K],{[K.id]:de.data},ie);const me=he();if(me.bindingEngine){const Se=[K.id];K.initGlobal&&Se.push("_global"),K.initLocal&&Se.push("_local"),me.bindingEngine.invalidateCacheByKeys(Se)}const Ne={[K.id]:de.data};Object.keys(ie).length>0&&(Ne._localInit=ie,Object.assign(U,ie)),K.initGlobal&&(Ne._global={...this.globalState}),te(Ne)}else if(de.state==="error"&&de.error){const ie=de.error,me=ie.response?.data?.message;D[K.id]={message:me||de.error.message,status:ie.response?.status||ie.status},B.log(`Progressive data source error: ${K.id}`,D[K.id]),te({[K.id]:null,_dataSourceErrors:{...D}})}}catch(re){B.error(`Failed to fetch data source: ${K.id}`,re)}});if(await Promise.all(x),a!==this.currentRouteChangeId){B.log("Route change cancelled after progressive fetch (newer request exists):",a);return}B.log("All progressive data sources loaded")}finally{Na.setPending(!1),this.hideTransitionOverlay()}}else this.hideTransitionOverlay();const ye=E.filter(te=>te.type==="websocket");if(ye.length>0){B.log("Subscribing WebSocket data sources:",ye.map(K=>K.id));const{updateTemplateData:te,getState:he}=await Promise.resolve().then(()=>za),x={...this.currentFetchedData,...e.params,route:{...e.params||{},path:e.path},query:f,_global:{...this.globalState}};B.log("WebSocket binding context keys:",Object.keys(x)),this.currentWebSocketSubscriptions=S.subscribeWebSockets(E,(K,re)=>{B.log(`WebSocket data received for: ${K}`,re),this.currentFetchedData[K]=re;const de=E.find(Se=>Se.id===K),ie=he();if(ie.bindingEngine){const Se=[K];de?.initGlobal&&Se.push("_global"),de?.initLocal&&Se.push("_local"),ie.bindingEngine.invalidateCacheByKeys(Se)}te({[K]:re});const Ne=E.find(Se=>Se.type==="websocket"&&(Se.target_source||Se.id)===K)?.onReceive;Array.isArray(Ne)&&Ne.length>0&&window.G7Core?.dispatch&&(async()=>{for(const He of Ne)try{const Ae=this.getActionDispatcher?.();Ae&&await Ae.dispatchAction(He,{navigate:this.getRouter?.()?(Et,kt)=>this.getRouter().navigate(Et,kt):void 0,setState:Et=>this.setGlobalState(Et),state:this.globalState,data:{...this.globalState,$args:[re],$event:re},_isDispatchFallbackContext:!0})}catch(Ae){B.error(`WebSocket onReceive action failed for ${K}:`,Ae)}})()},x),B.log("WebSocket subscriptions established:",this.currentWebSocketSubscriptions)}B.log("Layout rendered successfully")}catch(r){B.error("Route change handling failed:",r),this.hideTransitionOverlay(),this.showRouteError(r)}}processInitOptions(e,a,r,i){e.some(u=>u.refetchOnMount===!0&&u.initLocal)&&(r._forceLocalInit=Date.now(),B.log("refetchOnMount detected, forcing local state init")),e.forEach(u=>{const d=a[u.id];if(!d)return;const f=d.data??d;if(u.initLocal){if(typeof u.initLocal=="string"){let g=f;if(u.initLocalDefaults&&typeof u.initLocalDefaults=="object"){const b=this.evaluateDefaults(u.initLocalDefaults,a);g={...b,...f},B.log(`initLocalDefaults applied for ${u.initLocal}:`,Object.keys(b))}const m=this.globalState._local?.[u.initLocal];m!==void 0&&typeof m=="object"&&typeof g=="object"?(r[u.initLocal]=this.deepMerge(m,g),B.log(`initLocal (merged): ${u.id}.data -> _local.${u.initLocal}`)):(r[u.initLocal]=g,B.log(`initLocal: ${u.id}.data -> _local.${u.initLocal}`))}else if(typeof u.initLocal=="object"&&u.initLocal.key){const{key:g,path:m}=u.initLocal;let b=m?this.extractValueByPathOrExpression(f,m,u.id):f;if(u.initLocalDefaults&&typeof u.initLocalDefaults=="object"){const S=this.evaluateDefaults(u.initLocalDefaults,a);b={...S,...b},B.log(`initLocalDefaults applied for ${g}:`,Object.keys(S))}const v=this.globalState._local?.[g];v!==void 0&&typeof v=="object"&&typeof b=="object"?(r[g]=this.deepMerge(v,b),B.log(`initLocal (merged): ${u.id}.data${m?"."+m:""} -> _local.${g}`)):(r[g]=b,B.log(`initLocal: ${u.id}.data${m?"."+m:""} -> _local.${g}`))}else if(typeof u.initLocal=="object"){const g=u.initLocal._merge||"deep",m=this.flattenNestedObjectToMappings(u.initLocal);for(const{targetPath:b,sourcePath:v}of m){const S=this.extractValueByPathOrExpression(f,v,u.id);if(b.includes(".")){const E=b.split(".")[0];r[E]===void 0&&this.globalState._local?.[E]!==void 0&&(r[E]=JSON.parse(JSON.stringify(this.globalState._local[E]))),this.setValueAtPath(r,b,S,g),B.log(`initLocal map (${g}): ${u.id} ${v} -> _local.${b}`)}else{const E=this.globalState._local?.[b];g==="replace"?(r[b]=S,B.log(`initLocal map (replace): ${u.id} ${v} -> _local.${b}`)):g==="shallow"?E!==void 0&&typeof E=="object"&&typeof S=="object"?(r[b]={...E,...S},B.log(`initLocal map (shallow): ${u.id} ${v} -> _local.${b}`)):(r[b]=S,B.log(`initLocal map: ${u.id} ${v} -> _local.${b}`)):E!==void 0&&typeof E=="object"&&typeof S=="object"?(r[b]=this.deepMerge(E,S),B.log(`initLocal map (deep): ${u.id} ${v} -> _local.${b}`)):(r[b]=S,B.log(`initLocal map: ${u.id} ${v} -> _local.${b}`))}}}}if(u.initGlobal)if(typeof u.initGlobal=="object"&&!Array.isArray(u.initGlobal)&&!("key"in u.initGlobal))for(const[m,b]of Object.entries(u.initGlobal)){if(typeof b!="string"){B.warn(`initGlobal map value must be string, got ${typeof b} for key ${m}`);continue}const v=this.extractValueByPathOrExpression(f,b,u.id),S=this.globalState[m];S!==void 0&&typeof S=="object"&&typeof v=="object"?(this.globalState[m]=this.deepMerge(S,v),B.log(`initGlobal map (merged): ${u.id} ${b} -> _global.${m}`)):(this.globalState[m]=v,B.log(`initGlobal map: ${u.id} ${b} -> _global.${m}`))}else{const m=Array.isArray(u.initGlobal)?u.initGlobal:[u.initGlobal];for(const b of m)if(typeof b=="string"){const v=this.globalState[b];v!==void 0&&typeof v=="object"&&typeof f=="object"?(this.globalState[b]=this.deepMerge(v,f),B.log(`initGlobal (merged): ${u.id}.data -> _global.${b}`)):(this.globalState[b]=f,B.log(`initGlobal: ${u.id}.data -> _global.${b}`))}else if(typeof b=="object"&&b.key){const{key:v,path:S}=b,E=S?this.extractValueByPathOrExpression(f,S,u.id):f,A=this.globalState[v];A!==void 0&&typeof A=="object"&&typeof E=="object"?(this.globalState[v]=this.deepMerge(A,E),B.log(`initGlobal (merged): ${u.id}.data${S?"."+S:""} -> _global.${v}`)):(this.globalState[v]=E,B.log(`initGlobal: ${u.id}.data${S?"."+S:""} -> _global.${v}`))}}if(i&&u.initIsolated){if(typeof u.initIsolated=="string"){const g=i[u.initIsolated];g!==void 0&&typeof g=="object"&&typeof f=="object"?(i[u.initIsolated]=this.deepMerge(g,f),B.log(`initIsolated (merged): ${u.id}.data -> _isolated.${u.initIsolated}`)):(i[u.initIsolated]=f,B.log(`initIsolated: ${u.id}.data -> _isolated.${u.initIsolated}`))}else if(typeof u.initIsolated=="object"&&u.initIsolated.key){const{key:g,path:m}=u.initIsolated,b=m?this.extractValueByPathOrExpression(f,m,u.id):f,v=i[g];v!==void 0&&typeof v=="object"&&typeof b=="object"?(i[g]=this.deepMerge(v,b),B.log(`initIsolated (merged): ${u.id}.data${m?"."+m:""} -> _isolated.${g}`)):(i[g]=b,B.log(`initIsolated: ${u.id}.data${m?"."+m:""} -> _isolated.${g}`))}else if(typeof u.initIsolated=="object")for(const[g,m]of Object.entries(u.initIsolated)){if(typeof m!="string"){B.warn(`initIsolated map value must be string, got ${typeof m} for key ${g}`);continue}const b=this.extractValueByPathOrExpression(f,m,u.id),v=i[g];v!==void 0&&typeof v=="object"&&typeof b=="object"?(i[g]=this.deepMerge(v,b),B.log(`initIsolated map (merged): ${u.id} ${m} -> _isolated.${g}`)):(i[g]=b,B.log(`initIsolated map: ${u.id} ${m} -> _isolated.${g}`))}}})}evaluateDefaults(e,a){const r={};for(const[i,l]of Object.entries(e))if(typeof l=="string"&&l.startsWith("{{")&&l.endsWith("}}")){const u=l.slice(2,-2).trim();r[i]=this.evaluateExpression(u,a)}else r[i]=l;return r}evaluateExpression(e,a){try{const r=e.split("??").map(i=>i.trim());for(const i of r){if(/^['"].*['"]$/.test(i))return i.slice(1,-1);if(i==="true")return!0;if(i==="false")return!1;if(/^-?\d+(\.\d+)?$/.test(i))return Number(i);const l=this.getNestedValue(a,i);if(l!=null)return l}return}catch(r){B.warn(`Expression evaluation failed: ${e}`,r);return}}getNestedValue(e,a){const r=a.replace(/\?\./g,".");let i=e;const l=r.split(/\.(?![^\[]*\])/).flatMap(u=>{const d=u.match(/^([^\[]*)((?:\[\d+\])*)$/);if(d){const[,f,g]=d,m=[];f&&m.push(f);const b=g.match(/\[\d+\]/g);return b&&m.push(...b),m}return[u]}).filter(u=>u!=="");for(const u of l){if(i==null)return;if(u.startsWith("[")&&u.endsWith("]")){const d=parseInt(u.slice(1,-1),10);i=i[d]}else i=i[u]}return i}extractValueByPathOrExpression(e,a,r){const i=a.match(/^\{\{(.+)\}\}$/);if(i){const l=i[1].trim(),u=new wn,d={data:e,_global:this.globalState,_local:this.globalState._local||{}};try{const f=u.evaluateExpression(l,d);return B.log(`initLocal/initGlobal expression evaluated: ${a} -> `,f),f}catch(f){B.warn(`initLocal/initGlobal expression evaluation failed for ${r}:`,a,f);return}}return this.getNestedValue(e,a)}async loadLayoutScripts(e,a){const r=[];for(const i of e){if((i.if!==void 0||i.conditions!==void 0)&&!Xi({if:i.if,conditions:i.conditions},a,this.bindingEngine,`script:${i.id}`)){B.log(`Script skipped (condition not met): ${i.id}`);continue}if(document.getElementById(i.id)){B.log(`Script already loaded: ${i.id}`);continue}const u=new Promise((d,f)=>{const g=document.createElement("script");g.src=i.src,g.id=i.id,g.async=i.async??!0,g.onload=()=>{B.log(`Script loaded successfully: ${i.id}`),d()},g.onerror=()=>{B.warn(`Failed to load script: ${i.id} (${i.src})`),d()},document.head.appendChild(g)});r.push(u)}r.length>0&&(await Promise.all(r),B.log(`All scripts loaded: ${e.filter(i=>!document.getElementById(i.id)||r.length>0).map(i=>i.id).join(", ")}`))}evaluateScriptCondition(e,a){try{if(e.startsWith("{{")&&e.endsWith("}}")){const r=e.slice(2,-2).trim();return new Function("ctx",` + `}static renderFromError(e,n,r,i=!1,l,u,d){let f,g;if(n.userMessageKey.startsWith("$t:"))if(u&&l)try{f=u.translate(n.userMessageKey,l)}catch{f=n.userMessageKey.replace("$t:","")}else f=n.userMessageKey.replace("$t:","");else f=n.userMessageKey;if(d){const m=d;m.details?.apiMessage?g=m.details.apiMessage:m.response?.data?.message&&(g=m.response.data.message)}this.render(e,{title:r,message:f,detailMessage:g,icon:n.icon,showStack:n.showStack,stackTrace:n.stack,showReloadButton:n.recoverable,debug:i})}static escapeHtml(e){if(!e)return"";const n=document.createElement("div");return n.textContent=e,n.innerHTML}}const ds=dt("Router");class nA{constructor(e){$(this,"routes",[]);$(this,"templateIdentifier");$(this,"eventHandlers",new Map);$(this,"pendingNavigation",null);$(this,"isNavigating",!1);$(this,"handlePopState",()=>{this.navigateToCurrentPath()});this.templateIdentifier=e,this.initPopstateListener()}initPopstateListener(){window.addEventListener("popstate",this.handlePopState)}on(e,n){this.eventHandlers.has(e)||this.eventHandlers.set(e,[]),this.eventHandlers.get(e).push(n)}async emit(e,...n){const r=this.eventHandlers.get(e);r&&await Promise.all(r.map(i=>i(...n)))}async loadRoutes(e){try{const n=e!==void 0&&e>0?e:null,r=await fetch(Ma(`/api/templates/${this.templateIdentifier}/routes`,"json",n));if(!r.ok)throw new Error(`Failed to load routes: ${r.statusText}`);const i=await r.json();if(!i.success)throw new Error("Failed to load routes from API");if(i.data&&Array.isArray(i.data.routes))this.routes=i.data.routes,ds.log(`Loaded ${this.routes.length} routes${e?` (v=${e})`:""}`);else throw new Error("Invalid routes data format")}catch(n){throw ds.error("Error loading routes:",n),n}}setRoutes(e){this.routes=e,ds.log(`Set ${this.routes.length} routes`)}match(e){const n=this.normalizePathname(e);for(const r of this.routes){const i=this.matchPattern(r.path,n);if(i!==null)return{route:r,params:i}}return null}normalizePathname(e){return e.length>1&&e.endsWith("/")?e.replace(/\/+$/,"")||"/":e}matchPattern(e,n){const r=[];let i=e.replace(/:([^/]+)/g,(f,g)=>(r.push(g),"([^/]+)"));i.startsWith("*/")&&(i="(?:/[^/]+)?"+i.slice(1)),i=i.replace(/\//g,"\\/");const l=new RegExp(`^${i}$`),u=n.match(l);if(!u)return null;const d={};return r.forEach((f,g)=>{d[f]=u[g+1]}),d}getRoutes(){return[...this.routes]}getAuthType(e,n){return e.auth_type?e.auth_type:n.startsWith("/admin")?"admin":"user"}async navigateToCurrentPath(){const e=window.location.pathname,n=window.location.search,r=this.match(e);if(!r){ds.warn(`No route matched for path: ${e}`),this.emit("routeNotFound",e);return}if(r.route.redirect){ds.log(`Redirecting from ${e} to ${r.route.redirect}`),this.navigate(r.route.redirect);return}if(r.route.auth_required){const u=this.getAuthType(r.route,e),d=ga.getInstance();let f=d.isAuthenticated()&&d.getAuthType()===u;if(f||(f=await d.checkAuth(u)),!f){const g=d.getLoginRedirectUrl(u,e+n);ds.log(`Not authenticated, redirecting to: ${g}`),window.location.href=g;return}}const i=new URLSearchParams(n),l={};for(const u of i.keys()){if(u in l)continue;const d=i.getAll(u);d.length>1?l[u]=d:d.length===1&&(u.endsWith("[]")?l[u]=d:l[u]=d[0])}await this.emit("routeChange",{path:e,layout:r.route.layout,endpoint:r.route.endpoint,params:{...r.route.params||{},...r.params},query:l,auth_required:r.route.auth_required,auth_type:r.route.auth_type,meta:r.route.meta})}navigate(e){if(this.isNavigating){this.pendingNavigation=e;return}this.executeNavigation(e)}async executeNavigation(e){this.isNavigating=!0,this.pendingNavigation=null;try{window.history.pushState({},"",e),await this.navigateToCurrentPath()}finally{if(this.isNavigating=!1,this.pendingNavigation){const n=this.pendingNavigation;this.executeNavigation(n)}}}}const aA=/^\/admin\/layout-editor\/([^/?#]+)\/?$/;function hy(o){const e=aA.exec(o);return e?{templateIdentifier:e[1]}:null}const Pt=dt("ErrorPageHandler");class rA{constructor(e){$(this,"templateId");$(this,"layoutLoader");$(this,"locale");$(this,"debug");$(this,"renderFunction");$(this,"dataSourceManager");$(this,"globalState");$(this,"errorConfig",null);$(this,"configLoaded",!1);this.templateId=e.templateId,this.layoutLoader=e.layoutLoader,this.locale=e.locale,this.debug=e.debug,this.renderFunction=e.renderFunction,this.dataSourceManager=e.dataSourceManager,this.globalState=e.globalState||{}}async loadConfig(){if(this.configLoaded)return this.errorConfig;try{const e=await fetch(Ma(`/api/templates/${this.templateId}/config`,"json"));if(!e.ok)return this.debug&&Pt.warn("Failed to load template config:",e.statusText),this.configLoaded=!0,null;const n=await e.json();if(!n.success||!n.data)return this.debug&&Pt.warn("Invalid template config response"),this.configLoaded=!0,null;const r=n.data;return!r.error_config||!r.error_config.layouts?(this.debug&&Pt.warn("No error_config found in template.json"),this.configLoaded=!0,null):(this.errorConfig=r.error_config,this.configLoaded=!0,this.debug&&Pt.log("Error config loaded:",this.errorConfig),this.errorConfig)}catch(e){return Pt.error("Failed to load error config:",e),this.configLoaded=!0,null}}async renderError(e,n="app"){try{const r=await this.loadConfig();if(!r)return this.debug&&Pt.warn("No error config available, cannot render error page"),!1;const i=r.layouts[e]||r.layouts[String(e)];if(!i)return this.debug&&Pt.warn(`No layout defined for error code: ${e}`),!1;this.debug&&Pt.log(`Loading error layout: ${i} for code: ${e}`);const l=await this.layoutLoader.loadLayout(this.templateId,i);if(!l)return this.debug&&Pt.error(`Failed to load error layout: ${i}`),!1;this.debug&&Pt.log("Error layout loaded:",l);let u={};const d=l.data_sources||[];if(d.length>0){this.debug&&Pt.log("Fetching data sources:",d.map(S=>S.id));const m=d.filter(S=>S.loading_strategy==="blocking"),b=d.filter(S=>!S.loading_strategy||S.loading_strategy==="progressive"),v=[...m,...b];if(v.length>0)try{u=await this.dataSourceManager.fetchDataSources(v,{},new URLSearchParams),this.debug&&Pt.log("Data sources fetched:",Object.keys(u))}catch(S){Pt.error("Failed to fetch data sources:",S)}}const f={};d.length>0&&(this.processInitOptions(d,u,f),this.debug&&Pt.log("initOptions processed:",{globalKeys:Object.keys(this.globalState),localKeys:Object.keys(f)}));const g={...u,errorCode:e,_global:{...this.globalState},_local:{...f}};return await this.renderFunction({containerId:n,layoutJson:l,dataContext:g,translationContext:{templateId:this.templateId,locale:this.locale}}),this.debug&&Pt.log(`Error page ${e} rendered successfully`),!0}catch(r){return Pt.error(`Failed to render error page ${e}:`,r),!1}}processInitOptions(e,n,r){for(const i of e){const l=n[i.id];if(!l)continue;const u=l?.data??l;if(i.initLocal){if(typeof i.initLocal=="string")r[i.initLocal]=u,Pt.log(`initLocal: ${i.id}.data -> _local.${i.initLocal}`);else if(typeof i.initLocal=="object"&&"key"in i.initLocal){const{key:d,path:f}=i.initLocal;r[d]=f?this.getValueByPath(u,f):u,Pt.log(`initLocal: ${i.id}.data${f?"."+f:""} -> _local.${d}`)}}if(i.initGlobal){const d=Array.isArray(i.initGlobal)?i.initGlobal:[i.initGlobal];for(const f of d)if(typeof f=="string")this.globalState[f]=u,Pt.log(`initGlobal: ${i.id}.data -> _global.${f}`);else if(typeof f=="object"&&f!==null&&"key"in f){const{key:g,path:m}=f;this.globalState[g]=m?this.getValueByPath(u,m):u,Pt.log(`initGlobal: ${i.id}.data${m?"."+m:""} -> _global.${g}`)}}}}getValueByPath(e,n){return n.split(".").reduce((r,i)=>r?.[i],e)}updateGlobalState(e){this.globalState={...this.globalState,...e}}updateLocale(e){this.locale=e,this.debug&&Pt.log("Locale updated:",e)}isConfigLoaded(){return this.configLoaded}async hasErrorLayout(e){const n=await this.loadConfig();return n?!!(n.layouts[e]||n.layouts[String(e)]):!1}clearConfigCache(){this.errorConfig=null,this.configLoaded=!1,this.debug&&Pt.log("Config cache cleared")}}const Ht=dt("ModuleAssetLoader");class iA{constructor(){$(this,"loadedAssets",new Map);$(this,"loadingPromises",new Map);$(this,"failedJsAssets",new Set)}hasFailedJsAssets(){return this.failedJsAssets.size>0}getFailedJsAssets(){return[...this.failedJsAssets]}async loadActiveExtensionAssets(e){if(!e||e.length===0){Ht.log("No module assets to load");return}const n=[...e].sort((d,f)=>d.priority-f.priority);Ht.log("Loading module assets:",n.map(d=>d.identifier));const r=n.filter(d=>d.css).map(d=>this.loadCSS(d.identifier,d.css)),i=n.filter(d=>d.js).map(d=>this.loadJS(d.identifier,d.js)),l=await Promise.allSettled([...r,...i]),u=l.filter(d=>d.status==="rejected");if(u.length>0){Ht.warn(`Some module assets failed to load (${u.length}/${l.length}); continuing with the rest`,this.getFailedJsAssets());return}Ht.log("All module assets loaded successfully")}async loadBundle(e,n,r){const i=[];if(r&&i.push(this.loadBundleCss(e,r)),n&&i.push(this.loadBundleJs(e,n)),i.length===0){Ht.log(`No bundle assets to load for: ${e}`);return}await Promise.all(i)}async loadBundleCss(e,n){const r=`ext-bundle-css-${e}`;if(document.getElementById(r)){Ht.log(`Bundle CSS already loaded: ${e}`);return}return new Promise(i=>{const l=document.createElement("link");l.rel="stylesheet",l.href=n,l.id=r,l.onload=()=>{Ht.log(`Bundle CSS loaded: ${e}`),this.registerLoadedAsset(`bundle-${e}`,{type:"css",element:l}),i()},l.onerror=()=>{Ht.warn(`Failed to load bundle CSS: ${e} (${n})`),i()},document.head.appendChild(l)})}async loadBundleJs(e,n){const r=`ext-bundle-js-${e}`;if(document.getElementById(r)){Ht.log(`Bundle JS already loaded: ${e}`);return}const i=this.loadingPromises.get(r);if(i)return Ht.log(`Bundle JS already loading: ${e}`),i;const l=Zg(n,{id:r},{label:`bundle JS: ${e}`}).then(()=>{Ht.log(`Bundle JS loaded: ${e}`);const u=document.getElementById(r);u&&this.registerLoadedAsset(`bundle-${e}`,{type:"js",element:u}),this.loadingPromises.delete(r)}).catch(u=>{throw Ht.warn(`Failed to load bundle JS: ${e} (${n})`,u),this.failedJsAssets.add(e),this.loadingPromises.delete(r),u});return this.loadingPromises.set(r,l),l}async loadCSS(e,n){const r=`module-css-${e}`;if(document.getElementById(r)){Ht.log(`CSS already loaded: ${e}`);return}return new Promise((i,l)=>{const u=document.createElement("link");u.rel="stylesheet",u.href=n,u.id=r,u.onload=()=>{Ht.log(`CSS loaded: ${e}`),this.registerLoadedAsset(e,{type:"css",element:u}),i()},u.onerror=()=>{Ht.warn(`Failed to load CSS: ${e} (${n})`),i()},document.head.appendChild(u)})}async loadJS(e,n){const r=`module-js-${e}`;if(document.getElementById(r)){Ht.log(`JS already loaded: ${e}`);return}const i=this.loadingPromises.get(e);if(i)return Ht.log(`JS already loading: ${e}`),i;const l=Zg(n,{id:r},{label:`JS: ${e}`}).then(()=>{Ht.log(`JS loaded: ${e}`);const u=document.getElementById(r);u&&this.registerLoadedAsset(e,{type:"js",element:u}),this.loadingPromises.delete(e)}).catch(u=>{throw Ht.warn(`Failed to load JS: ${e} (${n})`,u),this.failedJsAssets.add(e),this.loadingPromises.delete(e),u});return this.loadingPromises.set(e,l),l}registerLoadedAsset(e,n){const r=this.loadedAssets.get(e)||[];r.push(n),this.loadedAssets.set(e,r)}unloadExtensionAsset(e){const n=this.loadedAssets.get(e);if(!n||n.length===0){Ht.log(`No assets to unload for: ${e}`);return}n.forEach(r=>{r.element.parentNode&&(r.element.parentNode.removeChild(r.element),Ht.log(`${r.type.toUpperCase()} unloaded: ${e}`))}),this.loadedAssets.delete(e),Ht.log(`All assets unloaded for: ${e}`)}unloadAllAssets(){Array.from(this.loadedAssets.keys()).forEach(n=>{this.unloadExtensionAsset(n)}),Ht.log("All module assets unloaded")}isLoaded(e){return this.loadedAssets.has(e)}getLoadedModules(){return Array.from(this.loadedAssets.keys())}}let hf=null;function gf(){return hf||(hf=new iA),hf}function sA(){if(typeof window>"u")return[];const o=window.G7Config;if(!o?.moduleAssets)return[];const e=[];for(const[n,r]of Object.entries(o.moduleAssets)){const i=r;e.push({identifier:n,js:i.js?Cr(i.js):i.js,css:i.css?Cr(i.css):i.css,priority:i.priority,external:i.external})}return e}function oA(){if(typeof window>"u")return null;const o=window.G7Config;if(!o?.bundleUrls)return null;const e=o.bundleUrls;return{moduleJs:e.moduleJs?Cr(e.moduleJs):e.moduleJs,moduleCss:e.moduleCss?Cr(e.moduleCss):e.moduleCss,pluginJs:e.pluginJs?Cr(e.pluginJs):e.pluginJs,pluginCss:e.pluginCss?Cr(e.pluginCss):e.pluginCss}}function lA(){if(typeof window>"u")return[];const o=window.G7Config;if(!o?.pluginAssets)return[];const e=[];for(const[n,r]of Object.entries(o.pluginAssets)){const i=r;e.push({identifier:n,js:i.js?Cr(i.js):i.js,css:i.css?Cr(i.css):i.css,priority:i.priority,external:i.external})}return e}const pf=dt("SystemBannerManager");class vc{static show(e){this.banners.set(e.id,e),this.render(),pf.log(`Banner shown: ${e.id}`)}static hide(e){this.banners.delete(e)&&(this.render(),pf.log(`Banner hidden: ${e}`))}static hideAll(){this.banners.clear(),this.render(),pf.log("All banners hidden")}static detectLocale(){try{const n=window.G7Core;if(n?.locale?.current)return n.locale.current()}catch{}return(navigator.language||"ko").split("-")[0]}static resolveMessage(e,n){return typeof e=="string"?e:e[n]||e.en||e.ko||Object.values(e)[0]||""}static render(){if(typeof document>"u")return;let e=document.getElementById(this.containerId);if(this.banners.size===0){e&&(e.remove(),this.adjustAppPadding(0));return}e||(e=document.createElement("div"),e.id=this.containerId,e.style.cssText="position:fixed;top:0;left:0;right:0;z-index:99999;",document.body.prepend(e));const n=Array.from(this.banners.values()).sort((i,l)=>(i.order??0)-(l.order??0)),r=this.detectLocale();e.innerHTML=n.map(i=>{const l=this.resolveMessage(i.message,r),u=i.background||"#f59e0b",d=i.color||"white";return`
${l}
`}).join(""),requestAnimationFrame(()=>{e&&this.adjustAppPadding(e.offsetHeight)})}static adjustAppPadding(e){const n=document.getElementById("app");n&&(n.style.paddingTop=e>0?`${e}px`:"")}}$(vc,"banners",new Map),$(vc,"containerId","g7-system-banners");const B=dt("TemplateApp");function gy(o){const e={};for(const n of o.keys()){if(n in e)continue;const r=o.getAll(n);r.length>1?e[n]=r:r.length===1&&(n.endsWith("[]")?e[n]=r:e[n]=r[0])}return e}const Ea=class Ea{constructor(e){$(this,"router",null);$(this,"layoutLoader",null);$(this,"errorPageHandler",null);$(this,"config");$(this,"globalState");$(this,"globalStateListeners",new Set);$(this,"currentRouteChangeId",0);$(this,"currentDataSources",[]);$(this,"currentRawDataSources",[]);$(this,"currentRouteParams",{});$(this,"currentQueryParams",new URLSearchParams);$(this,"currentFetchedData",{});$(this,"currentLayoutName","");$(this,"templateErrorHandling",null);$(this,"currentWebSocketSubscriptions",[]);$(this,"extensionCacheVersion",0);$(this,"currentGlobalHeaders",[]);$(this,"transitionOverlayEl",null);$(this,"skeletonOverlayRoot",null);$(this,"skeletonOverlayContainer",null);$(this,"_spinnerState",null);$(this,"modalDataSources",new Map);this.globalState={sidebarOpen:!1},this.loadG7Config(),this.migrateLocaleStorage();const n=this.loadLocaleFromStorage(),r=n||e.locale||"ko";this.config={...e,locale:r},!n&&e.locale&&this.saveLocaleToStorage(e.locale)}loadG7Config(){if(typeof window<"u"&&window.G7Config){const e=window.G7Config;e.settings&&(this.globalState.settings=e.settings,B.log("Loaded settings from G7Config:",Object.keys(e.settings)),e.settings.upload&&(this.globalState.uploadSettings=e.settings.upload)),e.plugins&&(this.globalState.plugins=e.plugins,B.log("Loaded plugin settings from G7Config:",Object.keys(e.plugins))),e.modules&&(this.globalState.modules=e.modules,B.log("Loaded module settings from G7Config:",Object.keys(e.modules))),e.appConfig&&(this.globalState.appConfig=e.appConfig,B.log("Loaded appConfig from G7Config:",Object.keys(e.appConfig)))}}resolveRouteExpressions(e){const n=new Rn,r={_global:this.globalState};return e.map(i=>{const l={...i};if(l.path&&l.path.includes("{{")){const u=l.path;l.path=n.resolveBindings(l.path,r),l.path=l.path.replace(/\/\/+/g,"/")||"/",l.path.includes("{{")&&(B.warn("Route expression resolution failed, using fallback:",u),l.path=u.replace(/\{\{[^}]+\}\}/g,"").replace(/\/\/+/g,"/")||"/")}if(l.redirect&&l.redirect.includes("{{")){const u=l.redirect;l.redirect=n.resolveBindings(l.redirect,r),l.redirect=l.redirect.replace(/\/\/+/g,"/")||"/",l.redirect.includes("{{")&&(B.warn("Route redirect expression resolution failed:",u),l.redirect=u.replace(/\{\{[^}]+\}\}/g,"").replace(/\/\/+/g,"/")||"/")}return l})}migrateLocaleStorage(){const e=["locale","g7_template_locale"];for(const n of e)try{const r=localStorage.getItem(n);r&&r!==localStorage.getItem(Ea.LOCALE_STORAGE_KEY)&&(localStorage.setItem(Ea.LOCALE_STORAGE_KEY,r),B.log(`Migrated locale from '${n}' to '${Ea.LOCALE_STORAGE_KEY}'`)),localStorage.removeItem(n)}catch(r){B.warn(`Failed to migrate locale key '${n}':`,r)}}async init(){try{Js.getInstance().setDebug(this.config.debug),B.log("Initializing with config:",this.config),KS();const e=fa.getInstance(),n=ga.getInstance(),r=this.loadCacheVersionFromStorage()||0,[i,l,u,d,f]=await Promise.all([ko({templateId:this.config.templateId,templateType:this.config.templateType,locale:this.config.locale,debug:this.config.debug,cacheVersion:r}),e.loadComponents(this.config.templateId,this.config.templateType),Dl(Ma(`/api/templates/${this.config.templateId}/routes`,"json",r>0?r:null),{label:"routes.json"}).then(x=>{if(!x.ok)throw new Error(`Failed to load routes: ${x.statusText}`);return x.json()}).then(x=>{if(!x.success)throw new Error("Failed to load routes from API");return x.data}).catch(x=>{throw B.error("Error loading routes:",x),x}),n.preloadAuth(this.config.templateType==="admin"?"admin":"user"),fetch(Ma(`/api/templates/${this.config.templateId}/config`,"json")).then(x=>x.ok?x.json():null).then(x=>!x?.success||!x?.data?null:x.data).catch(x=>(B.warn("Error loading template config:",x),null))]);if(B.log("Template Engine initialized"),B.log("ComponentRegistry loaded"),B.log("Routes data loaded"),B.log("User info preloaded"),B.log("Template config loaded:",f),f?.cache_version!==void 0){const x=this.loadCacheVersionFromStorage();if(this.extensionCacheVersion=f.cache_version,this.saveCacheVersionToStorage(this.extensionCacheVersion),B.log("Extension cache version:",this.extensionCacheVersion),x!==null&&x!==this.extensionCacheVersion){B.log("Cache version changed, reloading routes...");const k=await Dl(Ma(`/api/templates/${this.config.templateId}/routes`,"json",this.extensionCacheVersion),{label:"routes.json (reload)"}).then(O=>{if(!O.ok)throw new Error(`Failed to reload routes: ${O.statusText}`);return O.json()}).then(O=>{if(!O.success)throw new Error("Failed to reload routes from API");return O.data});Array.isArray(k.routes)&&(k.routes=this.resolveRouteExpressions(k.routes),Object.assign(u,k),B.log("Routes reloaded with new cache version"));try{const{TranslationEngine:O}=await Promise.resolve().then(()=>rp),M=O.getInstance();M.setCacheVersion(this.extensionCacheVersion);const T=this.config.locale||"ko",D="en";await M.loadTranslations(this.config.templateId,T,"/api",!0),T!==D&&await M.loadTranslations(this.config.templateId,D,"/api",!0),B.log("Translations reloaded with new cache version")}catch(O){B.error("Failed to reload translations:",O)}}}f?.errorHandling&&(this.templateErrorHandling=f.errorHandling,ma().setTemplateConfig(this.templateErrorHandling),B.log("Template errorHandling registered:",this.templateErrorHandling)),n.on("logout",()=>{B.log("User logged out")}),n.on("authStateChange",x=>{B.log("Auth state changed:",x)}),B.log("AuthManager event handlers registered");const g=Ia(),m=this.config.templateType==="admin"?"admin":"user",b=n.getConfig(m);g.setOnUnauthorized(()=>{B.log("Unauthorized - redirecting to login page"),g.removeToken();const x=window.location.pathname+window.location.search,k=n.getLoginRedirectUrl(m,x,"session_expired");window.location.href=k}),B.log("ApiClient onUnauthorized callback registered"),this.layoutLoader=new sf(e),this.extensionCacheVersion>0&&this.layoutLoader.setCacheVersion(this.extensionCacheVersion),B.log("LayoutLoader initialized:",this.layoutLoader);const v=new Sa({onUnauthorized:()=>{B.warn("Unauthorized request in error page")}});if(this.errorPageHandler=new rA({templateId:this.config.templateId,layoutLoader:this.layoutLoader,locale:this.config.locale,debug:this.config.debug,renderFunction:fs,dataSourceManager:v,globalState:this.globalState}),B.log("ErrorPageHandler initialized with DataSourceManager"),await this.handleServerError()){B.log("Server error handled, skipping normal initialization");return}if(this.router=new nA(this.config.templateId),Array.isArray(u.routes)){const x=this.resolveRouteExpressions(u.routes);this.router.setRoutes(x)}else throw new Error("Invalid routes data format");B.log("Router initialized:",this.router),B.log("Routes set:",this.router.getRoutes());const{getActionDispatcher:S}=await Promise.resolve().then(()=>Ua),_=S();if(_&&(_.setDefaultContext({navigate:x=>this.router?.navigate(x)}),_.setGlobalStateUpdater((x,k)=>this.setGlobalState(x,k)),B.log("Navigate function and setGlobalState injected to ActionDispatcher")),await this.loadExtensionAssets(),this.reinitializeTemplateHandlers(),this.router.on("routeChange",x=>this.handleRouteChange(x)),this.router.on("routeNotFound",x=>this.handleRouteNotFound(x)),typeof window<"u"&&hy(window.location.pathname)){B.log("Layout editor mode detected — skipping router match"),await fs({containerId:"app",layoutJson:{components:[]},dataContext:{},translationContext:{templateId:this.config.templateId,locale:this.config.locale}}),B.log("Template App initialized in layout editor mode");return}this.router.navigateToCurrentPath(),B.log("Template App initialized successfully")}catch(e){B.error("Initialization failed:",e),this.showInitError(e)}}async loadExtensionAssets(){try{const e=gf(),n=oA();if(!n){await this.loadExtensionAssetsIndividually();return}await e.loadBundle("module",n.moduleJs,n.moduleCss),await e.loadBundle("plugin",n.pluginJs,n.pluginCss),B.log("Extension bundle assets loaded successfully")}catch(e){B.warn("Failed to load extension assets:",e)}}async loadExtensionAssetsIndividually(){const e=gf(),n=sA();n.length>0&&(B.log("Loading module assets (individual fallback):",n.map(i=>i.identifier)),await e.loadActiveExtensionAssets(n));const r=lA();r.length>0&&(B.log("Loading plugin assets (individual fallback):",r.map(i=>i.identifier)),await e.loadActiveExtensionAssets(r))}async handleRouteChange(e){const n=++this.currentRouteChangeId;window.__g7ForcedLocalFields=void 0,window.__g7ActionContext=void 0,window.__g7PendingLocalState=void 0,window.__g7LastSetLocalSnapshot=void 0,window.__g7SetLocalOverrideKeys=void 0,window.__g7SequenceLocalSync=void 0,window.__g7AutoBindingPaths=new Map;try{if(B.log("Route changed:",e,"requestId:",n),!this.layoutLoader)throw new Error("LayoutLoader is not initialized");if(!e.layout)throw new Error("Route layout is not defined");let r=e.layout;const i=r==="__preview__";i&&e.params?.token&&(r=`__preview__/${e.params.token}`);const l=await this.layoutLoader.loadLayout(this.config.templateId,r);if(n!==this.currentRouteChangeId){B.log("Route change cancelled (newer request exists):",n);return}B.log("Layout loaded:",l);const u=ma();l.errorHandling?(u.setLayoutConfig(l.errorHandling),B.log("Layout errorHandling registered:",l.errorHandling)):u.clearLayoutConfig();const d=l.data_sources||[],f=e.query||{},g=new URLSearchParams;for(const[ae,ge]of Object.entries(f))if(Array.isArray(ge))for(const A of ge)g.append(ae,A);else g.set(ae,ge);const m={route:e.params||{},query:f,_global:this.globalState};l.scripts&&Array.isArray(l.scripts)&&await this.loadLayoutScripts(l.scripts,m);const{DataSourceManager:b,getActionDispatcher:v}=await Promise.resolve().then(()=>Ua),S=new b;if(i){const ae=v();ae&&ae.setPreviewMode(!0),this.setGlobalState({__isPreview:!0}),vc.show({id:"preview-mode",message:{ko:"⚠ 미리보기 모드 — 페이지 이동이 비활성화됩니다",en:"⚠ Preview Mode — Navigation is disabled"},background:"linear-gradient(90deg, #f59e0b, #d97706)",color:"white"}),B.log("Preview mode activated")}else{const ae=v();ae?.isPreviewMode()&&(ae.setPreviewMode(!1),vc.hide("preview-mode"))}if(this.currentGlobalHeaders=l.globalHeaders||[],this.currentGlobalHeaders.length>0){S.setGlobalHeaders(this.currentGlobalHeaders);const ae=v();ae&&ae.setGlobalHeaders(this.currentGlobalHeaders),B.log("globalHeaders set:",this.currentGlobalHeaders.map(ge=>ge.pattern))}if(l.named_actions&&Object.keys(l.named_actions).length>0){const ae=v();ae&&ae.setNamedActions(l.named_actions)}const _=S.filterByCondition(d,m);d.length!==_.length&&B.log("Data sources filtered by condition:",{before:d.map(ae=>ae.id),after:_.map(ae=>ae.id)});const x=_.filter(ae=>ae.loading_strategy==="blocking"),k=_.filter(ae=>(ae.loading_strategy||"progressive")!=="blocking"&&ae.type!=="websocket"),O=Array.isArray(l.transition_overlay?.wait_for)?l.transition_overlay.wait_for:[],M=O.length>0&&_.some(ae=>O.includes(ae.id)&&ae.type!=="websocket"&&(ae.loading_strategy||"progressive")!=="background");if((x.length>0||M)&&l.transition_overlay){const ae=typeof l.transition_overlay=="boolean"?{enabled:l.transition_overlay,style:"opaque"}:l.transition_overlay;ae.enabled&&ae.style==="skeleton"&&ae.skeleton?.component&&ae.target?this.renderSkeletonOverlay(ae.target,ae.skeleton,l,ae.fallback_target):ae.enabled&&ae.style==="spinner"&&ae.target&&this.renderSpinnerOverlay(ae.target,ae.spinner,ae.fallback_target)}let T={},D={},j={},H={};this.currentWebSocketSubscriptions.length>0&&(B.log("Unsubscribing previous WebSocket subscriptions:",this.currentWebSocketSubscriptions),S.unsubscribeWebSockets(this.currentWebSocketSubscriptions),this.currentWebSocketSubscriptions=[]),this.currentDataSources=_,this.currentRawDataSources=d,this.currentRouteParams=e.params||{},this.currentQueryParams=g,B.log(`handleRouteChange #${n} - queryObject:`,f),B.log(`handleRouteChange #${n} - queryParams:`,g.toString()),x.length>0&&(B.log("Fetching blocking data sources:",x.map(ge=>ge.id)),(await S.fetchDataSourcesWithResults(x,e.params||{},g)).forEach(ge=>{if(ge.state==="success"&&ge.data!==void 0)T[ge.id]=ge.data;else if(ge.state==="error"&&ge.error){const A=ge.error,K=A.response?.data?.message;D[ge.id]={message:K||ge.error.message,status:A.response?.status||A.status}}}),this.processInitOptions(x,T,j,H),this.currentFetchedData={...T},B.log("Blocking data loaded:",Object.keys(T)),Object.keys(D).length>0&&B.log("Data source errors:",D),Object.keys(j).length>0&&B.log("Local state init (blocking):",Object.keys(j)),Object.keys(H).length>0&&B.log("Isolated state init (blocking):",Object.keys(H)));const P=k.length>0;if(P&&(Ha.setPending(!0),B.log("Transition started before rendering")),n!==this.currentRouteChangeId){B.log("Route change cancelled after blocking data (newer request exists):",n);return}const{getState:X}=await Promise.resolve().then(()=>Ua),pe=X().currentDataContext||{},_e=k.map(ae=>ae.id),we={};if(P){_e.forEach(ge=>{pe[ge]!==void 0?we[ge]=pe[ge]:we[ge]=void 0});const ae=Object.keys(we).filter(ge=>we[ge]!==void 0);ae.length>0&&B.log("Preserving previous progressive data:",ae),B.log("Progressive data sources initialized:",_e)}const Me=l.defines||{},qe={...we,...e.params,...T,route:{...e.params||{},path:e.path},query:f,_global:{...this.globalState},_globalSetState:ae=>this.setGlobalState(ae),_dataSourceErrors:Object.keys(D).length>0?D:void 0,_localInit:Object.keys(j).length>0?j:void 0,_isolatedInit:Object.keys(H).length>0?H:void 0,_defines:Object.keys(Me).length>0?Me:void 0};if(l.computed&&Object.keys(l.computed).length>0){const ae=this.calculateComputed(l.computed,qe);Object.keys(ae).length>0&&(qe._computed=ae,this.globalState._computed=ae,B.log("Computed values calculated:",Object.keys(ae))),qe._computedDefinitions=l.computed}const Je=l.layout_name||e.layout;this.currentLayoutName!==""&&this.currentLayoutName!==Je&&(B.log("_local reset due to layout change:",{from:this.currentLayoutName,to:Je}),this.globalState._local={},bC()),this.currentLayoutName=Je;const Q=l.initLocal||l.state;if(Q&&Object.keys(Q).length>0){this.globalState._local||(this.globalState._local={});for(const[ae,ge]of Object.entries(Q))this.globalState._local[ae]===void 0&&(this.globalState._local[ae]=JSON.parse(JSON.stringify(ge)));qe._local={...this.globalState._local},B.log("initLocal applied to _local:",Object.keys(Q))}if(l.initGlobal&&Object.keys(l.initGlobal).length>0){for(const[ae,ge]of Object.entries(l.initGlobal))this.globalState[ae]===void 0&&(this.globalState[ae]=JSON.parse(JSON.stringify(ge)));B.log("initGlobal applied to _global:",Object.keys(l.initGlobal))}if(l.initIsolated&&Object.keys(l.initIsolated).length>0){for(const[ae,ge]of Object.entries(l.initIsolated))H[ae]===void 0&&(H[ae]=JSON.parse(JSON.stringify(ge)));B.log("initIsolated applied:",Object.keys(l.initIsolated))}qe._global={...this.globalState,layoutWarnings:l.warnings||[]};const fe=l.initActions||l.init_actions;if(fe&&fe.length>0){await this.executeInitActions(fe,qe),B.log("initActions executed before render");const ae=this.globalState;if(ae._local){if(Object.keys(j).length>0){for(const[ge,A]of Object.entries(j))ae._local[ge]!==void 0?ae._local[ge]=this.deepMerge(ae._local[ge],A):ae._local[ge]=A;B.log("localInit merged into _local after initActions:",Object.keys(j))}qe._local=ae._local,B.log("_local merged into dataContext:",ae._local)}if(qe._global={...this.globalState,layoutWarnings:l.warnings||[]},B.log("_global merged into dataContext after initActions"),l.computed&&Object.keys(l.computed).length>0){const ge=this.calculateComputed(l.computed,qe);Object.keys(ge).length>0&&(qe._computed=ge,this.globalState._computed=ge,B.log("Computed values recalculated after init_actions:",Object.keys(ge)))}if(Object.keys(this.currentFetchedData).length>0){for(const[ge,A]of Object.entries(this.currentFetchedData))qe[ge]=A;B.log("Fetched data sources merged into dataContext after initActions:",Object.keys(this.currentFetchedData))}}if(l.transition_overlay&&!this.skeletonOverlayContainer&&this.showTransitionOverlay(l.transition_overlay,l),await fs({containerId:"app",layoutJson:l,dataContext:qe,translationContext:{templateId:this.config.templateId,locale:this.config.locale}}),B.log("Initial render complete with blocking data"),this.reattachSpinnerOverlay(),k.length>0){if(n!==this.currentRouteChangeId){B.log("Route change cancelled before progressive fetch (newer request exists):",n),Ha.setPending(!1),this.hideTransitionOverlay();return}B.log("Fetching progressive/background data sources:",k.map(A=>A.id));const{updateTemplateData:ae,getState:ge}=await Promise.resolve().then(()=>Ua);try{const A=k.map(async K=>{try{const he=(await S.fetchDataSourcesWithResults([K],e.params||{},g,this.globalState))[0];if(!he){B.log(`Data source ${K.id} skipped (no fetch result)`);return}if(n!==this.currentRouteChangeId){B.log(`Data source ${K.id} fetch cancelled (newer request exists)`);return}if(he.state==="success"&&he.data!==void 0){B.log(`Progressive data source loaded: ${K.id}`),this.currentFetchedData[K.id]=he.data;const le={};this.processInitOptions([K],{[K.id]:he.data},le);const de=ge();if(de.bindingEngine){const He=[K.id];K.initGlobal&&He.push("_global"),K.initLocal&&He.push("_local"),de.bindingEngine.invalidateCacheByKeys(He)}const Oe={[K.id]:he.data};Object.keys(le).length>0&&(Oe._localInit=le,Object.assign(j,le)),K.initGlobal&&(Oe._global={...this.globalState}),ae(Oe)}else if(he.state==="error"&&he.error){const le=he.error,de=le.response?.data?.message;D[K.id]={message:de||he.error.message,status:le.response?.status||le.status},B.log(`Progressive data source error: ${K.id}`,D[K.id]),ae({[K.id]:null,_dataSourceErrors:{...D}})}}catch(ue){B.error(`Failed to fetch data source: ${K.id}`,ue)}});if(await Promise.all(A),n!==this.currentRouteChangeId){B.log("Route change cancelled after progressive fetch (newer request exists):",n);return}B.log("All progressive data sources loaded")}finally{Ha.setPending(!1),this.hideTransitionOverlay()}}else this.hideTransitionOverlay();const ve=_.filter(ae=>ae.type==="websocket");if(ve.length>0){B.log("Subscribing WebSocket data sources:",ve.map(K=>K.id));const{updateTemplateData:ae,getState:ge}=await Promise.resolve().then(()=>Ua),A={...this.currentFetchedData,...e.params,route:{...e.params||{},path:e.path},query:f,_global:{...this.globalState}};B.log("WebSocket binding context keys:",Object.keys(A)),this.currentWebSocketSubscriptions=S.subscribeWebSockets(_,(K,ue)=>{B.log(`WebSocket data received for: ${K}`,ue),this.currentFetchedData[K]=ue;const he=_.find(He=>He.id===K),le=ge();if(le.bindingEngine){const He=[K];he?.initGlobal&&He.push("_global"),he?.initLocal&&He.push("_local"),le.bindingEngine.invalidateCacheByKeys(He)}ae({[K]:ue});const Oe=_.find(He=>He.type==="websocket"&&(He.target_source||He.id)===K)?.onReceive;Array.isArray(Oe)&&Oe.length>0&&window.G7Core?.dispatch&&(async()=>{for(const Pe of Oe)try{const ke=this.getActionDispatcher?.();ke&&await ke.dispatchAction(Pe,{navigate:this.getRouter?.()?(Ot,ut)=>this.getRouter().navigate(Ot,ut):void 0,setState:Ot=>this.setGlobalState(Ot),state:this.globalState,data:{...this.globalState,$args:[ue],$event:ue},_isDispatchFallbackContext:!0})}catch(ke){B.error(`WebSocket onReceive action failed for ${K}:`,ke)}})()},A),B.log("WebSocket subscriptions established:",this.currentWebSocketSubscriptions)}B.log("Layout rendered successfully")}catch(r){B.error("Route change handling failed:",r),this.hideTransitionOverlay(),this.showRouteError(r)}}processInitOptions(e,n,r,i){e.some(u=>u.refetchOnMount===!0&&u.initLocal)&&(r._forceLocalInit=Date.now(),B.log("refetchOnMount detected, forcing local state init")),e.forEach(u=>{const d=n[u.id];if(!d)return;const f=d.data??d;if(u.initLocal){if(typeof u.initLocal=="string"){let g=f;if(u.initLocalDefaults&&typeof u.initLocalDefaults=="object"){const b=this.evaluateDefaults(u.initLocalDefaults,n);g={...b,...f},B.log(`initLocalDefaults applied for ${u.initLocal}:`,Object.keys(b))}const m=this.globalState._local?.[u.initLocal];m!==void 0&&typeof m=="object"&&typeof g=="object"?(r[u.initLocal]=this.deepMerge(m,g),B.log(`initLocal (merged): ${u.id}.data -> _local.${u.initLocal}`)):(r[u.initLocal]=g,B.log(`initLocal: ${u.id}.data -> _local.${u.initLocal}`))}else if(typeof u.initLocal=="object"&&u.initLocal.key){const{key:g,path:m}=u.initLocal;let b=m?this.extractValueByPathOrExpression(f,m,u.id):f;if(u.initLocalDefaults&&typeof u.initLocalDefaults=="object"){const S=this.evaluateDefaults(u.initLocalDefaults,n);b={...S,...b},B.log(`initLocalDefaults applied for ${g}:`,Object.keys(S))}const v=this.globalState._local?.[g];v!==void 0&&typeof v=="object"&&typeof b=="object"?(r[g]=this.deepMerge(v,b),B.log(`initLocal (merged): ${u.id}.data${m?"."+m:""} -> _local.${g}`)):(r[g]=b,B.log(`initLocal: ${u.id}.data${m?"."+m:""} -> _local.${g}`))}else if(typeof u.initLocal=="object"){const g=u.initLocal._merge||"deep",m=this.flattenNestedObjectToMappings(u.initLocal);for(const{targetPath:b,sourcePath:v}of m){const S=this.extractValueByPathOrExpression(f,v,u.id);if(b.includes(".")){const _=b.split(".")[0];r[_]===void 0&&this.globalState._local?.[_]!==void 0&&(r[_]=JSON.parse(JSON.stringify(this.globalState._local[_]))),this.setValueAtPath(r,b,S,g),B.log(`initLocal map (${g}): ${u.id} ${v} -> _local.${b}`)}else{const _=this.globalState._local?.[b];g==="replace"?(r[b]=S,B.log(`initLocal map (replace): ${u.id} ${v} -> _local.${b}`)):g==="shallow"?_!==void 0&&typeof _=="object"&&typeof S=="object"?(r[b]={..._,...S},B.log(`initLocal map (shallow): ${u.id} ${v} -> _local.${b}`)):(r[b]=S,B.log(`initLocal map: ${u.id} ${v} -> _local.${b}`)):_!==void 0&&typeof _=="object"&&typeof S=="object"?(r[b]=this.deepMerge(_,S),B.log(`initLocal map (deep): ${u.id} ${v} -> _local.${b}`)):(r[b]=S,B.log(`initLocal map: ${u.id} ${v} -> _local.${b}`))}}}}if(u.initGlobal)if(typeof u.initGlobal=="object"&&!Array.isArray(u.initGlobal)&&!("key"in u.initGlobal))for(const[m,b]of Object.entries(u.initGlobal)){if(typeof b!="string"){B.warn(`initGlobal map value must be string, got ${typeof b} for key ${m}`);continue}const v=this.extractValueByPathOrExpression(f,b,u.id),S=this.globalState[m];S!==void 0&&typeof S=="object"&&typeof v=="object"?(this.globalState[m]=this.deepMerge(S,v),B.log(`initGlobal map (merged): ${u.id} ${b} -> _global.${m}`)):(this.globalState[m]=v,B.log(`initGlobal map: ${u.id} ${b} -> _global.${m}`))}else{const m=Array.isArray(u.initGlobal)?u.initGlobal:[u.initGlobal];for(const b of m)if(typeof b=="string"){const v=this.globalState[b];v!==void 0&&typeof v=="object"&&typeof f=="object"?(this.globalState[b]=this.deepMerge(v,f),B.log(`initGlobal (merged): ${u.id}.data -> _global.${b}`)):(this.globalState[b]=f,B.log(`initGlobal: ${u.id}.data -> _global.${b}`))}else if(typeof b=="object"&&b.key){const{key:v,path:S}=b,_=S?this.extractValueByPathOrExpression(f,S,u.id):f,x=this.globalState[v];x!==void 0&&typeof x=="object"&&typeof _=="object"?(this.globalState[v]=this.deepMerge(x,_),B.log(`initGlobal (merged): ${u.id}.data${S?"."+S:""} -> _global.${v}`)):(this.globalState[v]=_,B.log(`initGlobal: ${u.id}.data${S?"."+S:""} -> _global.${v}`))}}if(i&&u.initIsolated){if(typeof u.initIsolated=="string"){const g=i[u.initIsolated];g!==void 0&&typeof g=="object"&&typeof f=="object"?(i[u.initIsolated]=this.deepMerge(g,f),B.log(`initIsolated (merged): ${u.id}.data -> _isolated.${u.initIsolated}`)):(i[u.initIsolated]=f,B.log(`initIsolated: ${u.id}.data -> _isolated.${u.initIsolated}`))}else if(typeof u.initIsolated=="object"&&u.initIsolated.key){const{key:g,path:m}=u.initIsolated,b=m?this.extractValueByPathOrExpression(f,m,u.id):f,v=i[g];v!==void 0&&typeof v=="object"&&typeof b=="object"?(i[g]=this.deepMerge(v,b),B.log(`initIsolated (merged): ${u.id}.data${m?"."+m:""} -> _isolated.${g}`)):(i[g]=b,B.log(`initIsolated: ${u.id}.data${m?"."+m:""} -> _isolated.${g}`))}else if(typeof u.initIsolated=="object")for(const[g,m]of Object.entries(u.initIsolated)){if(typeof m!="string"){B.warn(`initIsolated map value must be string, got ${typeof m} for key ${g}`);continue}const b=this.extractValueByPathOrExpression(f,m,u.id),v=i[g];v!==void 0&&typeof v=="object"&&typeof b=="object"?(i[g]=this.deepMerge(v,b),B.log(`initIsolated map (merged): ${u.id} ${m} -> _isolated.${g}`)):(i[g]=b,B.log(`initIsolated map: ${u.id} ${m} -> _isolated.${g}`))}}})}evaluateDefaults(e,n){const r={};for(const[i,l]of Object.entries(e))if(typeof l=="string"&&l.startsWith("{{")&&l.endsWith("}}")){const u=l.slice(2,-2).trim();r[i]=this.evaluateExpression(u,n)}else r[i]=l;return r}evaluateExpression(e,n){try{const r=e.split("??").map(i=>i.trim());for(const i of r){if(/^['"].*['"]$/.test(i))return i.slice(1,-1);if(i==="true")return!0;if(i==="false")return!1;if(/^-?\d+(\.\d+)?$/.test(i))return Number(i);const l=this.getNestedValue(n,i);if(l!=null)return l}return}catch(r){B.warn(`Expression evaluation failed: ${e}`,r);return}}getNestedValue(e,n){const r=n.replace(/\?\./g,".");let i=e;const l=r.split(/\.(?![^\[]*\])/).flatMap(u=>{const d=u.match(/^([^\[]*)((?:\[\d+\])*)$/);if(d){const[,f,g]=d,m=[];f&&m.push(f);const b=g.match(/\[\d+\]/g);return b&&m.push(...b),m}return[u]}).filter(u=>u!=="");for(const u of l){if(i==null)return;if(u.startsWith("[")&&u.endsWith("]")){const d=parseInt(u.slice(1,-1),10);i=i[d]}else i=i[u]}return i}extractValueByPathOrExpression(e,n,r){const i=n.match(/^\{\{(.+)\}\}$/);if(i){const l=i[1].trim(),u=new Rn,d={data:e,_global:this.globalState,_local:this.globalState._local||{}};try{const f=u.evaluateExpression(l,d);return B.log(`initLocal/initGlobal expression evaluated: ${n} -> `,f),f}catch(f){B.warn(`initLocal/initGlobal expression evaluation failed for ${r}:`,n,f);return}}return this.getNestedValue(e,n)}async loadLayoutScripts(e,n){const r=[];for(const i of e){if((i.if!==void 0||i.conditions!==void 0)&&!Qi({if:i.if,conditions:i.conditions},n,this.bindingEngine,`script:${i.id}`)){B.log(`Script skipped (condition not met): ${i.id}`);continue}if(document.getElementById(i.id)){B.log(`Script already loaded: ${i.id}`);continue}const u=new Promise((d,f)=>{const g=document.createElement("script");g.src=i.src,g.id=i.id,g.async=i.async??!0,g.onload=()=>{B.log(`Script loaded successfully: ${i.id}`),d()},g.onerror=()=>{B.warn(`Failed to load script: ${i.id} (${i.src})`),d()},document.head.appendChild(g)});r.push(u)}r.length>0&&(await Promise.all(r),B.log(`All scripts loaded: ${e.filter(i=>!document.getElementById(i.id)||r.length>0).map(i=>i.id).join(", ")}`))}evaluateScriptCondition(e,n){try{if(e.startsWith("{{")&&e.endsWith("}}")){const r=e.slice(2,-2).trim();return new Function("ctx",` with(ctx) { try { return Boolean(${r}); @@ -232,7 +232,7 @@ Error generating stack: `+c.message+` return false; } } - `)(a)}return!!e}catch(r){return B.warn(`Failed to evaluate script condition: ${e}`,r),!1}}showInitError(e){if(td()){B.warn("Init failed while document is unloading — skipping error screen",e);return}const a=ry(e);cf.renderFromError("app",a,"초기화 실패",this.config.debug,{templateId:this.config.templateId,locale:this.config.locale},void 0,e)}showTransitionOverlay(e,a){const r=typeof e=="boolean"?{enabled:e,style:"opaque",target:void 0,skeleton:void 0,spinner:void 0}:{enabled:e.enabled,style:e.style||"opaque",target:e.target,skeleton:e.skeleton,spinner:e.spinner,fallback_target:e.fallback_target};if(!r.enabled)return;if(this.hideTransitionOverlay(),r.style==="skeleton"&&r.skeleton?.component&&r.target&&a){this.renderSkeletonOverlay(r.target,r.skeleton,a,r.fallback_target);return}if(r.style==="spinner"&&r.target){this.renderSpinnerOverlay(r.target,r.spinner,r.fallback_target);return}const i=document.documentElement.classList.contains("dark");let l,u="";switch(r.style){case"blur":l=i?"rgba(17,24,39,0.3)":"rgba(255,255,255,0.3)",u="backdrop-filter:blur(4px);-webkit-backdrop-filter:blur(4px);";break;case"fade":l=i?"rgba(17,24,39,0.8)":"rgba(255,255,255,0.8)";break;case"skeleton":l=i?"rgb(17,24,39)":"rgb(249,250,251)";break;default:l=i?"rgb(17,24,39)":"rgb(249,250,251)";break}if(r.target){const d=`#${CSS.escape(r.target)}`,f=document.createElement("style");f.id="g7-transition-overlay",f.textContent=`${d}{position:relative;z-index:0;}${d}::after{content:'';position:absolute;inset:0;background:${l};${u}z-index:2147483647;pointer-events:none;}`,document.head.appendChild(f),this.transitionOverlayEl=f}else{const d=document.createElement("div");d.id="g7-transition-overlay",d.setAttribute("aria-hidden","true"),d.style.position="fixed",d.style.inset="0",d.style.zIndex="9999",d.style.pointerEvents="none",d.style.background=l;for(const f of u.split(";")){const g=f.indexOf(":");g!==-1&&d.style.setProperty(f.slice(0,g).trim(),f.slice(g+1).trim())}document.body.appendChild(d),this.transitionOverlayEl=d}}hideTransitionOverlay(){this.transitionOverlayEl&&(this.transitionOverlayEl.remove(),this.transitionOverlayEl=null),this.hideSkeletonOverlay()}renderSkeletonOverlay(e,a,r,i){const u=da.getInstance().getComponent(a.component);if(!u){B.log(`Skeleton component "${a.component}" not found in registry, falling back to opaque overlay`),this.showTransitionOverlay({enabled:!0,style:"opaque",target:e});return}let d=document.getElementById(e),f="target";if(!d&&i&&(d=document.getElementById(i),f="fallback"),d||(d=document.getElementById("app"),f="fullpage"),!d){B.log(`Skeleton overlay: no target found (target="#${e}", fallback="${i||"none"}"), falling back to opaque overlay`),this.showTransitionOverlay({enabled:!0,style:"opaque",target:e});return}this.hideSkeletonOverlay();const m=document.documentElement.classList.contains("dark")?"rgb(17,24,39)":"rgb(249,250,251)",b=f==="fullpage"?"app":f==="fallback"?i:e,v=`#${CSS.escape(b)}`,S=document.createElement("style");S.id="g7-skeleton-overlay-style",S.textContent=`${v}{position:relative;z-index:0;}${v}::after{content:'';position:absolute;inset:0;background:${m};z-index:2147483646;pointer-events:none;}`,document.head.appendChild(S),this.transitionOverlayEl=S;const E=document.createElement("div");if(E.id="g7-skeleton-overlay",E.setAttribute("role","status"),E.setAttribute("aria-busy","true"),E.setAttribute("aria-label","Loading..."),f==="fullpage")E.style.cssText=["position:fixed","inset:0","z-index:20","overflow:hidden","pointer-events:none",`background:${m}`].join(";")+";";else{const R=d.getBoundingClientRect(),D=window.scrollX||document.documentElement.scrollLeft,U=window.scrollY||document.documentElement.scrollTop;E.style.cssText=["position:absolute",`top:${R.top+U}px`,`left:${R.left+D}px`,`width:${R.width}px`,`height:${R.height}px`,"z-index:20","overflow:hidden","pointer-events:none",`background:${m}`].join(";")+";"}document.body.appendChild(E),this.skeletonOverlayContainer=E;const A=r.components||[];let T;if(f==="fullpage")T=A;else{const R=f==="fallback"?i:e;T=this.findComponentChildrenById(A,R)}const L=Ju.createRoot(E);this.skeletonOverlayRoot=L,Ar.flushSync(()=>{L.render(Ye.createElement(u,{components:T,options:{animation:a.animation||"pulse",iteration_count:a.iteration_count||5}}))});const M=f==="fullpage"?"fullpage (#app)":f==="fallback"?`fallback (#${i})`:`target (#${e})`;B.log(`Skeleton overlay rendered [${M}] with "${a.component}" (${T.length} components)`)}findComponentChildrenById(e,a){const r=i=>{for(const l of i){if(l.id===a)return l.children||[];if(l.children&&Array.isArray(l.children)){const u=r(l.children);if(u!==null)return u}}return null};return r(e)||e}renderSpinnerOverlay(e,a,r){let i=document.getElementById(e),l="target";if(!i&&r&&(i=document.getElementById(r),l="fallback"),i||(i=document.getElementById("app"),l="fullpage"),!i){B.log(`Spinner overlay: no target found (target="#${e}", fallback="${r||"none"}"), falling back to opaque overlay`),this.showTransitionOverlay({enabled:!0,style:"opaque",target:e});return}this.hideSkeletonOverlay();const u=l==="fullpage"?"app":l==="fallback"?r:e,d=`#${CSS.escape(u)}`,f=document.createElement("style");f.id="g7-skeleton-overlay-style",f.textContent=[`${d}{position:relative;}`,"@keyframes g7-spin{to{transform:rotate(360deg)}}"].join(""),document.head.appendChild(f),this.transitionOverlayEl=f;const g=a?.text||window.G7Core?.t?.("nav.loading")||"";this._spinnerState={target:e,fallbackTarget:r,spinnerConfig:a,resolvedText:g},this._mountSpinnerInTarget(i);const m=l==="fullpage"?"fullpage (#app)":l==="fallback"?`fallback (#${r})`:`target (#${e})`,b=a?.component||"default spinner";B.log(`Spinner overlay rendered [${m}] with "${b}"`)}_mountSpinnerInTarget(e){if(!this._spinnerState)return;const{spinnerConfig:a,resolvedText:r}=this._spinnerState;if(this.skeletonOverlayRoot){try{this.skeletonOverlayRoot.unmount()}catch{}this.skeletonOverlayRoot=null}if(this.skeletonOverlayContainer){try{this.skeletonOverlayContainer.remove()}catch{}this.skeletonOverlayContainer=null}const i=document.createElement("div");if(i.id="g7-skeleton-overlay",i.setAttribute("role","status"),i.setAttribute("aria-busy","true"),e.appendChild(i),this.skeletonOverlayContainer=i,a?.component){const u=da.getInstance().getComponent(a.component);if(u){const d=Ju.createRoot(i);this.skeletonOverlayRoot=d,Ar.flushSync(()=>{d.render(Ye.createElement(u,{options:{text:r}}))});return}B.log(`Spinner component "${a.component}" not found in registry, using default spinner`)}i.innerHTML='
'}reattachSpinnerOverlay(){if(!this._spinnerState)return;const{target:e,fallbackTarget:a}=this._spinnerState;let r=document.getElementById(e);!r&&a&&(r=document.getElementById(a)),r||(r=document.getElementById("app")),r&&(this._mountSpinnerInTarget(r),B.log("Spinner overlay reattached to new DOM target"))}hideSkeletonOverlay(){if(this.skeletonOverlayRoot){try{this.skeletonOverlayRoot.unmount()}catch{}this.skeletonOverlayRoot=null}if(this.skeletonOverlayContainer){try{this.skeletonOverlayContainer.parentNode&&this.skeletonOverlayContainer.remove()}catch{}this.skeletonOverlayContainer=null}const e=document.getElementById("g7-skeleton-overlay-style");e&&e.remove(),this._spinnerState=null}showRouteError(e){if(e instanceof ba&&e.details?.status===401){const r=this.config.templateId||"",i=window.location.pathname,l=r.includes("admin")||i.startsWith("/admin")?"admin":"user",u=i+window.location.search,d=!!$a().getToken()||e.details?.hadToken===!0,f=ha.getInstance().getLoginRedirectUrl(l,u,d?"session_expired":void 0);window.location.href=f;return}const a=ry(e);cf.renderFromError("app",a,"페이지 로딩 실패",this.config.debug,{templateId:this.config.templateId,locale:this.config.locale},void 0,e)}async handleServerError(){const e=window.G7Error;if(!e)return!1;B.warn("Server error detected:",e);try{return this.errorPageHandler&&(e.data&&(this.globalState.errorData=e.data),this.errorPageHandler.updateGlobalState(this.globalState),this.errorPageHandler.updateLocale(this.config.locale),await this.errorPageHandler.renderError(e.code,"app"))?(B.log(`${e.code} error page rendered successfully`),!0):(B.log(`Falling back to ErrorDisplay for ${e.code}`),this.showInitError(new Error(`Service unavailable (${e.code})`)),!0)}catch(a){return B.error(`Failed to render ${e.code} page:`,a),this.showInitError(new Error(`Service unavailable (${e.code})`)),!0}}async handleRouteNotFound(e){B.warn("Route not found:",e);try{if(this.errorPageHandler&&(this.errorPageHandler.updateGlobalState(this.globalState),this.errorPageHandler.updateLocale(this.config.locale),await this.errorPageHandler.renderError(404,"app"))){B.log("404 error page rendered successfully");return}B.log("Falling back to ErrorDisplay for 404"),this.showRouteError(new Error(`Page not found: ${e}`))}catch(a){B.error("Failed to render 404 page:",a),this.showRouteError(new Error(`Page not found: ${e}`))}}getRouter(){return this.router}getConfig(){return this.config}getLayoutLoader(){return this.layoutLoader}async reloadExtensionState(){B.log("reloadExtensionState: start");let e;try{const a=await fetch(La(`/api/templates/${this.config.templateId}/config`,"json",null,`_=${Date.now()}`));if(a.ok){const r=await a.json();r?.success&&r?.data?.cache_version!==void 0&&(e=r.data.cache_version)}}catch(a){B.warn("reloadExtensionState: failed to fetch config.json",a)}e!==void 0&&e!==this.extensionCacheVersion&&(B.log(`reloadExtensionState: cache version ${this.extensionCacheVersion} -> ${e}`),this.extensionCacheVersion=e,this.saveCacheVersionToStorage(e));try{this.router&&(await this.router.loadRoutes(this.extensionCacheVersion),B.log("reloadExtensionState: routes reloaded"))}catch(a){B.error("reloadExtensionState: routes reload failed",a)}try{this.layoutLoader&&(this.extensionCacheVersion>0&&this.layoutLoader.setCacheVersion(this.extensionCacheVersion),this.layoutLoader.clear(),B.log("reloadExtensionState: layout cache cleared"))}catch(a){B.error("reloadExtensionState: layout cache clear failed",a)}try{const{TranslationEngine:a}=await Promise.resolve().then(()=>tp),r=a.getInstance();this.extensionCacheVersion>0&&r.setCacheVersion(this.extensionCacheVersion);const i=this.config.locale||"ko",l="en";await r.loadTranslations(this.config.templateId,i,"/api",!0),i!==l&&await r.loadTranslations(this.config.templateId,l,"/api",!0),B.log("reloadExtensionState: translations reloaded")}catch(a){B.error("reloadExtensionState: translations reload failed",a)}try{const a=await fetch(`/api/locales/active?_=${Date.now()}`);if(a.ok){const i=(await a.json())?.data?.locales;if(Array.isArray(i)&&i.length>0){const l=this.globalState.appConfig??{};this.setGlobalState({appConfig:{...l,supportedLocales:i}}),B.log("reloadExtensionState: supportedLocales refreshed",i)}}}catch(a){B.warn("reloadExtensionState: supportedLocales refresh failed",a)}B.log("reloadExtensionState: done")}getActionDispatcher(){return Za().actionDispatcher}async changeLocale(e){try{if(B.log("Changing locale to:",e),this.config.locale===e){B.log("Locale is already",e);return}this.config.locale=e,this.saveLocaleToStorage(e),await this.saveLocaleToDatabase(e),this.layoutLoader&&(this.layoutLoader.clear(),B.log("Layout cache cleared")),this.errorPageHandler&&(this.errorPageHandler.updateLocale(e),B.log("ErrorPageHandler locale updated")),yc(),await Ao({templateId:this.config.templateId,templateType:this.config.templateType,locale:e,debug:this.config.debug,cacheVersion:this.extensionCacheVersion}),B.log("Template Engine re-initialized with new locale");const{getActionDispatcher:a}=await Promise.resolve().then(()=>za),r=a();r&&(r.setDefaultContext({navigate:i=>this.router?.navigate(i)}),r.setGlobalStateUpdater((i,l)=>this.setGlobalState(i,l)),B.log("Navigate function and setGlobalState re-injected to ActionDispatcher")),this.reinitializeModuleHandlers(),B.log("Module handlers re-initialized"),this.reinitializeTemplateHandlers(),B.log("Template handlers re-initialized"),this.reinitializePluginHandlers(),B.log("Plugin handlers re-initialized"),this.router&&this.router.navigateToCurrentPath(),B.log("Locale changed successfully to",e)}catch(a){throw B.error("Failed to change locale:",a),a}}loadLocaleFromStorage(){try{return localStorage.getItem(Ca.LOCALE_STORAGE_KEY)}catch(e){return B.warn("Failed to load locale from storage:",e),null}}saveLocaleToStorage(e){try{localStorage.setItem(Ca.LOCALE_STORAGE_KEY,e)}catch(a){B.warn("Failed to save locale to storage:",a)}}async saveLocaleToDatabase(e){const a=localStorage.getItem("auth_token");if(!a){B.log("No auth token, skipping DB locale save");return}let r,i;if(this.config.localeApi)r=this.config.localeApi.endpoint,i=this.config.localeApi.method;else{const l=this.config.templateType==="admin";r=l?"/api/admin/users/me/language":"/api/user/profile/update-language",i=l?"PATCH":"POST"}try{const l=this.getXsrfToken(),u=await fetch(r,{method:i,headers:{"Content-Type":"application/json",Accept:"application/json",...l&&{"X-XSRF-TOKEN":l},Authorization:`Bearer ${a}`},credentials:"include",body:JSON.stringify({language:e})});u.ok?B.log("Locale saved to DB:",e):B.warn("Failed to save locale to DB (UI will still change):",u.statusText)}catch(l){B.warn("Failed to call locale API (UI will still change):",l)}}getXsrfToken(){if(typeof document>"u")return null;const a=`; ${document.cookie}`.split("; XSRF-TOKEN=");return a.length===2?decodeURIComponent(a.pop()?.split(";").shift()||""):null}loadCacheVersionFromStorage(){try{const e=localStorage.getItem(Ca.CACHE_VERSION_STORAGE_KEY);return e?parseInt(e,10):null}catch(e){return B.warn("Failed to load cache version from storage:",e),null}}saveCacheVersionToStorage(e){try{localStorage.setItem(Ca.CACHE_VERSION_STORAGE_KEY,String(e))}catch(a){B.warn("Failed to save cache version to storage:",a)}}reinitializeModuleHandlers(){if(typeof window>"u")return;const e="__",a=window;Object.keys(a).forEach(r=>{if(r.startsWith(e)&&typeof a[r]?.initModule=="function")try{a[r].initModule(),B.log(`Module handler re-initialized: ${r}`)}catch(i){B.warn(`Failed to re-initialize module handlers for ${r}:`,i)}})}reinitializeTemplateHandlers(){if(typeof window>"u")return;const e=window.G7TemplateHandlers;if(!e){B.warn("Template handlers not found on window.G7TemplateHandlers");return}const a=this.getActionDispatcher();if(!a){B.warn("ActionDispatcher not available for template handler registration");return}Object.entries(e).forEach(([r,i])=>{a.registerHandler(r,i)}),B.log(`${Object.keys(e).length} template handler(s) re-registered:`,Object.keys(e))}reinitializePluginHandlers(){if(typeof window>"u")return;const e="__",a=window;Object.keys(a).forEach(r=>{if(r.startsWith(e)&&typeof a[r]?.initPlugin=="function")try{a[r].initPlugin(),B.log(`Plugin handler re-initialized: ${r}`)}catch(i){B.warn(`Failed to re-initialize plugin handlers for ${r}:`,i)}})}getLocale(){return this.config.locale}getErrorPageHandler(){return this.errorPageHandler}getGlobalState(){return{...this.globalState}}setGlobalState(e,a){const r={...this.globalState};typeof e=="function"?this.globalState=e(this.globalState):this.globalState={...this.globalState,...e},B.log("Global state updated:",this.globalState),window.G7Core?.devTools?.captureStateSnapshot?.({source:"setGlobalState",prev:r,next:this.globalState}),this.globalStateListeners.forEach(l=>{l(this.globalState)}),a?.render!==!1&&Promise.resolve().then(()=>za).then(({updateTemplateData:l,getState:u})=>{const d=u();d.reactRoot&&d.currentLayoutJson&&l({_global:{...this.globalState},_local:this.globalState._local||{}})})}onGlobalStateChange(e){this.globalStateListeners.add(e)}offGlobalStateChange(e){this.globalStateListeners.delete(e)}async refetchDataSource(e,a){let r=this.currentDataSources.find(i=>i.id===e);if(!r)for(const[,i]of this.modalDataSources){const l=i.find(u=>u.id===e);if(l){r=l;break}}if(!r){B.warn(`Data source not found: ${e}`);return}B.log(`Refetching data source: ${e}`,a?.sync?"(sync mode)":"",a?.globalStateOverride?"(with global override)":"",a?.localStateOverride?"(with local override)":""),Na.setPending(!0);try{const i=new va;this.currentGlobalHeaders.length>0&&i.setGlobalHeaders(this.currentGlobalHeaders);const l=Za(),u=l.currentDataContext?._global||{},d=a?.globalStateOverride?{...u,...a.globalStateOverride}:u,f=l.currentDataContext?._local||{},g=a?.localStateOverride?{...f,...a.localStateOverride}:f,b=(await i.fetchDataSourcesWithResults([r],this.currentRouteParams,this.currentQueryParams,d,g,{ignoreAutoFetch:!0}))[0];if(b.state==="success"&&b.data!==void 0){this.currentFetchedData[e]=b.data;const v={};this.processInitOptions([r],{[e]:b.data},v);const S=Za();if(S.bindingEngine){const A=[e];r.initGlobal&&A.push("_global"),r.initLocal&&A.push("_local"),S.bindingEngine.invalidateCacheByKeys(A)}const E={[e]:b.data};return Object.keys(v).length>0&&(E._localInit=v),r.initGlobal&&(E._global={...this.globalState}),cs(E,a?.sync?{sync:!0}:void 0),B.log(`Data source refetched successfully: ${e}`),b.data}else if(b.state==="error"){B.error(`Failed to refetch data source: ${e}`,b.error);return}}catch(i){B.error(`Error refetching data source: ${e}`,i);return}finally{Na.setPending(!1)}}registerModalDataSources(e,a){this.modalDataSources.set(e,a),B.log(`Modal data sources registered: ${e} (${a.length} sources)`)}unregisterModalDataSources(e){this.modalDataSources.delete(e),B.log(`Modal data sources unregistered: ${e}`)}getDataSource(e){return this.currentFetchedData[e]}setDataSource(e,a,r){if(!e){B.warn("setDataSource: dataSourceId is required");return}const{merge:i=!1,sync:l=!1}=r||{};i&&this.currentFetchedData[e]?this.currentFetchedData[e]={...this.currentFetchedData[e],...a}:this.currentFetchedData[e]=a,Promise.resolve().then(()=>za).then(({updateTemplateData:u})=>{u({[e]:this.currentFetchedData[e]},l?{sync:!0}:void 0)}),B.log(`setDataSource: Updated ${e}`,i?"(merged)":"(replaced)")}updateDataSourceItem(e,a,r,i,l){const{idField:u="id",merge:d=!0,skipRender:f=!1}=l||{},g=this.currentFetchedData[e];if(!g)return B.warn(`updateDataSourceItem: DataSource '${e}' not found`),!1;const m=this.parseItemPath(a);let b=g;for(const E of m)if(b=b?.[E],b===void 0)return B.warn(`updateDataSourceItem: Path '${a}' not found in dataSource`),!1;if(!Array.isArray(b))return B.warn(`updateDataSourceItem: Target at '${a}' is not an array`),!1;const v=b.findIndex(E=>String(E[u])===String(r));if(v===-1)return B.warn(`updateDataSourceItem: Item with ${u}='${r}' not found`),!1;d?b[v]=this.deepMerge(b[v],i):b[v]={...b[v],...i};const S=window.G7Core?.devTools;return S?.isEnabled?.()&&S.trackDataSourceUpdate?.({dataSourceId:e,updateType:"partial",itemPath:a,itemId:r,updates:i,timestamp:Date.now()}),f||Promise.resolve().then(()=>za).then(({updateTemplateData:E})=>{E({[e]:this.currentFetchedData[e]},{sync:!1})}),B.log(`updateDataSourceItem: Updated ${e}.${a}[${u}=${r}]`),!0}parseItemPath(e){const a=[],r=/([^\.\[\]]+)|\[(\d+)\]/g;let i;for(;(i=r.exec(e))!==null;)i[1]!==void 0?a.push(i[1]):i[2]!==void 0&&a.push(parseInt(i[2],10));return a}deepMerge(e,a){if(a==null)return e;if(typeof a!="object"||Array.isArray(a))return a;const r={...e};for(const i of Object.keys(a))typeof a[i]=="object"&&a[i]!==null&&!Array.isArray(a[i])?r[i]=this.deepMerge(r[i]||{},a[i]):r[i]=a[i];return r}setValueAtPath(e,a,r,i="deep"){const l=a.split(".");let u=e;for(let g=0;g0?l.filterByCondition(this.currentRawDataSources,d):this.currentDataSources;this.currentDataSources=f;const g=f.filter(A=>A.auto_fetch!==!1&&A.type!=="websocket");if(g.length===0){B.log("No auto_fetch data sources to refetch");return}B.log(`Refetching ${g.length} auto_fetch data sources`),Na.setPending(!0);const m=Za().currentLayoutJson,b=m?.transition_overlay,v=Array.isArray(b?.wait_for)?b.wait_for:[],S=g.some(A=>(A.loading_strategy||"progressive")==="blocking"),E=v.length>0&&g.some(A=>v.includes(A.id)&&A.type!=="websocket"&&(A.loading_strategy||"progressive")!=="background");if((S||E)&&b&&typeof b=="object"){const A=a?.transitionOverlayTarget||b.target;b.enabled&&b.style==="skeleton"&&b.skeleton?.component&&A?this.renderSkeletonOverlay(A,b.skeleton,m,b.fallback_target):b.enabled&&b.style==="spinner"&&A&&this.renderSpinnerOverlay(A,b.spinner,b.fallback_target)}try{const A=new va;this.currentGlobalHeaders.length>0&&A.setGlobalHeaders(this.currentGlobalHeaders);const T=Za(),L=T.currentDataContext?._global||{},M=await A.fetchDataSourcesWithResults(g,this.currentRouteParams,this.currentQueryParams,L,void 0,{ignoreAutoFetch:!1}),R={},D={},U=new Map(g.map(j=>[j.id,j]));for(const j of M){const P=U.get(j.id);if(!P){B.warn(`Refetch result id not found in autoFetchDataSources: ${j.id}`);continue}const X=j.id;j.state==="success"&&j.data!==void 0?(this.currentFetchedData[X]=j.data,R[X]=j.data,this.processInitOptions([P],{[X]:j.data},D),B.log(`Data source refetched: ${X}`)):j.state==="error"&&B.error(`Failed to refetch data source: ${X}`,j.error)}if(T.bindingEngine){const j=Object.keys(R);j.push("query"),T.bindingEngine.invalidateCacheByKeys(j)}if(Object.keys(D).length>0&&(R._localInit=D),Object.keys(R).length>0){if(R.query=sy(this.currentQueryParams),T.currentLayoutJson?.computed&&Object.keys(T.currentLayoutJson.computed).length>0){const j={...T.currentDataContext,...R,query:R.query},P=this.calculateComputed(T.currentLayoutJson.computed,j);Object.keys(P).length>0&&(R._computed=P,this.globalState._computed=P,B.log("Computed values recalculated in updateQueryParams:",Object.keys(P)))}cs(R,{sync:!0}),B.log("Template data updated with new query params")}}catch(A){B.error("Error in updateQueryParams:",A)}finally{Na.setPending(!1),this.hideTransitionOverlay()}}calculateComputed(e,a){const r={},i=new wn;for(const[l,u]of Object.entries(e))try{let d;if(this.isComputedSwitchDefinition(u))d=i.resolveSwitch(u,a,{skipCache:!0});else if(typeof u=="string")if(u.startsWith("{{")&&u.endsWith("}}")){const f=u.slice(2,-2).trim();d=this.evaluateComputedExpression(f,a)}else d=u;r[l]=d,B.log(`Computed ${l}:`,d)}catch(d){B.warn(`Failed to calculate computed value: ${l}`,d),r[l]=void 0}return r}isComputedSwitchDefinition(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&"$switch"in e&&"$cases"in e}evaluateComputedExpression(e,a){try{return new Function("ctx",` + `)(n)}return!!e}catch(r){return B.warn(`Failed to evaluate script condition: ${e}`,r),!1}}showInitError(e){if(id()){B.warn("Init failed while document is unloading — skipping error screen",e);return}const n=fy(e);ff.renderFromError("app",n,"초기화 실패",this.config.debug,{templateId:this.config.templateId,locale:this.config.locale},void 0,e)}showTransitionOverlay(e,n){const r=typeof e=="boolean"?{enabled:e,style:"opaque",target:void 0,skeleton:void 0,spinner:void 0}:{enabled:e.enabled,style:e.style||"opaque",target:e.target,skeleton:e.skeleton,spinner:e.spinner,fallback_target:e.fallback_target};if(!r.enabled)return;if(this.hideTransitionOverlay(),r.style==="skeleton"&&r.skeleton?.component&&r.target&&n){this.renderSkeletonOverlay(r.target,r.skeleton,n,r.fallback_target);return}if(r.style==="spinner"&&r.target){this.renderSpinnerOverlay(r.target,r.spinner,r.fallback_target);return}const i=document.documentElement.classList.contains("dark");let l,u="";switch(r.style){case"blur":l=i?"rgba(17,24,39,0.3)":"rgba(255,255,255,0.3)",u="backdrop-filter:blur(4px);-webkit-backdrop-filter:blur(4px);";break;case"fade":l=i?"rgba(17,24,39,0.8)":"rgba(255,255,255,0.8)";break;case"skeleton":l=i?"rgb(17,24,39)":"rgb(249,250,251)";break;default:l=i?"rgb(17,24,39)":"rgb(249,250,251)";break}if(r.target){const d=`#${CSS.escape(r.target)}`,f=document.createElement("style");f.id="g7-transition-overlay",f.textContent=`${d}{position:relative;z-index:0;}${d}::after{content:'';position:absolute;inset:0;background:${l};${u}z-index:2147483647;pointer-events:none;}`,document.head.appendChild(f),this.transitionOverlayEl=f}else{const d=document.createElement("div");d.id="g7-transition-overlay",d.setAttribute("aria-hidden","true"),d.style.position="fixed",d.style.inset="0",d.style.zIndex="9999",d.style.pointerEvents="none",d.style.background=l;for(const f of u.split(";")){const g=f.indexOf(":");g!==-1&&d.style.setProperty(f.slice(0,g).trim(),f.slice(g+1).trim())}document.body.appendChild(d),this.transitionOverlayEl=d}}hideTransitionOverlay(){this.transitionOverlayEl&&(this.transitionOverlayEl.remove(),this.transitionOverlayEl=null),this.hideSkeletonOverlay()}renderSkeletonOverlay(e,n,r,i){const u=fa.getInstance().getComponent(n.component);if(!u){B.log(`Skeleton component "${n.component}" not found in registry, falling back to opaque overlay`),this.showTransitionOverlay({enabled:!0,style:"opaque",target:e});return}let d=document.getElementById(e),f="target";if(!d&&i&&(d=document.getElementById(i),f="fallback"),d||(d=document.getElementById("app"),f="fullpage"),!d){B.log(`Skeleton overlay: no target found (target="#${e}", fallback="${i||"none"}"), falling back to opaque overlay`),this.showTransitionOverlay({enabled:!0,style:"opaque",target:e});return}this.hideSkeletonOverlay();const m=document.documentElement.classList.contains("dark")?"rgb(17,24,39)":"rgb(249,250,251)",b=f==="fullpage"?"app":f==="fallback"?i:e,v=`#${CSS.escape(b)}`,S=document.createElement("style");S.id="g7-skeleton-overlay-style",S.textContent=`${v}{position:relative;z-index:0;}${v}::after{content:'';position:absolute;inset:0;background:${m};z-index:2147483646;pointer-events:none;}`,document.head.appendChild(S),this.transitionOverlayEl=S;const _=document.createElement("div");if(_.id="g7-skeleton-overlay",_.setAttribute("role","status"),_.setAttribute("aria-busy","true"),_.setAttribute("aria-label","Loading..."),f==="fullpage")_.style.cssText=["position:fixed","inset:0","z-index:20","overflow:hidden","pointer-events:none",`background:${m}`].join(";")+";";else{const T=d.getBoundingClientRect(),D=window.scrollX||document.documentElement.scrollLeft,j=window.scrollY||document.documentElement.scrollTop;_.style.cssText=["position:absolute",`top:${T.top+j}px`,`left:${T.left+D}px`,`width:${T.width}px`,`height:${T.height}px`,"z-index:20","overflow:hidden","pointer-events:none",`background:${m}`].join(";")+";"}document.body.appendChild(_),this.skeletonOverlayContainer=_;const x=r.components||[];let k;if(f==="fullpage")k=x;else{const T=f==="fallback"?i:e;k=this.findComponentChildrenById(x,T)}const O=td.createRoot(_);this.skeletonOverlayRoot=O,Ar.flushSync(()=>{O.render(Xe.createElement(u,{components:k,options:{animation:n.animation||"pulse",iteration_count:n.iteration_count||5}}))});const M=f==="fullpage"?"fullpage (#app)":f==="fallback"?`fallback (#${i})`:`target (#${e})`;B.log(`Skeleton overlay rendered [${M}] with "${n.component}" (${k.length} components)`)}findComponentChildrenById(e,n){const r=i=>{for(const l of i){if(l.id===n)return l.children||[];if(l.children&&Array.isArray(l.children)){const u=r(l.children);if(u!==null)return u}}return null};return r(e)||e}renderSpinnerOverlay(e,n,r){let i=document.getElementById(e),l="target";if(!i&&r&&(i=document.getElementById(r),l="fallback"),i||(i=document.getElementById("app"),l="fullpage"),!i){B.log(`Spinner overlay: no target found (target="#${e}", fallback="${r||"none"}"), falling back to opaque overlay`),this.showTransitionOverlay({enabled:!0,style:"opaque",target:e});return}this.hideSkeletonOverlay();const u=l==="fullpage"?"app":l==="fallback"?r:e,d=`#${CSS.escape(u)}`,f=document.createElement("style");f.id="g7-skeleton-overlay-style",f.textContent=[`${d}{position:relative;}`,"@keyframes g7-spin{to{transform:rotate(360deg)}}"].join(""),document.head.appendChild(f),this.transitionOverlayEl=f;const g=n?.text||window.G7Core?.t?.("nav.loading")||"";this._spinnerState={target:e,fallbackTarget:r,spinnerConfig:n,resolvedText:g},this._mountSpinnerInTarget(i);const m=l==="fullpage"?"fullpage (#app)":l==="fallback"?`fallback (#${r})`:`target (#${e})`,b=n?.component||"default spinner";B.log(`Spinner overlay rendered [${m}] with "${b}"`)}_mountSpinnerInTarget(e){if(!this._spinnerState)return;const{spinnerConfig:n,resolvedText:r}=this._spinnerState;if(this.skeletonOverlayRoot){try{this.skeletonOverlayRoot.unmount()}catch{}this.skeletonOverlayRoot=null}if(this.skeletonOverlayContainer){try{this.skeletonOverlayContainer.remove()}catch{}this.skeletonOverlayContainer=null}const i=document.createElement("div");if(i.id="g7-skeleton-overlay",i.setAttribute("role","status"),i.setAttribute("aria-busy","true"),e.appendChild(i),this.skeletonOverlayContainer=i,n?.component){const u=fa.getInstance().getComponent(n.component);if(u){const d=td.createRoot(i);this.skeletonOverlayRoot=d,Ar.flushSync(()=>{d.render(Xe.createElement(u,{options:{text:r}}))});return}B.log(`Spinner component "${n.component}" not found in registry, using default spinner`)}i.innerHTML='
'}reattachSpinnerOverlay(){if(!this._spinnerState)return;const{target:e,fallbackTarget:n}=this._spinnerState;let r=document.getElementById(e);!r&&n&&(r=document.getElementById(n)),r||(r=document.getElementById("app")),r&&(this._mountSpinnerInTarget(r),B.log("Spinner overlay reattached to new DOM target"))}hideSkeletonOverlay(){if(this.skeletonOverlayRoot){try{this.skeletonOverlayRoot.unmount()}catch{}this.skeletonOverlayRoot=null}if(this.skeletonOverlayContainer){try{this.skeletonOverlayContainer.parentNode&&this.skeletonOverlayContainer.remove()}catch{}this.skeletonOverlayContainer=null}const e=document.getElementById("g7-skeleton-overlay-style");e&&e.remove(),this._spinnerState=null}showRouteError(e){if(e instanceof va&&e.details?.status===401){const r=this.config.templateId||"",i=window.location.pathname,l=r.includes("admin")||i.startsWith("/admin")?"admin":"user",u=i+window.location.search,d=!!Ia().getToken()||e.details?.hadToken===!0,f=ga.getInstance().getLoginRedirectUrl(l,u,d?"session_expired":void 0);window.location.href=f;return}const n=fy(e);ff.renderFromError("app",n,"페이지 로딩 실패",this.config.debug,{templateId:this.config.templateId,locale:this.config.locale},void 0,e)}async handleServerError(){const e=window.G7Error;if(!e)return!1;B.warn("Server error detected:",e);try{return this.errorPageHandler&&(e.data&&(this.globalState.errorData=e.data),this.errorPageHandler.updateGlobalState(this.globalState),this.errorPageHandler.updateLocale(this.config.locale),await this.errorPageHandler.renderError(e.code,"app"))?(B.log(`${e.code} error page rendered successfully`),!0):(B.log(`Falling back to ErrorDisplay for ${e.code}`),this.showInitError(new Error(`Service unavailable (${e.code})`)),!0)}catch(n){return B.error(`Failed to render ${e.code} page:`,n),this.showInitError(new Error(`Service unavailable (${e.code})`)),!0}}async handleRouteNotFound(e){B.warn("Route not found:",e);try{if(this.errorPageHandler&&(this.errorPageHandler.updateGlobalState(this.globalState),this.errorPageHandler.updateLocale(this.config.locale),await this.errorPageHandler.renderError(404,"app"))){B.log("404 error page rendered successfully");return}B.log("Falling back to ErrorDisplay for 404"),this.showRouteError(new Error(`Page not found: ${e}`))}catch(n){B.error("Failed to render 404 page:",n),this.showRouteError(new Error(`Page not found: ${e}`))}}getRouter(){return this.router}getConfig(){return this.config}getLayoutLoader(){return this.layoutLoader}async reloadExtensionState(){B.log("reloadExtensionState: start");let e;try{const n=await fetch(Ma(`/api/templates/${this.config.templateId}/config`,"json",null,`_=${Date.now()}`));if(n.ok){const r=await n.json();r?.success&&r?.data?.cache_version!==void 0&&(e=r.data.cache_version)}}catch(n){B.warn("reloadExtensionState: failed to fetch config.json",n)}e!==void 0&&e!==this.extensionCacheVersion&&(B.log(`reloadExtensionState: cache version ${this.extensionCacheVersion} -> ${e}`),this.extensionCacheVersion=e,this.saveCacheVersionToStorage(e));try{this.router&&(await this.router.loadRoutes(this.extensionCacheVersion),B.log("reloadExtensionState: routes reloaded"))}catch(n){B.error("reloadExtensionState: routes reload failed",n)}try{this.layoutLoader&&(this.extensionCacheVersion>0&&this.layoutLoader.setCacheVersion(this.extensionCacheVersion),this.layoutLoader.clear(),B.log("reloadExtensionState: layout cache cleared"))}catch(n){B.error("reloadExtensionState: layout cache clear failed",n)}try{const{TranslationEngine:n}=await Promise.resolve().then(()=>rp),r=n.getInstance();this.extensionCacheVersion>0&&r.setCacheVersion(this.extensionCacheVersion);const i=this.config.locale||"ko",l="en";await r.loadTranslations(this.config.templateId,i,"/api",!0),i!==l&&await r.loadTranslations(this.config.templateId,l,"/api",!0),B.log("reloadExtensionState: translations reloaded")}catch(n){B.error("reloadExtensionState: translations reload failed",n)}try{const n=await fetch(`/api/locales/active?_=${Date.now()}`);if(n.ok){const i=(await n.json())?.data?.locales;if(Array.isArray(i)&&i.length>0){const l=this.globalState.appConfig??{};this.setGlobalState({appConfig:{...l,supportedLocales:i}}),B.log("reloadExtensionState: supportedLocales refreshed",i)}}}catch(n){B.warn("reloadExtensionState: supportedLocales refresh failed",n)}B.log("reloadExtensionState: done")}getActionDispatcher(){return er().actionDispatcher}async changeLocale(e){try{if(B.log("Changing locale to:",e),this.config.locale===e){B.log("Locale is already",e);return}this.config.locale=e,this.saveLocaleToStorage(e),await this.saveLocaleToDatabase(e),this.layoutLoader&&(this.layoutLoader.clear(),B.log("Layout cache cleared")),this.errorPageHandler&&(this.errorPageHandler.updateLocale(e),B.log("ErrorPageHandler locale updated")),Sc(),await ko({templateId:this.config.templateId,templateType:this.config.templateType,locale:e,debug:this.config.debug,cacheVersion:this.extensionCacheVersion}),B.log("Template Engine re-initialized with new locale");const{getActionDispatcher:n}=await Promise.resolve().then(()=>Ua),r=n();r&&(r.setDefaultContext({navigate:i=>this.router?.navigate(i)}),r.setGlobalStateUpdater((i,l)=>this.setGlobalState(i,l)),B.log("Navigate function and setGlobalState re-injected to ActionDispatcher")),this.reinitializeModuleHandlers(),B.log("Module handlers re-initialized"),this.reinitializeTemplateHandlers(),B.log("Template handlers re-initialized"),this.reinitializePluginHandlers(),B.log("Plugin handlers re-initialized"),this.router&&this.router.navigateToCurrentPath(),B.log("Locale changed successfully to",e)}catch(n){throw B.error("Failed to change locale:",n),n}}loadLocaleFromStorage(){try{return localStorage.getItem(Ea.LOCALE_STORAGE_KEY)}catch(e){return B.warn("Failed to load locale from storage:",e),null}}saveLocaleToStorage(e){try{localStorage.setItem(Ea.LOCALE_STORAGE_KEY,e)}catch(n){B.warn("Failed to save locale to storage:",n)}}async saveLocaleToDatabase(e){const n=localStorage.getItem("auth_token");if(!n){B.log("No auth token, skipping DB locale save");return}let r,i;if(this.config.localeApi)r=this.config.localeApi.endpoint,i=this.config.localeApi.method;else{const l=this.config.templateType==="admin";r=l?"/api/admin/users/me/language":"/api/user/profile/update-language",i=l?"PATCH":"POST"}try{const l=this.getXsrfToken(),u=await fetch(r,{method:i,headers:{"Content-Type":"application/json",Accept:"application/json",...l&&{"X-XSRF-TOKEN":l},Authorization:`Bearer ${n}`},credentials:"include",body:JSON.stringify({language:e})});u.ok?B.log("Locale saved to DB:",e):B.warn("Failed to save locale to DB (UI will still change):",u.statusText)}catch(l){B.warn("Failed to call locale API (UI will still change):",l)}}getXsrfToken(){if(typeof document>"u")return null;const n=`; ${document.cookie}`.split("; XSRF-TOKEN=");return n.length===2?decodeURIComponent(n.pop()?.split(";").shift()||""):null}loadCacheVersionFromStorage(){try{const e=localStorage.getItem(Ea.CACHE_VERSION_STORAGE_KEY);return e?parseInt(e,10):null}catch(e){return B.warn("Failed to load cache version from storage:",e),null}}saveCacheVersionToStorage(e){try{localStorage.setItem(Ea.CACHE_VERSION_STORAGE_KEY,String(e))}catch(n){B.warn("Failed to save cache version to storage:",n)}}reinitializeModuleHandlers(){if(typeof window>"u")return;const e="__",n=window;Object.keys(n).forEach(r=>{if(r.startsWith(e)&&typeof n[r]?.initModule=="function")try{n[r].initModule(),B.log(`Module handler re-initialized: ${r}`)}catch(i){B.warn(`Failed to re-initialize module handlers for ${r}:`,i)}})}reinitializeTemplateHandlers(){if(typeof window>"u")return;const e=window.G7TemplateHandlers;if(!e){B.warn("Template handlers not found on window.G7TemplateHandlers");return}const n=this.getActionDispatcher();if(!n){B.warn("ActionDispatcher not available for template handler registration");return}Object.entries(e).forEach(([r,i])=>{n.registerHandler(r,i)}),B.log(`${Object.keys(e).length} template handler(s) re-registered:`,Object.keys(e))}reinitializePluginHandlers(){if(typeof window>"u")return;const e="__",n=window;Object.keys(n).forEach(r=>{if(r.startsWith(e)&&typeof n[r]?.initPlugin=="function")try{n[r].initPlugin(),B.log(`Plugin handler re-initialized: ${r}`)}catch(i){B.warn(`Failed to re-initialize plugin handlers for ${r}:`,i)}})}getLocale(){return this.config.locale}getErrorPageHandler(){return this.errorPageHandler}getGlobalState(){return{...this.globalState}}setGlobalState(e,n){const r={...this.globalState};typeof e=="function"?this.globalState=e(this.globalState):this.globalState={...this.globalState,...e},B.log("Global state updated:",this.globalState),window.G7Core?.devTools?.captureStateSnapshot?.({source:"setGlobalState",prev:r,next:this.globalState}),this.globalStateListeners.forEach(l=>{l(this.globalState)}),n?.render!==!1&&Promise.resolve().then(()=>Ua).then(({updateTemplateData:l,getState:u})=>{const d=u();d.reactRoot&&d.currentLayoutJson&&l({_global:{...this.globalState},_local:this.globalState._local||{}})})}onGlobalStateChange(e){this.globalStateListeners.add(e)}offGlobalStateChange(e){this.globalStateListeners.delete(e)}async refetchDataSource(e,n){let r=this.currentDataSources.find(i=>i.id===e);if(!r)for(const[,i]of this.modalDataSources){const l=i.find(u=>u.id===e);if(l){r=l;break}}if(!r){B.warn(`Data source not found: ${e}`);return}B.log(`Refetching data source: ${e}`,n?.sync?"(sync mode)":"",n?.globalStateOverride?"(with global override)":"",n?.localStateOverride?"(with local override)":""),Ha.setPending(!0);try{const i=new Sa;this.currentGlobalHeaders.length>0&&i.setGlobalHeaders(this.currentGlobalHeaders);const l=er(),u=l.currentDataContext?._global||{},d=n?.globalStateOverride?{...u,...n.globalStateOverride}:u,f=l.currentDataContext?._local||{},g=n?.localStateOverride?{...f,...n.localStateOverride}:f,b=(await i.fetchDataSourcesWithResults([r],this.currentRouteParams,this.currentQueryParams,d,g,{ignoreAutoFetch:!0}))[0];if(b.state==="success"&&b.data!==void 0){this.currentFetchedData[e]=b.data;const v={};this.processInitOptions([r],{[e]:b.data},v);const S=er();if(S.bindingEngine){const x=[e];r.initGlobal&&x.push("_global"),r.initLocal&&x.push("_local"),S.bindingEngine.invalidateCacheByKeys(x)}const _={[e]:b.data};return Object.keys(v).length>0&&(_._localInit=v),r.initGlobal&&(_._global={...this.globalState}),hs(_,n?.sync?{sync:!0}:void 0),B.log(`Data source refetched successfully: ${e}`),b.data}else if(b.state==="error"){B.error(`Failed to refetch data source: ${e}`,b.error);return}}catch(i){B.error(`Error refetching data source: ${e}`,i);return}finally{Ha.setPending(!1)}}registerModalDataSources(e,n){this.modalDataSources.set(e,n),B.log(`Modal data sources registered: ${e} (${n.length} sources)`)}unregisterModalDataSources(e){this.modalDataSources.delete(e),B.log(`Modal data sources unregistered: ${e}`)}getDataSource(e){return this.currentFetchedData[e]}setDataSource(e,n,r){if(!e){B.warn("setDataSource: dataSourceId is required");return}const{merge:i=!1,sync:l=!1}=r||{};i&&this.currentFetchedData[e]?this.currentFetchedData[e]={...this.currentFetchedData[e],...n}:this.currentFetchedData[e]=n,Promise.resolve().then(()=>Ua).then(({updateTemplateData:u})=>{u({[e]:this.currentFetchedData[e]},l?{sync:!0}:void 0)}),B.log(`setDataSource: Updated ${e}`,i?"(merged)":"(replaced)")}updateDataSourceItem(e,n,r,i,l){const{idField:u="id",merge:d=!0,skipRender:f=!1}=l||{},g=this.currentFetchedData[e];if(!g)return B.warn(`updateDataSourceItem: DataSource '${e}' not found`),!1;const m=this.parseItemPath(n);let b=g;for(const _ of m)if(b=b?.[_],b===void 0)return B.warn(`updateDataSourceItem: Path '${n}' not found in dataSource`),!1;if(!Array.isArray(b))return B.warn(`updateDataSourceItem: Target at '${n}' is not an array`),!1;const v=b.findIndex(_=>String(_[u])===String(r));if(v===-1)return B.warn(`updateDataSourceItem: Item with ${u}='${r}' not found`),!1;d?b[v]=this.deepMerge(b[v],i):b[v]={...b[v],...i};const S=window.G7Core?.devTools;return S?.isEnabled?.()&&S.trackDataSourceUpdate?.({dataSourceId:e,updateType:"partial",itemPath:n,itemId:r,updates:i,timestamp:Date.now()}),f||Promise.resolve().then(()=>Ua).then(({updateTemplateData:_})=>{_({[e]:this.currentFetchedData[e]},{sync:!1})}),B.log(`updateDataSourceItem: Updated ${e}.${n}[${u}=${r}]`),!0}parseItemPath(e){const n=[],r=/([^\.\[\]]+)|\[(\d+)\]/g;let i;for(;(i=r.exec(e))!==null;)i[1]!==void 0?n.push(i[1]):i[2]!==void 0&&n.push(parseInt(i[2],10));return n}deepMerge(e,n){if(n==null)return e;if(typeof n!="object"||Array.isArray(n))return n;const r={...e};for(const i of Object.keys(n))typeof n[i]=="object"&&n[i]!==null&&!Array.isArray(n[i])?r[i]=this.deepMerge(r[i]||{},n[i]):r[i]=n[i];return r}setValueAtPath(e,n,r,i="deep"){const l=n.split(".");let u=e;for(let g=0;g0?l.filterByCondition(this.currentRawDataSources,d):this.currentDataSources;this.currentDataSources=f;const g=f.filter(x=>x.auto_fetch!==!1&&x.type!=="websocket");if(g.length===0){B.log("No auto_fetch data sources to refetch");return}B.log(`Refetching ${g.length} auto_fetch data sources`),Ha.setPending(!0);const m=er().currentLayoutJson,b=m?.transition_overlay,v=Array.isArray(b?.wait_for)?b.wait_for:[],S=g.some(x=>(x.loading_strategy||"progressive")==="blocking"),_=v.length>0&&g.some(x=>v.includes(x.id)&&x.type!=="websocket"&&(x.loading_strategy||"progressive")!=="background");if((S||_)&&b&&typeof b=="object"){const x=n?.transitionOverlayTarget||b.target;b.enabled&&b.style==="skeleton"&&b.skeleton?.component&&x?this.renderSkeletonOverlay(x,b.skeleton,m,b.fallback_target):b.enabled&&b.style==="spinner"&&x&&this.renderSpinnerOverlay(x,b.spinner,b.fallback_target)}try{const x=new Sa;this.currentGlobalHeaders.length>0&&x.setGlobalHeaders(this.currentGlobalHeaders);const k=er(),O=k.currentDataContext?._global||{},M=await x.fetchDataSourcesWithResults(g,this.currentRouteParams,this.currentQueryParams,O,void 0,{ignoreAutoFetch:!1}),T={},D={},j=new Map(g.map(H=>[H.id,H]));for(const H of M){const P=j.get(H.id);if(!P){B.warn(`Refetch result id not found in autoFetchDataSources: ${H.id}`);continue}const X=H.id;H.state==="success"&&H.data!==void 0?(this.currentFetchedData[X]=H.data,T[X]=H.data,this.processInitOptions([P],{[X]:H.data},D),B.log(`Data source refetched: ${X}`)):H.state==="error"&&B.error(`Failed to refetch data source: ${X}`,H.error)}if(k.bindingEngine){const H=Object.keys(T);H.push("query"),k.bindingEngine.invalidateCacheByKeys(H)}if(Object.keys(D).length>0&&(T._localInit=D),Object.keys(T).length>0){if(T.query=gy(this.currentQueryParams),k.currentLayoutJson?.computed&&Object.keys(k.currentLayoutJson.computed).length>0){const H={...k.currentDataContext,...T,query:T.query},P=this.calculateComputed(k.currentLayoutJson.computed,H);Object.keys(P).length>0&&(T._computed=P,this.globalState._computed=P,B.log("Computed values recalculated in updateQueryParams:",Object.keys(P)))}hs(T,{sync:!0}),B.log("Template data updated with new query params")}}catch(x){B.error("Error in updateQueryParams:",x)}finally{Ha.setPending(!1),this.hideTransitionOverlay()}}calculateComputed(e,n){const r={},i=new Rn;for(const[l,u]of Object.entries(e))try{let d;if(this.isComputedSwitchDefinition(u))d=i.resolveSwitch(u,n,{skipCache:!0});else if(typeof u=="string")if(u.startsWith("{{")&&u.endsWith("}}")){const f=u.slice(2,-2).trim();d=this.evaluateComputedExpression(f,n)}else d=u;r[l]=d,B.log(`Computed ${l}:`,d)}catch(d){B.warn(`Failed to calculate computed value: ${l}`,d),r[l]=void 0}return r}isComputedSwitchDefinition(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&"$switch"in e&&"$cases"in e}evaluateComputedExpression(e,n){try{return new Function("ctx",` with(ctx) { try { return ${e}; @@ -240,4 +240,5 @@ Error generating stack: `+c.message+` return undefined; } } - `)(a)}catch(r){B.warn(`Expression evaluation failed: ${e}`,r);return}}async executeInitActions(e,a={}){const{getActionDispatcher:r}=await Promise.resolve().then(()=>za),i=r();if(!i){B.warn("ActionDispatcher not available for init_actions");return}B.log("Executing init_actions:",e.map(d=>d.handler)),B.log("Init actions dataContext:",a),B.log("Init actions dataContext._global:",a._global);const l=e.map(d=>d.handler).filter(d=>d.includes("."));l.length>0&&await this.waitForHandlers(i,l);let u={...a};for(const d of e)try{const f={type:"click",handler:d.handler,target:d.target,params:d.params,resultTo:d.resultTo,onSuccess:d.onSuccess,onError:d.onError,if:d.if,conditions:d.conditions,auth_mode:d.auth_mode,auth_required:d.auth_required},g=i.createHandler(f,u),m=new Event("init");await g(m),B.log(`Init action executed: ${d.handler}`);const b=this.globalState;u={...u,_global:{...b},_local:b._local||u._local||{}},B.log(`Data context refreshed after ${d.handler}:`,{cartKey:u._global?.cartKey})}catch(f){B.error(`Failed to execute init action: ${d.handler}`,f)}}async waitForHandlers(e,a,r=5e3){const i=Date.now(),l=50,u=()=>a.every(f=>e.customHandlers?.has(f));if(u()){B.log("All module handlers already registered");return}const d=df().getFailedJsAssets();if(d.length>0){const f=d.some(b=>b==="module"||b==="plugin"),g=a.filter(b=>!e.customHandlers?.has(b)),m=g.length>0&&g.every(b=>d.some(v=>b.startsWith(`${v}.`)));if(f||m){B.warn("Extension asset load failed — not waiting for handlers that will never register:",{pending:g,failedAssets:d});return}}return B.log("Waiting for module handlers:",a),new Promise(f=>{const g=()=>{if(u()){B.log("All module handlers now registered"),f();return}if(Date.now()-i>=r){const m=a.filter(b=>!e.customHandlers?.has(b));B.warn("Timeout waiting for handlers:",m),f();return}setTimeout(g,l)};g()})}};$(Ca,"LOCALE_STORAGE_KEY","g7_locale"),$(Ca,"CACHE_VERSION_STORAGE_KEY","g7_cache_version");let So=Ca;function hf(o){const e=new So(o);return o.websocket&&(hc.configure(o.websocket),B.log("WebSocket 설정 완료")),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{e.init(),window.__templateApp=e}):(e.init(),window.__templateApp=e),e}typeof window<"u"&&(window.G7Core=window.G7Core||{},window.G7Core.initTemplateApp=hf,window.G7Core.dataSource={refetch:async(o,e)=>{const a=window.__templateApp;if(!a){B.warn("TemplateApp not initialized (G7Core.dataSource.refetch)");return}return a.refetchDataSource(o,e)},get:o=>{const e=window.__templateApp;if(!e){B.warn("TemplateApp not initialized (G7Core.dataSource.get)");return}return e.getDataSource(o)}});function K_(o={}){const{checked:e,value:a,name:r,type:i="checkbox"}=o,u=a!==void 0?a:i==="checkbox"||i==="radio"?e??!1:String(e??""),d={checked:e??!1,value:u,name:r??"",type:i};return{target:d,currentTarget:d,preventDefault:()=>{},stopPropagation:()=>{},nativeEvent:new Event("change"),bubbles:!0,cancelable:!0,defaultPrevented:!1,eventPhase:Event.AT_TARGET,isTrusted:!1,timeStamp:Date.now(),type:"change",isDefaultPrevented:()=>!1,isPropagationStopped:()=>!1,persist:()=>{}}}function W_(o={}){const{button:e=0,clientX:a=0,clientY:r=0}=o;return{button:e,clientX:a,clientY:r,preventDefault:()=>{},stopPropagation:()=>{},nativeEvent:new MouseEvent("click"),bubbles:!0,cancelable:!0,defaultPrevented:!1,eventPhase:Event.AT_TARGET,isTrusted:!1,timeStamp:Date.now(),type:"click",isDefaultPrevented:()=>!1,isPropagationStopped:()=>!1,persist:()=>{},target:document.createElement("div"),currentTarget:document.createElement("div")}}function Y_(){return{preventDefault:()=>{},stopPropagation:()=>{},nativeEvent:new Event("submit"),bubbles:!0,cancelable:!0,defaultPrevented:!1,eventPhase:Event.AT_TARGET,isTrusted:!1,timeStamp:Date.now(),type:"submit",isDefaultPrevented:()=>!1,isPropagationStopped:()=>!1,persist:()=>{},target:document.createElement("form"),currentTarget:document.createElement("form")}}function X_(o,e="keydown"){return{key:o,code:o.length===1?`Key${o.toUpperCase()}`:o,preventDefault:()=>{},stopPropagation:()=>{},nativeEvent:new KeyboardEvent(e,{key:o}),bubbles:!0,cancelable:!0,defaultPrevented:!1,eventPhase:Event.AT_TARGET,isTrusted:!1,timeStamp:Date.now(),type:e,isDefaultPrevented:()=>!1,isPropagationStopped:()=>!1,persist:()=>{},target:document.createElement("div"),currentTarget:document.createElement("div"),altKey:!1,ctrlKey:!1,metaKey:!1,shiftKey:!1,repeat:!1}}const J_={justify:/^justify-(start|end|center|between|around|evenly)$/,items:/^items-(start|end|center|baseline|stretch)$/,content:/^content-(start|end|center|between|around|evenly|stretch)$/,self:/^self-(auto|start|end|center|stretch|baseline)$/,flex:/^flex-(row|row-reverse|col|col-reverse|wrap|wrap-reverse|nowrap|1|auto|initial|none)$/,grow:/^(grow|grow-0)$/,shrink:/^(shrink|shrink-0)$/,basis:/^basis-/,order:/^(order-|-)order-/,gap:/^gap(-x|-y)?-/,gridCols:/^grid-cols-/,gridRows:/^grid-rows-/,colSpan:/^col-(span-|start-|end-)/,rowSpan:/^row-(span-|start-|end-)/,display:/^(block|inline-block|inline|flex|inline-flex|table|inline-table|table-caption|table-cell|table-column|table-column-group|table-footer-group|table-header-group|table-row-group|table-row|flow-root|grid|inline-grid|contents|list-item|hidden)$/,position:/^(static|fixed|absolute|relative|sticky)$/,inset:/^(inset|top|right|bottom|left)-/,zIndex:/^z-/,width:/^w-/,minWidth:/^min-w-/,maxWidth:/^max-w-/,height:/^h-/,minHeight:/^min-h-/,maxHeight:/^max-h-/,padding:/^p[xytblr]?-/,margin:/^-?m[xytblr]?-/,space:/^space-(x|y)-/,fontSize:/^text-(xs|sm|base|lg|xl|2xl|3xl|4xl|5xl|6xl|7xl|8xl|9xl)$/,fontWeight:/^font-(thin|extralight|light|normal|medium|semibold|bold|extrabold|black)$/,fontStyle:/^(italic|not-italic)$/,fontFamily:/^font-(sans|serif|mono)/,textAlign:/^text-(left|center|right|justify|start|end)$/,textColor:/^text-(inherit|current|transparent|black|white|slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-/,textDecoration:/^(underline|overline|line-through|no-underline)$/,textTransform:/^(uppercase|lowercase|capitalize|normal-case)$/,lineHeight:/^leading-/,letterSpacing:/^tracking-/,textOverflow:/^(truncate|text-ellipsis|text-clip)$/,whitespace:/^whitespace-/,wordBreak:/^break-/,bgColor:/^bg-(inherit|current|transparent|black|white|slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-/,bgGradient:/^bg-gradient-/,bgSize:/^bg-(auto|cover|contain)$/,bgPosition:/^bg-(bottom|center|left|left-bottom|left-top|right|right-bottom|right-top|top)$/,bgRepeat:/^bg-(repeat|no-repeat|repeat-x|repeat-y|repeat-round|repeat-space)$/,bgAttachment:/^bg-(fixed|local|scroll)$/,bgClip:/^bg-clip-/,bgOrigin:/^bg-origin-/,borderWidth:/^border(-[xytblr])?(-0|-2|-4|-8)?$/,borderColor:/^border-(inherit|current|transparent|black|white|slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-/,borderStyle:/^border-(solid|dashed|dotted|double|hidden|none)$/,borderRadius:/^rounded(-[tblrse]{1,2})?(-none|-sm|-md|-lg|-xl|-2xl|-3xl|-full)?$/,ringWidth:/^ring(-0|-1|-2|-4|-8|-inset)?$/,ringColor:/^ring-(inherit|current|transparent|black|white|slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-/,ringOffset:/^ring-offset-/,shadow:/^shadow(-sm|-md|-lg|-xl|-2xl|-inner|-none)?$/,opacity:/^opacity-/,mixBlend:/^mix-blend-/,bgBlend:/^bg-blend-/,blur:/^blur(-none|-sm|-md|-lg|-xl|-2xl|-3xl)?$/,brightness:/^brightness-/,contrast:/^contrast-/,grayscale:/^grayscale(-0)?$/,hueRotate:/^-?hue-rotate-/,invert:/^invert(-0)?$/,saturate:/^saturate-/,sepia:/^sepia(-0)?$/,backdropBlur:/^backdrop-blur-/,backdropBrightness:/^backdrop-brightness-/,backdropContrast:/^backdrop-contrast-/,backdropGrayscale:/^backdrop-grayscale-/,backdropHueRotate:/^backdrop-hue-rotate-/,backdropInvert:/^backdrop-invert-/,backdropOpacity:/^backdrop-opacity-/,backdropSaturate:/^backdrop-saturate-/,backdropSepia:/^backdrop-sepia-/,scale:/^scale(-x|-y)?-/,rotate:/^-?rotate-/,translate:/^-?translate-[xy]-/,skew:/^-?skew-[xy]-/,transformOrigin:/^origin-/,transition:/^transition(-none|-all|-colors|-opacity|-shadow|-transform)?$/,duration:/^duration-/,ease:/^ease-(linear|in|out|in-out)$/,delay:/^delay-/,animate:/^animate-/,cursor:/^cursor-/,userSelect:/^select-/,pointerEvents:/^pointer-events-/,resize:/^resize(-none|-x|-y)?$/,scrollBehavior:/^scroll-(auto|smooth)$/,touchAction:/^touch-/,overflow:/^overflow(-x|-y)?-(auto|hidden|clip|visible|scroll)$/,overscroll:/^overscroll(-x|-y)?-(auto|contain|none)$/,visibility:/^(visible|invisible|collapse)$/,aspectRatio:/^aspect-/,columns:/^columns-/,breakAfter:/^break-after-/,breakBefore:/^break-before-/,breakInside:/^break-inside-/,boxDecorationBreak:/^box-decoration-/,boxSizing:/^box-(border|content)$/,float:/^float-(right|left|none)$/,clear:/^clear-(left|right|both|none)$/,isolation:/^(isolate|isolation-auto)$/,objectFit:/^object-(contain|cover|fill|none|scale-down)$/,objectPosition:/^object-/};function oy(o){const e=o.replace(/^(dark:|hover:|focus:|active:|disabled:|group-hover:|sm:|md:|lg:|xl:|2xl:)+/,"");for(const[a,r]of Object.entries(J_))if(r.test(e))return a;return null}function ly(o){const e=o.match(/^((dark:|hover:|focus:|active:|disabled:|group-hover:|sm:|md:|lg:|xl:|2xl:)+)/);return e?e[1]:""}function Q_(o,e){if(!e||e.trim()==="")return o;if(!o||o.trim()==="")return e;const a=o.split(/\s+/).filter(Boolean),r=e.split(/\s+/).filter(Boolean),i=new Map;for(const u of r){const d=oy(u);if(d){const f=ly(u),g=`${d}:${f}`;i.set(g,u)}}return[...a.filter(u=>{const d=oy(u);if(!d)return!0;const f=ly(u),g=`${d}:${f}`;return!i.has(g)}),...r].join(" ")}function Z_(o){return Object.entries(o).filter(([,e])=>e).map(([e])=>e).join(" ")}function eA(...o){return o.filter(e=>typeof e=="string"&&e.length>0).join(" ")}const we=ct("G7CoreGlobals");function tA(){window.React=Ye,window.ReactDOM={...Qu,createPortal:Ar.createPortal,unstable_batchedUpdates:o=>o()},window.ReactJSXRuntime=J0,we.log("전역 객체 window.React, window.ReactDOM, window.ReactJSXRuntime에 노출됨")}function nA(o){const e=new Map,a=Tr.getInstance();o.componentEvent={on:(r,i)=>(e.has(r)||e.set(r,new Set),e.get(r).add(i),a.trackEventSubscribe(r),()=>{e.get(r)?.delete(i),a.trackEventUnsubscribe(r)}),emit:async(r,i)=>{const l=e.get(r),u=l?.size??0;if(!l||l.size===0)return a.trackEventEmit(r,i,0),[];let d,f=[];try{f=await Promise.all(Array.from(l).map(async g=>{try{return await g(i)}catch(m){throw we.error(`componentEvent: Error in listener for "${r}":`,m),m}}))}catch(g){d=g instanceof Error?g:new Error(String(g))}if(a.trackEventEmit(r,i,u,f,d),d)throw d;return f},off:r=>{e.delete(r),a.trackEventOff(r)},clear:()=>{e.clear(),a.trackEventClear()}},we.log("전역 객체 window.G7Core.componentEvent에 노출됨")}function aA(o){o.__runtime||(o.__runtime={DynamicRenderer:Ha,ComponentRegistry:da,TranslationEngine:Cr,DataSourceManager:va,dataSourceManager:I_,DataBindingEngine:wn,dataBindingEngine:XS,ActionDispatcher:lo,TranslationReactContext:nf,TranslationProvider:uc,useTranslation:Fm,ResponsiveContext:Md,ResponsiveProvider:Jl,useResponsive:$d,responsiveManager:ui,BREAKPOINT_PRESETS:Dl,AuthManager:ha,createLogger:ct,G7DevToolsCore:Tr},we.log("전역 객체 window.G7Core.__runtime(코어 런타임 표면)에 노출됨"))}function rA(o){if(o.layoutEditor&&o.layoutEditor.__isStub!==!0||o.layoutEditor&&o.layoutEditor.__isStub===!0)return;const e=[],a=[];o.layoutEditor={__isStub:!0,__queue:e,__readyCallbacks:a,registerWidget:(r,i)=>e.push(["widget",r,i]),registerNodeEditor:(r,i)=>e.push(["nodeEditor",r,i]),registerCanvasOverlay:(r,i)=>e.push(["canvasOverlay",r,i]),onReady:r=>{typeof r=="function"&&a.push(r)}},we.log("전역 객체 window.G7Core.layoutEditor 예약 접수함(stub) 노출됨")}function iA(o,e){o.useTranslation=Fm,o.t=(a,r)=>{const i=e.getState();if(!i.translationEngine||!i.translationContext)return a;if(r){const l="|"+Object.entries(r).map(([u,d])=>`${u}=${d}`).join("|");return i.translationEngine.translate(a,i.translationContext,l)}return i.translationEngine.translate(a,i.translationContext)},we.log("전역 객체 window.G7Core.useTranslation에 노출됨")}function sA(o,e){o.createChangeEvent=K_,o.createClickEvent=W_,o.createSubmitEvent=Y_,o.createKeyboardEvent=X_,o.uuid=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,a=>{const r=Math.random()*16|0;return(a==="x"?r:r&3|8).toString(16)}),o.createLogger=ct,we.log("전역 객체 window.G7Core.createLogger에 노출됨"),o.renderItemChildren=(a,r,i,l,u)=>{const d=e.getState(),m={_global:window.__templateApp?.getGlobalState?.()||{},_local:r._local||{},_computed:r._computed||{},...r},b=new Set,v=(E,A)=>{const T=m._global?._remountKeys;return E&&T?.[E]&&!b.has(E)?(b.add(E),`${E}-remount-${T[E]}`):E||A},S={translationContext:d.translationContext,translationEngine:d.translationEngine,bindingEngine:d.bindingEngine,actionDispatcher:d.actionDispatcher,getRemountKey:v,...u};return Zs(a,m,i,l,S)},o.getComponentMap=()=>da.getInstance().getComponentMap(),o.renderComponentLayout=(a,r,i)=>{if(!a||!Array.isArray(a)||a.length===0)return null;const l=da.getInstance().getComponentMap(),u=e.getState(),f=window.__templateApp?.getGlobalState?.()||{},g={_global:f._global||{},_local:f._local||{},_computed:f._computed||{},...r},m=new Set,b=(v,S)=>{const E=g._global?._remountKeys;return v&&E?.[v]&&!m.has(v)?(m.add(v),`${v}-remount-${E[v]}`):v||S};return Zs(a,g,l,i,{translationContext:u.translationContext,translationEngine:u.translationEngine,bindingEngine:u.bindingEngine,actionDispatcher:u.actionDispatcher,getRemountKey:b})},o.renderExpandContent=a=>{const{children:r,row:i,expandContext:l,componentContext:u,keyPrefix:d}=a;if(!r||!Array.isArray(r)||r.length===0)return null;const f=a.componentMap||da.getInstance().getComponentMap(),g=e.getState(),m=o.state?.get?.()||{},b=u?.stateRef?.current??u?.state??{},v={...m._local||{},...b},S=u?.computedRef?.current??m._computed??{},E=g.bindingEngine??o.getDataBindingEngine?.(),A={...m,_local:v,_computed:S,row:i,item:i,$item:i};let T={};if(l&&typeof l=="object"&&E)try{for(const[D,U]of Object.entries(l))if(typeof U=="string"){const j=U.match(/^\{\{([^}]+)\}\}$/);if(j){const P=j[1].trim();try{T[D]=E.evaluateExpression(P,A,{skipCache:!0})}catch{T[D]=void 0}}else T[D]=E.resolveBindings(U,A,{skipCache:!0})}else T[D]=U}catch(D){we.warn("renderExpandContent: expandContext 평가 오류:",D)}const L={row:i,item:i,$item:i,_local:v,_global:m._global||{},_computed:m._computed||{},...T},M=new Set,R=(D,U)=>{const j=L._global?._remountKeys;return D&&j?.[D]&&!M.has(D)?(M.add(D),`${D}-remount-${j[D]}`):D||U};return Zs(r,L,f,d,{translationContext:g.translationContext,translationEngine:g.translationEngine??void 0,bindingEngine:g.bindingEngine??void 0,actionDispatcher:g.actionDispatcher,componentContext:u,getRemountKey:R})},o.$get=function(r,i,l=void 0){if(r==null)return l;const u=Array.isArray(i)?i:[i];if(u.length===0)return r;let d=r;for(const f of u){if(d==null||f==null)return l;d=d[f]}return d??l},we.log("전역 객체 window.G7Core.renderItemChildren에 노출됨"),we.log("전역 객체 window.G7Core.renderComponentLayout에 노출됨"),we.log("전역 객체 window.G7Core.renderExpandContent에 노출됨"),we.log("전역 객체 window.G7Core.$get에 노출됨")}function oA(o){o.dispatch=async(e,a)=>{const r=window.__templateApp;if(!r)return we.warn("G7Core.dispatch: TemplateApp이 초기화되지 않았습니다."),{success:!1,error:new Error("TemplateApp이 초기화되지 않았습니다.")};const i=r.getActionDispatcher?.();if(!i)return we.warn("G7Core.dispatch: ActionDispatcher를 찾을 수 없습니다."),{success:!1,error:new Error("ActionDispatcher를 찾을 수 없습니다.")};const l=r.getRouter?.(),u=r.getGlobalState?.(),d=r.setGlobalState?.bind(r),g=a?.componentContext||window.__g7ActionContext,m=window.__g7PendingLocalState;let b=g?.state??u;m&&g&&(b=m,we.log("[dispatch] Using __g7PendingLocalState for context.state:",m));let v=g?.data??u;m&&g?.data?._local&&(v={...g.data,_local:m},we.log("[dispatch] Updated context.data._local with pendingLocalState"));const S={navigate:l?(E,A)=>l.navigate(E,A):void 0,setState:g?.setState??d,state:b,data:v,_isDispatchFallbackContext:!g?.setState};if(e.debounce){const E=e.debounceKey||`dispatch-${e.handler}`,A=typeof e.debounce=="number"?e.debounce:e.debounce.delay;return i.debouncedCall(E,A,()=>{const{debounce:T,debounceKey:L,...M}=e;i.dispatchAction(M,S)}),{success:!0,debounced:!0}}try{return await i.dispatchAction(e,S)}catch(E){return we.error("G7Core.dispatch: 액션 실행 오류:",E),{success:!1,error:E instanceof Error?E:new Error(String(E))}}},we.log("전역 객체 window.G7Core.dispatch에 노출됨")}function wo(o){const e={};for(const[a,r]of Object.entries(o))if(a.includes(".")){const i=a.split(".");let l=e;for(let u=0;u0&&e.every(a=>/^\d+$/.test(a))}function uy(o,e){const a={...o};for(const r of Object.keys(e))r in a?a[r]!==null&&typeof a[r]=="object"&&!Array.isArray(a[r])&&e[r]!==null&&typeof e[r]=="object"&&!Array.isArray(e[r])&&(a[r]=uy(a[r],e[r])):a[r]=e[r];return a}function Zn(o,e){if(Array.isArray(o)&&!Array.isArray(e)&&lA(e)){const r=Object.keys(e).map(l=>parseInt(l,10));if(!((r.length>0?Math.max(...r):0)>=o.length+r.length+10)){const l=[...o];for(const[u,d]of Object.entries(e)){const f=parseInt(u,10);f>=0&&f=l.length&&(l[f]=d)}return l}}const a={...o};for(const[r,i]of Object.entries(e))i!==null&&typeof i=="object"&&!Array.isArray(i)?a[r]!==null&&typeof a[r]=="object"?a[r]=Zn(a[r],i):a[r]={...i}:a[r]=i;return a}function cA(o){o.state={get:()=>window.__templateApp?.getGlobalState?.()||{},set:(e,a)=>{const r=window.__templateApp;if(r?.setGlobalState&&r?.getGlobalState){const i=a?.merge||"deep",l=wo(e);let u;if(i==="replace")u=l;else if(i==="shallow")u={...r.getGlobalState(),...l};else{const d=r.getGlobalState();u=Zn(d,l)}r.setGlobalState(u,{render:a?.render})}else we.warn("G7Core.state.set: TemplateApp이 초기화되지 않았습니다.")},setLocal:(e,a)=>{const r=window.__templateApp;if(a?.render===!1&&!a?.selfManaged){const T=window.__g7AutoBindingPaths;T&&T.size>0&&cy(wo(e)).some(M=>T.has(M))&&(we.log("[setLocal] render:false + 자동바인딩 경로 겹침 감지 → render:true 자동 승격 (engine-v1.43.0)"),a={...a,render:!0})}if(a?.debounce){const T=r?.getActionDispatcher?.();if(T){const L=a.debounceKey||`setLocal-${Object.keys(e).join(",")}`,{debounce:M,debounceKey:R,...D}=a;T.debouncedCall(L,a.debounce,()=>{o.state.setLocal(e,D)});return}}const i=a?.scope??"current",l=a?.merge||"deep",u=window.__g7ActionContext,d=wo(e);if(i==="parent"||i==="root"){const T=window.__g7LayoutContextStack||[];if(T.length>0){const L=i==="parent"?T[T.length-1]:T[0];if(L?.setState){L.setState(M=>l==="replace"?d:l==="shallow"?{...M||{},...d}:Zn(M||{},d)),we.log(`[setLocal] scope=${i}: 타겟 컨텍스트에 상태 업데이트 (mergeMode=${l})`,d);return}}we.warn(`[setLocal] scope=${i}: 레이아웃 컨텍스트 스택이 비어있습니다. current로 폴백합니다.`)}const f=window.__g7PendingLocalState,g=r?.getGlobalState?.()?._local||{},v=!((window.__g7LayoutContextStack||[]).length>0)&&u?.state?u.state:void 0,S=v?uy(g,v):g,E=f||S;let A;if(l==="replace"?A=d:l==="shallow"?A={...E,...d}:A=Zn(E,d),r?.setGlobalState&&(r.setGlobalState({_local:A},{render:a?.render}),we.log(`[setLocal] globalLocal updated via setGlobalState (mergeMode=${l}, render=${a?.render??!0}):`,d)),window.__g7PendingLocalState=A,we.log("[setLocal] __g7PendingLocalState updated:",A),window.__g7SequenceLocalSync=A,window.__g7LastSetLocalSnapshot=A,l==="replace")window.__g7ForcedLocalFields=d;else{const T=window.__g7ForcedLocalFields||{};window.__g7ForcedLocalFields=Zn(T,d)}if(we.log("[setLocal] __g7ForcedLocalFields updated:",d),l==="replace")window.__g7SetLocalOverrideKeys=d;else{const T=window.__g7SetLocalOverrideKeys||{};window.__g7SetLocalOverrideKeys=Zn(T,d)}we.log("[setLocal] __g7SetLocalOverrideKeys updated:",d),u?.setState&&u.setState(T=>l==="replace"?d:l==="shallow"?{...T||{},...d}:Zn(T||{},d)),r?.setGlobalState||we.warn("G7Core.state.setLocal: TemplateApp이 없습니다.")},getLocal:()=>{const r=(window.__templateApp?.getGlobalState?.()||{})._local||{},i=window.__g7PendingLocalState;if(i)return Zn(r,i);const l=window.__g7LastSetLocalSnapshot;return l&&l!==r?Zn(r,l):r},update:e=>{const a=window.__templateApp;if(a?.getGlobalState&&a?.setGlobalState){const r=a.getGlobalState(),i=e(r);a.setGlobalState(i)}else we.warn("G7Core.state.update: TemplateApp이 초기화되지 않았습니다.")},subscribe:e=>{const a=window.__templateApp;return a?.onGlobalStateChange?a.onGlobalStateChange(e):(we.warn("G7Core.state.subscribe: TemplateApp이 초기화되지 않았습니다."),()=>{})},getDataSource:e=>window.__templateApp?.getDataSource?.(e),getIsolated:e=>e?window.__g7IsolatedStates?.[e]?.state??null:window.__g7ActionContext?.isolatedContext?.state??null,setIsolated:(e,a,r)=>{let i,l,u;typeof e=="string"?(i=e,l=a||{},u=r):(l=e,u=a&&typeof a=="object"&&"merge"in a?a:r);const d=u?.merge||"deep",f=wo(l);if(i){const b=window.__g7IsolatedStates?.[i];b?.mergeState?b.mergeState(f,d):we.warn(`G7Core.state.setIsolated: scopeId '${i}'를 찾을 수 없습니다.`);return}const g=window.__g7ActionContext;g?.isolatedContext?.mergeState?g.isolatedContext.mergeState(f,d):we.warn("G7Core.state.setIsolated: 액션 컨텍스트에 isolatedContext가 없습니다.")},getParent:()=>{const e=window.__g7LayoutContextStack||[];if(e.length===0)return we.log("[getParent] 레이아웃 컨텍스트 스택이 비어있습니다."),null;const a=e[e.length-1];if(!a)return null;const r=a.dataContext||{};return{_local:a.state||r._local||{},_global:r._global||o.state.get()||{},setState:a.setState}},setParentLocal:(e,a,r)=>{const i=window.__g7LayoutContextStack||[];if(i.length===0){we.warn("[setParentLocal] 레이아웃 컨텍스트 스택이 비어있습니다.");return}const l=i[i.length-1];if(!l?.setState){we.warn("[setParentLocal] 부모 컨텍스트에 setState가 없습니다.");return}let u,d;typeof e=="string"?(u={[e]:a},d=r):(u=e,d=a&&typeof a=="object"&&"merge"in a?a:r);const f=d?.merge||"deep",g=wo(u),m=l.state?._local!==void 0,b=m?l.state._local:l.state||{};let v;f==="replace"?v=g:f==="shallow"?v={...b,...g}:v=Zn(b,g),window.__g7PendingLocalState=v;const S=window.__templateApp;if(S?.setGlobalState&&S.setGlobalState({_local:v}),l.setState(v),m?l.state._local=v:l.state=v,l.dataContext&&(l.dataContext._local=v),f==="replace")window.__g7ForcedLocalFields=g;else{const E=window.__g7ForcedLocalFields||{};window.__g7ForcedLocalFields=Zn(E,g)}Dd()},setParentGlobal:(e,a)=>{let r;typeof e=="string"?r={[e]:a}:r=e,o.state.set(r),we.log("[setParentGlobal] 전역 상태 업데이트:",r)}},window.__g7IsolatedStates||(window.__g7IsolatedStates={}),o.state.getGlobal=o.state.get,o.state.setGlobal=o.state.set,we.log("전역 객체 window.G7Core.state에 노출됨")}function uA(o){o.dataSource={get:e=>window.__templateApp?.getDataSource?.(e),set:(e,a,r)=>{const i=window.__templateApp;i?.setDataSource?i.setDataSource(e,a,r):we.warn("G7Core.dataSource.set: TemplateApp이 초기화되지 않았습니다.")},refetch:async(e,a)=>{const r=window.__templateApp;if(r?.refetchDataSource)return r.refetchDataSource(e,a);we.warn("G7Core.dataSource.refetch: TemplateApp이 초기화되지 않았습니다.")},updateItem:(e,a,r,i,l)=>{const u=window.__templateApp;return u?.updateDataSourceItem?u.updateDataSourceItem(e,a,r,i,l):(we.warn("G7Core.dataSource.updateItem: TemplateApp이 초기화되지 않았습니다."),!1)},updateData:(e,a,r,i="append")=>{const l=window.__templateApp;if(!l?.getDataSource||!l?.setDataSource)return we.warn("G7Core.dataSource.updateData: TemplateApp이 초기화되지 않았습니다."),!1;const u=l.getDataSource(e);if(!u)return we.warn(`G7Core.dataSource.updateData: 데이터 소스 '${e}'를 찾을 수 없습니다.`),!1;let d,f=u,g=null;if(a){const b=a.split(".");g=b.pop();for(const v of b)if(f&&typeof f=="object"&&v in f)f=f[v];else return we.warn(`G7Core.dataSource.updateData: 경로 '${a}'를 찾을 수 없습니다.`),!1;d=f[g]}else d=u;if(!Array.isArray(d))return we.warn("G7Core.dataSource.updateData: 대상 경로의 데이터가 배열이 아닙니다."),!1;if(!Array.isArray(r))return we.warn("G7Core.dataSource.updateData: newData가 배열이 아닙니다."),!1;const m=i==="prepend"?[...r,...d]:[...d,...r];return a&&g?(f[g]=m,l.setDataSource(e,u,{merge:!1})):l.setDataSource(e,m,{merge:!1}),we.log(`G7Core.dataSource.updateData: '${e}'에 ${r.length}개 항목 ${i==="prepend"?"앞에":"뒤에"} 추가됨`),!0}},we.log("전역 객체 window.G7Core.dataSource에 노출됨")}function dA(o,e){o.locale={current:()=>window.__templateApp?.getLocale?.()||"ko",supported:()=>{const r=window.__templateApp?.globalState?.appConfig?.supportedLocales;return Array.isArray(r)&&r.length>0?r:e.getState().templateMetadata?.locales||["ko","en"]},change:async a=>{const r=window.__templateApp;r?.changeLocale?await r.changeLocale(a):we.warn("G7Core.locale.change: TemplateApp이 초기화되지 않았습니다.")}},we.log("전역 객체 window.G7Core.locale에 노출됨")}function fA(o){o.toast={show:(e,a)=>{o.dispatch({handler:"toast",params:{message:e,type:a?.type||"info",...a?.duration&&{duration:a.duration}}})},success:(e,a)=>{o.toast.show(e,{type:"success",duration:a})},error:(e,a)=>{o.toast.show(e,{type:"error",duration:a})},warning:(e,a)=>{o.toast.show(e,{type:"warning",duration:a})},info:(e,a)=>{o.toast.show(e,{type:"info",duration:a})}},we.log("전역 객체 window.G7Core.toast에 노출됨")}function hA(o){o.modal={open:e=>{o.dispatch({handler:"openModal",target:e})},close:e=>{o.dispatch({handler:"closeModal",...e&&{target:e}})},closeAll:()=>{o.dispatch({handler:"closeAllModals"})},isOpen:e=>{const a=o.state.get();return a._global?.activeModal===e||a._global?.modalStack?.includes(e)||!1},getStack:()=>o.state.get()._global?.modalStack||[]},we.log("전역 객체 window.G7Core.modal에 노출됨")}function gA(o){o.style={mergeClasses:Q_,conditionalClass:Z_,joinClasses:eA},we.log("전역 객체 window.G7Core.style에 노출됨")}function pA(o,e){const{webSocketManager:a}=e;o.websocket={manager:a,subscribe:(r,i,l,u)=>a.subscribe(r,i,l,u),unsubscribe:r=>a.unsubscribe(r),leaveChannel:r=>a.leaveChannel(r),disconnect:()=>a.disconnect(),isInitialized:()=>a.isInitialized(),getSubscriptionCount:()=>a.getSubscriptionCount()},we.log("전역 객체 window.G7Core.websocket에 노출됨")}function mA(o,e){const{transitionManager:a}=e;o.navigation={isPending:()=>a?.getIsPending?.()||!1,onComplete:r=>{if(!a)return r(),()=>{};let i=a.getIsPending();const l=a.subscribe(u=>{u?i=!0:i&&(r(),l())});return l}},we.log("전역 객체 window.G7Core.navigation에 노출됨")}function yA(o){o.plugin={getSettings:e=>window.G7Config?.plugins?.[e],get:(e,a,r)=>window.G7Config?.plugins?.[e]?.[a]??r,getAll:()=>window.G7Config?.plugins??{}},we.log("전역 객체 window.G7Core.plugin에 노출됨")}function bA(o){o.module={getSettings:e=>window.G7Config?.modules?.[e],get:(e,a,r)=>window.G7Config?.modules?.[e]?.[a]??r,getAll:()=>window.G7Config?.modules??{}},we.log("전역 객체 window.G7Core.module에 노출됨")}function vA(o,e){const{transitionManager:a,responsiveManager:r}=e;o.AuthManager=ha,o.api=$a(),o.TransitionManager=a,o.useTransitionState=nm,o.ResponsiveManager=r,o.useResponsive=$d,o.useControllableState=lC,o.shallowArrayEqual=cC,o.shallowObjectEqual=rm,o.updateQueryParams=async(i,l)=>{const u=window.__templateApp;if(u?.updateQueryParams)return u.updateQueryParams(i,l);we.warn("G7Core.updateQueryParams: TemplateApp이 초기화되지 않았습니다.")},we.log("전역 객체 window.G7Core.AuthManager에 노출됨"),we.log("전역 객체 window.G7Core.api에 노출됨"),we.log("전역 객체 window.G7Core.ResponsiveManager에 노출됨"),we.log("전역 객체 window.G7Core.useResponsive에 노출됨"),we.log("전역 객체 window.G7Core.useControllableState에 노출됨"),we.log("전역 객체 window.G7Core.updateQueryParams에 노출됨")}function SA(o,e){o.getSlotContext=()=>window.__slotContextValue??null,o.getDynamicRenderer=()=>window.__DynamicRenderer??null,o.getComponentRegistry=()=>e.getComponentRegistry?.()??da.getInstance(),o.getDataBindingEngine=()=>e.getDataBindingEngine?.()??e.getState().bindingEngine,o.getTranslationEngine=()=>e.getTranslationEngine?.()??e.getState().translationEngine,o.getActionDispatcher=()=>e.getActionDispatcher?.()??e.getState().actionDispatcher,we.log("전역 객체 window.G7Core 슬롯 API에 노출됨 (getSlotContext, getDynamicRenderer 등)")}function wA(o){o.identity={setLauncher:St.setLauncher.bind(St),handle:St.handle.bind(St),isIdentityRequired:St.isIdentityRequired.bind(St),hasLauncher:St.hasLauncher.bind(St),markDomainNoticeShown:St.markDomainNoticeShown.bind(St),redirectExternally:St.redirectExternally.bind(St),createDeferred:St.createDeferred.bind(St),resolveDeferred:St.resolveDeferred.bind(St),reset:St.reset.bind(St),redirectStashKey:_d},we.log("전역 객체 window.G7Core 본인인증(IDV) API에 노출됨 (identity)")}function CA(o){if(typeof window>"u")return;tA(),window.G7Core||(window.G7Core={});const e=window.G7Core;aA(e),nA(e),rA(e),vA(e,o),iA(e,o),sA(e,o),oA(e),cA(e),uA(e),dA(e,o),fA(e),hA(e),gA(e),pA(e,o),mA(e,o),yA(e),bA(e),SA(e,o),wA(e),we.log("G7Core 전역 객체 초기화 완료")}function EA(){const o=window.G7Core;if(!o){we.warn("G7Core가 초기화되지 않았습니다.");return}const e=()=>Tr.getInstance(),a={isEnabled:()=>{try{return e().isEnabled()}catch{return!1}},trackRender:r=>{try{e().isEnabled()&&e().trackRender(r)}catch{}},trackIteration:(r,i,l,u,d)=>{try{e().isEnabled()&&e().trackIteration(r,{source:i,itemVar:l,indexVar:u,sourceLength:d})}catch{}},trackIfCondition:(r,i,l,u)=>{try{e().isEnabled()&&e().trackIfCondition(r,i,l)}catch{}},trackMount:(r,i)=>{try{e().isEnabled()&&e().trackMount(r,{...i,id:r})}catch{}},trackUnmount:r=>{try{e().isEnabled()&&e().trackUnmount(r)}catch{}},trackExpressionEval:r=>{try{e().isEnabled()&&e().trackExpressionEval(r)}catch{}},trackBindingEval:r=>{try{e().isEnabled()&&e().trackBindingEval(r)}catch{}},recordCacheHit:()=>{try{e().isEnabled()&&e().recordCacheHit()}catch{}},recordCacheMiss:()=>{try{e().isEnabled()&&e().recordCacheMiss()}catch{}},trackHandlerRegistration:(r,i,l,u)=>{try{e().isEnabled()&&e().trackHandlerRegistration(r,i,l,u)}catch{}},trackHandlerUnregistration:r=>{try{e().isEnabled()&&e().trackHandlerUnregistration(r)}catch{}},logAction:r=>{try{e().isEnabled()&&e().logAction(r)}catch{}},trackRequest:(r,i)=>{try{return e().isEnabled()?e().trackRequest(r,i):""}catch{return""}},completeRequest:(r,i,l)=>{try{e().isEnabled()&&e().completeRequest(r,i,l)}catch{}},failRequest:(r,i)=>{try{e().isEnabled()&&e().failRequest(r,i)}catch{}},trackDataSourceDefinition:r=>{try{e().isEnabled()&&e().trackDataSourceDefinition(r)}catch{}},trackDataSourceLoading:r=>{try{e().isEnabled()&&e().trackDataSourceLoading(r)}catch{}},trackDataSourceLoaded:(r,i,l)=>{try{e().isEnabled()&&e().trackDataSourceLoaded(r,i,l)}catch{}},trackDataSourceError:(r,i)=>{try{e().isEnabled()&&e().trackDataSourceError(r,i)}catch{}},trackForm:(r,i,l)=>{try{e().isEnabled()&&e().trackForm(r,i,l)}catch{}},untrackForm:r=>{try{e().isEnabled()&&e().untrackForm(r)}catch{}},startStateChange:(r,i,l,u)=>{try{return e().isEnabled()?e().startStateChange(r,i,l,u):""}catch{return""}},completeStateChange:r=>{try{e().isEnabled()&&e().completeStateChange(r)}catch{}},trackComponentRender:(r,i,l,u,d,f)=>{try{e().isEnabled()&&e().trackComponentRender(r,i,l,u,d,f)}catch{}},updateLocalState:r=>{try{e().isEnabled()&&e().updateLocalState(r)}catch{}},updateComputedState:r=>{try{e().isEnabled()&&e().updateComputedState(r)}catch{}},updateParentContext:r=>{try{e().isEnabled()&&e().updateParentContext(r)}catch{}},trackComponentStateSource:(r,i,l,u)=>{try{e().isEnabled()&&e().trackComponentStateSource(r,i,l,u)}catch{}},trackDynamicState:(r,i)=>{try{e().isEnabled()&&e().trackDynamicState(r,i)}catch{}},trackContextFlow:(r,i,l,u,d,f)=>{try{e().isEnabled()&&e().trackContextFlow(r,i,l,u,d,f)}catch{}},trackComponentStyle:(r,i,l,u)=>{try{e().isEnabled()&&e().trackComponentStyle(r,i,l,u)}catch{}},trackAuthEvent:(r,i,l,u)=>{try{e().isEnabled()&&e().trackAuthEvent(r,i,l,u)}catch{}},trackAuthHeader:(r,i,l,u,d)=>{try{e().isEnabled()&&e().trackAuthHeader(r,i,l,u,d)}catch{}},trackLog:(r,i,l)=>{try{e().isEnabled()&&e().trackLog(r,i,l)}catch{}},trackAction:r=>{try{e().isEnabled()&&e().trackAction?.(r)}catch{}},trackDataSourceUpdate:r=>{try{e().isEnabled()&&e().trackDataSourceUpdate?.(r)}catch{}},startSequenceExecution:r=>{try{return e().isEnabled()?e().startSequenceExecution(r):""}catch{return""}},captureSequenceActionBefore:(r,i,l,u,d)=>{try{e().isEnabled()&&e().captureSequenceActionBefore(r,i,l,u,d)}catch{}},captureSequenceActionAfter:(r,i,l,u,d,f)=>{try{e().isEnabled()&&e().captureSequenceActionAfter(r,i,l,u,d,f)}catch{}},endSequenceExecution:(r,i)=>{try{e().isEnabled()&&e().endSequenceExecution(r,i)}catch{}},registerStateCaptureForHandler:(r,i,l)=>{try{e().isEnabled()&&e().registerStateCaptureForHandler(r,i,l)}catch{}},detectStaleClosure:(r,i,l,u,d)=>{try{return e().isEnabled()?e().detectStaleClosure(r,i,l,u,d):[]}catch{return[]}},trackStaleClosureWarning:r=>{try{e().isEnabled()&&e().trackStaleClosureWarning(r)}catch{}},trackModalOpen:r=>{try{e().isEnabled()&&e().trackModalOpen(r)}catch{}},trackModalClose:(r,i)=>{try{e().isEnabled()&&e().trackModalClose(r,i)}catch{}},trackModalStateChange:r=>{try{e().isEnabled()&&e().trackModalStateChange(r)}catch{}},trackNestedContext:r=>{try{return e().isEnabled()?e().trackNestedContext(r):""}catch{return""}},trackNestedContextAccess:(r,i)=>{try{e().isEnabled()&&e().trackNestedContextAccess(r,i)}catch{}},trackComputedProperty:(r,i,l,u,d,f,g)=>{try{e().isEnabled()&&e().trackComputedProperty(r,i,l,u,d,f,g)}catch{}},trackComputedRecalc:(r,i,l,u,d,f,g)=>{try{e().isEnabled()&&e().trackComputedRecalc(r,i,l,u,d,f,g)}catch{}},setNamedActionDefinitions:r=>{try{e().isEnabled()&&e().setNamedActionDefinitions(r)}catch{}},trackNamedActionRef:r=>{try{e().isEnabled()&&e().trackNamedActionRef(r)}catch{}}};o.devTools=a,we.log("G7Core.devTools 인터페이스 초기화 완료")}let Co=null;function _A(){const o=window.G7Core;return o?.__devtools?Promise.resolve(o.__devtools):Co||(Co=new Promise((e,a)=>{const r=window.G7Config?.coreDevToolsAsset||"/build/core/devtools.min.js",i="g7-devtools-bundle",l=()=>{const f=window.G7Core?.__devtools;f?e(f):a(new Error("DevTools 번들 로드됨 — 그러나 __devtools 미노출"))};window.G7Core=window.G7Core||{},window.G7Core.__onDevToolsReady=l;const u=document.getElementById(i);if(u){u.addEventListener("load",l,{once:!0}),u.addEventListener("error",()=>a(new Error(`DevTools 번들 로드 실패: ${r}`)),{once:!0});return}const d=document.createElement("script");d.id=i,d.src=r,d.async=!1,d.addEventListener("load",l,{once:!0}),d.addEventListener("error",()=>{Co=null,a(new Error(`DevTools 번들 로드 실패: ${r}`))},{once:!0}),document.head.appendChild(d)}),Co)}function AA(){const o=window.G7Core;if(!o){we.warn("G7Core가 초기화되지 않았습니다.");return}const e=Tr.getInstance();if(e.initialize(),!e.isEnabled()){window.G7DevTools={isEnabled:()=>!1,enable:()=>{we.log("환경설정 > 고급 설정 > 디버그 모드를 켜세요")}},ed(),we.log("G7DevTools 비활성화됨 (디버그 모드 꺼짐)");return}xA(o,e)}async function xA(o,e){let a;try{a=await _A()}catch(g){we.warn("DevTools 번들 로드 실패 — 최소 API 로 폴백:",g),window.G7DevTools={isEnabled:()=>!1,enable:()=>{}},ed();return}const{DiagnosticEngine:r,getServerConnector:i,getStyleTracker:l}=a;EA(),ed();try{l().enable(),we.log("StyleTracker 활성화됨")}catch(g){we.warn("StyleTracker 활성화 실패:",g)}const u=new r,d=i(),f={isEnabled:()=>e.isEnabled(),state:{get:()=>e.getState(),getHistory:()=>e.getStateHistory(),watch:(g,m)=>e.watchState(g,m)},actions:{getHistory:()=>e.getActionHistory(),watch:g=>e.watchActions(g),getMetrics:()=>e.getActionMetrics()},binding:{evaluate:g=>{const m=o.getDataBindingEngine?.();if(!m){we.warn("DataBindingEngine이 없습니다.");return}return m.evaluateExpression(g,e.getState())},getCacheStats:()=>e.getCacheStats(),clearStats:()=>{e.resetCacheStats(),we.log("캐시 통계 초기화됨")}},diagnose:{analyze:g=>u.analyze(g),suggestFix:g=>u.suggestFix(g),getCommonIssues:()=>u.getCommonIssues(),getRulesByCategory:g=>u.getRulesByCategory(g)},server:{dumpState:g=>d.dumpState(g),sendLog:g=>d.sendLog(g),sendError:(g,m)=>d.sendError(g,m),isConnected:()=>d.isConnected(),testConnection:()=>d.testConnection()},config:{isDebugMode:()=>e.isEnabled(),setLogLevel:g=>e.setLogLevel(g),setMaxHistory:g=>e.setMaxHistory(g)},lifecycle:{getMountedComponents:()=>e.getLifecycleInfo().mountedComponents,getOrphanedListeners:()=>e.getLifecycleInfo().orphanedListeners},performance:{getRenderCount:()=>e.getPerformanceInfo().renderCounts,getBindingEvalCount:()=>e.getPerformanceInfo().bindingEvalCount,getMemoryWarnings:()=>e.getPerformanceInfo().memoryWarnings,startProfiling:()=>e.startProfiling(),stopProfiling:()=>e.stopProfiling()},network:{getActiveRequests:()=>e.getNetworkInfo().activeRequests,getRequestHistory:()=>e.getNetworkInfo().requestHistory,getPendingDataSources:()=>e.getNetworkInfo().pendingDataSources},conditional:{getIfConditions:()=>e.getConditionalInfo().ifConditions,getIterations:()=>e.getConditionalInfo().iterations},form:{getForms:()=>e.getFormInfo()},websocket:{getInfo:()=>e.getWebSocketInfo()}};window.G7DevTools=f,o.devtools=f,we.log("G7DevTools 전역 객체 초기화 완료 (window.G7DevTools)"),TA(a.DevToolsPanel)}function TA(o){if(document.getElementById("g7-devtools-root")){we.log("DevToolsPanel 이미 렌더링됨");return}const e=document.createElement("div");e.id="g7-devtools-root",document.body.appendChild(e);try{Qu.createRoot(e).render(Ye.createElement(o)),we.log("DevToolsPanel UI 렌더링 완료")}catch(a){we.error("DevToolsPanel UI 렌더링 실패:",a)}}const Ze=ct("TemplateEngine"),se={templateId:null,locale:"ko",isInitialized:!1,reactRoot:null,containerId:null,currentLayoutJson:null,currentDataContext:{},translationContext:{templateId:"",locale:"ko"},registry:null,bindingEngine:null,translationEngine:null,actionDispatcher:null,templateMetadata:null};let Eo=!1;const _o=[];async function RA(o){try{Ze.log("템플릿 메타데이터 로드 중...",o);const e=o.split("-").map(r=>r.split("_").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join("")).join(""),a=window[e];return a?.templateMetadata?(Ze.log("템플릿 메타데이터 로드 완료 (전역 변수)",a.templateMetadata),a.templateMetadata):(Ze.warn(`템플릿 번들에 메타데이터가 없습니다. 전역 변수: ${e}`),{identifier:o,locales:["ko","en"],name:{ko:o,en:o},description:{ko:"",en:""},version:"1.0.0",type:"admin"})}catch(e){return Ze.error("템플릿 메타데이터 로드 실패",e),{identifier:o,locales:["ko","en"],name:{ko:o,en:o},description:{ko:"",en:""},version:"1.0.0",type:"admin"}}}function dy(){const e=(typeof window<"u"?window.__templateApp:void 0)?.globalState?.appConfig?.supportedLocales,a=se.templateMetadata?.locales;return{$locale:se.locale,$locales:Array.isArray(e)&&e.length>0?e:a||["ko","en"],$templateLocales:a||["ko","en"],$templateId:se.templateId}}async function Ao(o){try{if(Ze.log("템플릿 엔진 초기화 시작",o),se.isInitialized)throw new Error("템플릿 엔진이 이미 초기화되었습니다. destroyTemplate()을 먼저 호출하세요.");if(!o.templateId)throw new z_;Eo=o.debug??!1,typeof window<"u"&&(window.G7Config||(window.G7Config={}),window.G7Config.debug=Eo),AA(),se.templateId=o.templateId,se.locale=o.locale||"ko",Ze.log("엔진 인스턴스 생성 중..."),se.registry=da.getInstance(),se.bindingEngine=new wn,se.translationEngine=Cr.getInstance(),o.cacheVersion!==void 0&&o.cacheVersion>0&&se.translationEngine.setCacheVersion(o.cacheVersion),se.translationContext={templateId:o.templateId,locale:se.locale},se.actionDispatcher=new lo({},se.translationEngine,se.translationContext),eC(se.actionDispatcher),Ze.log("다국어 파일 로드 중...",o.templateId,se.locale);const e="en",a=[se.translationEngine.loadTranslations(o.templateId,se.locale).then(()=>{Ze.log(`다국어 파일 로드 완료: ${se.locale}`)}).catch(r=>{Ze.warn(`다국어 파일 로드 실패 (${se.locale}):`,r instanceof Error?r.message:r)})];se.locale!==e&&a.push(se.translationEngine.loadTranslations(o.templateId,e).then(()=>{Ze.log(`폴백 다국어 파일 로드 완료: ${e}`)}).catch(r=>{Ze.warn(`폴백 다국어 파일 로드 실패 (${e}):`,r instanceof Error?r.message:r)})),await Promise.allSettled(a),Ze.log("템플릿 메타데이터 로드 중...",o.templateId),se.templateMetadata=await RA(o.templateId),se.isInitialized=!0,Ze.log("템플릿 엔진 초기화 완료 (ComponentRegistry는 별도 로드)")}catch(e){throw Ze.error("템플릿 엔진 초기화 실패",e),se.isInitialized=!1,se.registry=null,se.bindingEngine=null,se.translationEngine=null,se.actionDispatcher=null,e}}let xo=null;function gf(){const o=window.G7Core;return o?.__LayoutEditorChrome?Promise.resolve(o.__LayoutEditorChrome):xo||(xo=new Promise((e,a)=>{const r=window.G7Config?.coreEditorAsset||"/build/core/layout-editor.min.js",i="g7-layout-editor-bundle",l=document.getElementById(i),u=()=>{const f=window.G7Core?.__LayoutEditorChrome;f?e(f):a(new Error("편집기 번들 로드됨 — 그러나 __LayoutEditorChrome 미노출"))};if(window.G7Core=window.G7Core||{},window.G7Core.__onChromeReady=u,l){l.addEventListener("load",u,{once:!0}),l.addEventListener("error",()=>a(new Error(`편집기 번들 로드 실패: ${r}`)),{once:!0});return}const d=document.createElement("script");d.id=i,d.src=r,d.async=!1,d.addEventListener("load",u,{once:!0}),d.addEventListener("error",()=>{xo=null,a(new Error(`편집기 번들 로드 실패: ${r}`))},{once:!0}),document.head.appendChild(d)}),xo)}async function ls(o){try{if(Ze.log("템플릿 렌더링 시작",o),!se.isInitialized)throw new Error("템플릿 엔진이 초기화되지 않았습니다. initTemplateEngine()을 먼저 호출하세요.");if(!o.containerId)throw new Error("containerId는 필수입니다.");if(!o.layoutJson)throw new Error("layoutJson은 필수입니다.");const e=document.getElementById(o.containerId);if(!e)throw new Error(`컨테이너를 찾을 수 없습니다: #${o.containerId}`);const a=dy();if(se.containerId=o.containerId,se.currentLayoutJson=o.layoutJson,se.currentDataContext={...a,...o.dataContext||{}},se.translationContext=o.translationContext||{templateId:se.templateId||"",locale:se.locale},se.reactRoot||(Ze.log("React Root 생성"),se.reactRoot=Qu.createRoot(e)),typeof window<"u"){const l=iy(window.location.pathname);if(l){Ze.log("레이아웃 편집기 모드 진입",l);let u;try{u=await gf()}catch(f){Ze.error("레이아웃 편집기 번들 로드 실패",f),cf.render(o.containerId,{title:"레이아웃 편집기 로드 실패",message:f instanceof Error?f.message:"편집기 번들을 불러오지 못했습니다.",icon:"fas fa-triangle-exclamation",showStack:!1,showReloadButton:!0,debug:Eo});return}const d=Ye.createElement(u,{templateIdentifier:l.templateIdentifier,initialLocale:se.locale});se.reactRoot.render(Ye.createElement(uc,{translationEngine:se.translationEngine,translationContext:se.translationContext,children:Ye.createElement(Od,{children:Ye.createElement(Jl,{children:Ye.createElement(af,{children:d})})})}));return}}const r=o.layoutJson.components||[];if(r.length===0){Ze.warn("렌더링할 컴포넌트가 없습니다.");return}const i=o.layoutJson.modals||[];if(Ze.log("modals 배열:",i),Ze.log("modals 개수:",i.length),Ze.log("DynamicRenderer로 렌더링 시작"),se.reactRoot.render(Ye.createElement(uc,{translationEngine:se.translationEngine,translationContext:se.translationContext},Ye.createElement(Od,null,Ye.createElement(Jl,null,Ye.createElement(af,null,[...r.map((l,u)=>{const d=se.currentLayoutJson?.layout_name||"";return Ye.createElement(Ha,{key:d&&!l._fromBase?`${l.id}_${d}`:l.id,componentDef:l,dataContext:se.currentDataContext,translationContext:se.translationContext,registry:se.registry,bindingEngine:se.bindingEngine,translationEngine:se.translationEngine,actionDispatcher:se.actionDispatcher,isRootRenderer:u===0,layoutKey:d})}),Ye.createElement(Jp,{key:"__modal_parent_context_provider"},i.map(l=>{const u=se.currentDataContext._global?.modalStack||[],f=u.includes(l.id)||se.currentDataContext._global?.activeModal===l.id,g=u.indexOf(l.id),m=g>=0?50+g:50,b=window.__g7LayoutContextStack||[],S=b[b.length-1]?.dataContext,E=Ye.createElement(Ha,{key:`modal_${l.id}_renderer`,componentDef:{...l,props:{...l.props,isOpen:f,style:{...l.props?.style,zIndex:m},onClose:se.actionDispatcher?.createHandler({type:"click",handler:"closeModal"},se.currentDataContext)}},dataContext:se.currentDataContext,translationContext:se.translationContext,registry:se.registry,bindingEngine:se.bindingEngine,translationEngine:se.translationEngine,actionDispatcher:se.actionDispatcher,parentDataContext:S});return l.data_sources&&l.data_sources.length>0?Ye.createElement(ay,{key:`modal_${l.id}`,isOpen:f,modalId:l.id,dataSources:l.data_sources,dataContext:se.currentDataContext,globalStateUpdater:se.actionDispatcher?.getGlobalStateUpdater(),bindingEngine:se.bindingEngine,debug:Eo,children:E}):E}))]))))),Ze.log("템플릿 렌더링 완료"),_o.length>0){Ze.log(`대기 중인 데이터 업데이트 ${_o.length}건 적용`);const l=[..._o];_o.length=0;for(const{data:u,options:d}of l)cs(u,d)}}catch(e){throw Ze.error("템플릿 렌더링 실패",e),e}}function cs(o,e){try{if(Ze.log("템플릿 데이터 업데이트 시작",Object.keys(o)),!se.isInitialized)throw new Error("템플릿 엔진이 초기화되지 않았습니다.");if(!se.reactRoot||!se.currentLayoutJson){Ze.log("React 미준비 - 데이터 업데이트 큐잉:",Object.keys(o)),_o.push({data:o,options:e});return}const a=dy(),r={...se.currentDataContext._global||{},...o._global||{}},i=sC(se.currentDataContext._localInit,o._localInit);se.currentDataContext={...a,...se.currentDataContext,...o,_global:r,_localInit:i},r._local!==void 0&&(se.currentDataContext._local=r._local),r._computed!==void 0&&(se.currentDataContext._computed=r._computed);const l=se.currentLayoutJson.components||[],u=se.currentLayoutJson.modals||[];Ze.log("updateTemplateData - modals 배열:",u),Ze.log("updateTemplateData - modals 개수:",u.length),Ze.log("updateTemplateData - activeModal:",se.currentDataContext._global?.activeModal);const d=()=>{se.reactRoot.render(Ye.createElement(uc,{translationEngine:se.translationEngine,translationContext:se.translationContext},Ye.createElement(Od,null,Ye.createElement(Jl,null,Ye.createElement(af,null,[...l.map((f,g)=>{const m=se.currentLayoutJson?.layout_name||"";return Ye.createElement(Ha,{key:m&&!f._fromBase?`${f.id}_${m}`:f.id,componentDef:f,dataContext:se.currentDataContext,translationContext:se.translationContext,registry:se.registry,bindingEngine:se.bindingEngine,translationEngine:se.translationEngine,actionDispatcher:se.actionDispatcher,isRootRenderer:g===0,layoutKey:m})}),Ye.createElement(Jp,{key:"__modal_parent_context_provider_update"},u.map(f=>{const g=se.currentDataContext._global?.modalStack||[],b=g.includes(f.id)||se.currentDataContext._global?.activeModal===f.id,v=g.indexOf(f.id),S=v>=0?50+v:50,E=window.__g7LayoutContextStack||[],T=E[E.length-1]?.dataContext,L=Ye.createElement(Ha,{key:`modal_${f.id}_renderer`,componentDef:{...f,props:{...f.props,isOpen:b,style:{...f.props?.style,zIndex:S},onClose:se.actionDispatcher?.createHandler({type:"click",handler:"closeModal"},se.currentDataContext)}},dataContext:se.currentDataContext,translationContext:se.translationContext,registry:se.registry,bindingEngine:se.bindingEngine,translationEngine:se.translationEngine,actionDispatcher:se.actionDispatcher,parentDataContext:T});return f.data_sources&&f.data_sources.length>0?Ye.createElement(ay,{key:`modal_${f.id}`,isOpen:b,modalId:f.id,dataSources:f.data_sources,dataContext:se.currentDataContext,globalStateUpdater:se.actionDispatcher?.getGlobalStateUpdater(),bindingEngine:se.bindingEngine,debug:Eo,children:L}):L}))])))))};e?.sync?(Ze.log("재렌더링 시작 (sync mode - 즉시 렌더링)"),d()):(Ze.log("재렌더링 시작 (with startTransition)"),N.startTransition(()=>{d()})),Ze.log("템플릿 데이터 업데이트 완료")}catch(a){throw Ze.error("템플릿 데이터 업데이트 실패",a),a}}function yc(){try{Ze.log("템플릿 정리 시작"),se.reactRoot&&(Ze.log("React Root 언마운트"),se.reactRoot.unmount(),se.reactRoot=null),se.templateId=null,se.locale="ko",se.isInitialized=!1,se.containerId=null,se.currentLayoutJson=null,se.currentDataContext={},se.translationContext={templateId:"",locale:"ko"},se.registry=null,se.bindingEngine=null,se.translationEngine=null,se.actionDispatcher=null,se.templateMetadata=null,Ze.log("템플릿 정리 완료")}catch(o){throw Ze.error("템플릿 정리 실패",o),o}}function Za(){return Object.freeze({...se})}function fy(){return se.actionDispatcher}const To={initTemplateEngine:Ao,renderTemplate:ls,updateTemplateData:cs,destroyTemplate:yc,getState:Za};typeof window<"u"&&(window.G7Core||(window.G7Core={}),window.G7Core.TemplateEngine=To,CA({getState:()=>({translationEngine:se.translationEngine,translationContext:se.translationContext,bindingEngine:se.bindingEngine,actionDispatcher:se.actionDispatcher,templateMetadata:se.templateMetadata}),transitionManager:Na,responsiveManager:ui,webSocketManager:hc}),Ze.log("전역 객체 window.G7Core.TemplateEngine에 노출됨"));const za=Object.freeze(Object.defineProperty({__proto__:null,DataSourceManager:va,LayoutLoader:tf,TemplateApp:So,TemplateEngine:To,default:To,destroyTemplate:yc,getActionDispatcher:fy,getState:Za,initTemplateApp:hf,initTemplateEngine:Ao,loadLayoutEditorBundle:gf,renderTemplate:ls,updateTemplateData:cs},Symbol.toStringTag,{value:"Module"}));Ft.DataSourceManager=va,Ft.LayoutLoader=tf,Ft.TemplateApp=So,Ft.TemplateEngine=To,Ft.default=To,Ft.destroyTemplate=yc,Ft.getActionDispatcher=fy,Ft.getState=Za,Ft.initTemplateApp=hf,Ft.initTemplateEngine=Ao,Ft.loadLayoutEditorBundle=gf,Ft.renderTemplate=ls,Ft.updateTemplateData=cs,Object.defineProperties(Ft,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})})(this.G7Core=this.G7Core||{}); + `)(n)}catch(r){B.warn(`Expression evaluation failed: ${e}`,r);return}}async executeInitActions(e,n={}){const{getActionDispatcher:r}=await Promise.resolve().then(()=>Ua),i=r();if(!i){B.warn("ActionDispatcher not available for init_actions");return}B.log("Executing init_actions:",e.map(d=>d.handler)),B.log("Init actions dataContext:",n),B.log("Init actions dataContext._global:",n._global);const l=e.map(d=>d.handler).filter(d=>d.includes("."));l.length>0&&await this.waitForHandlers(i,l);let u={...n};for(const d of e)try{const f={type:"click",handler:d.handler,target:d.target,params:d.params,resultTo:d.resultTo,onSuccess:d.onSuccess,onError:d.onError,if:d.if,conditions:d.conditions,auth_mode:d.auth_mode,auth_required:d.auth_required},g=i.createHandler(f,u),m=new Event("init");await g(m),B.log(`Init action executed: ${d.handler}`);const b=this.globalState;u={...u,_global:{...b},_local:b._local||u._local||{}},B.log(`Data context refreshed after ${d.handler}:`,{cartKey:u._global?.cartKey})}catch(f){B.error(`Failed to execute init action: ${d.handler}`,f)}}async waitForHandlers(e,n,r=5e3){const i=Date.now(),l=50,u=()=>n.every(f=>e.customHandlers?.has(f));if(u()){B.log("All module handlers already registered");return}const d=gf().getFailedJsAssets();if(d.length>0){const f=d.some(b=>b==="module"||b==="plugin"),g=n.filter(b=>!e.customHandlers?.has(b)),m=g.length>0&&g.every(b=>d.some(v=>b.startsWith(`${v}.`)));if(f||m){B.warn("Extension asset load failed — not waiting for handlers that will never register:",{pending:g,failedAssets:d});return}}return B.log("Waiting for module handlers:",n),new Promise(f=>{const g=()=>{if(u()){B.log("All module handlers now registered"),f();return}if(Date.now()-i>=r){const m=n.filter(b=>!e.customHandlers?.has(b));B.warn("Timeout waiting for handlers:",m),f();return}setTimeout(g,l)};g()})}};$(Ea,"LOCALE_STORAGE_KEY","g7_locale"),$(Ea,"CACHE_VERSION_STORAGE_KEY","g7_cache_version");let _o=Ea;function mf(o){const e=new _o(o);return o.websocket&&(mc.configure(o.websocket),B.log("WebSocket 설정 완료")),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{e.init(),window.__templateApp=e}):(e.init(),window.__templateApp=e),e}typeof window<"u"&&(window.G7Core=window.G7Core||{},window.G7Core.initTemplateApp=mf,window.G7Core.dataSource={refetch:async(o,e)=>{const n=window.__templateApp;if(!n){B.warn("TemplateApp not initialized (G7Core.dataSource.refetch)");return}return n.refetchDataSource(o,e)},get:o=>{const e=window.__templateApp;if(!e){B.warn("TemplateApp not initialized (G7Core.dataSource.get)");return}return e.getDataSource(o)}});function cA(o={}){const{checked:e,value:n,name:r,type:i="checkbox"}=o,u=n!==void 0?n:i==="checkbox"||i==="radio"?e??!1:String(e??""),d={checked:e??!1,value:u,name:r??"",type:i};return{target:d,currentTarget:d,preventDefault:()=>{},stopPropagation:()=>{},nativeEvent:new Event("change"),bubbles:!0,cancelable:!0,defaultPrevented:!1,eventPhase:Event.AT_TARGET,isTrusted:!1,timeStamp:Date.now(),type:"change",isDefaultPrevented:()=>!1,isPropagationStopped:()=>!1,persist:()=>{}}}function uA(o={}){const{button:e=0,clientX:n=0,clientY:r=0}=o;return{button:e,clientX:n,clientY:r,preventDefault:()=>{},stopPropagation:()=>{},nativeEvent:new MouseEvent("click"),bubbles:!0,cancelable:!0,defaultPrevented:!1,eventPhase:Event.AT_TARGET,isTrusted:!1,timeStamp:Date.now(),type:"click",isDefaultPrevented:()=>!1,isPropagationStopped:()=>!1,persist:()=>{},target:document.createElement("div"),currentTarget:document.createElement("div")}}function dA(){return{preventDefault:()=>{},stopPropagation:()=>{},nativeEvent:new Event("submit"),bubbles:!0,cancelable:!0,defaultPrevented:!1,eventPhase:Event.AT_TARGET,isTrusted:!1,timeStamp:Date.now(),type:"submit",isDefaultPrevented:()=>!1,isPropagationStopped:()=>!1,persist:()=>{},target:document.createElement("form"),currentTarget:document.createElement("form")}}function fA(o,e="keydown"){return{key:o,code:o.length===1?`Key${o.toUpperCase()}`:o,preventDefault:()=>{},stopPropagation:()=>{},nativeEvent:new KeyboardEvent(e,{key:o}),bubbles:!0,cancelable:!0,defaultPrevented:!1,eventPhase:Event.AT_TARGET,isTrusted:!1,timeStamp:Date.now(),type:e,isDefaultPrevented:()=>!1,isPropagationStopped:()=>!1,persist:()=>{},target:document.createElement("div"),currentTarget:document.createElement("div"),altKey:!1,ctrlKey:!1,metaKey:!1,shiftKey:!1,repeat:!1}}const hA={justify:/^justify-(start|end|center|between|around|evenly)$/,items:/^items-(start|end|center|baseline|stretch)$/,content:/^content-(start|end|center|between|around|evenly|stretch)$/,self:/^self-(auto|start|end|center|stretch|baseline)$/,flex:/^flex-(row|row-reverse|col|col-reverse|wrap|wrap-reverse|nowrap|1|auto|initial|none)$/,grow:/^(grow|grow-0)$/,shrink:/^(shrink|shrink-0)$/,basis:/^basis-/,order:/^(order-|-)order-/,gap:/^gap(-x|-y)?-/,gridCols:/^grid-cols-/,gridRows:/^grid-rows-/,colSpan:/^col-(span-|start-|end-)/,rowSpan:/^row-(span-|start-|end-)/,display:/^(block|inline-block|inline|flex|inline-flex|table|inline-table|table-caption|table-cell|table-column|table-column-group|table-footer-group|table-header-group|table-row-group|table-row|flow-root|grid|inline-grid|contents|list-item|hidden)$/,position:/^(static|fixed|absolute|relative|sticky)$/,inset:/^(inset|top|right|bottom|left)-/,zIndex:/^z-/,width:/^w-/,minWidth:/^min-w-/,maxWidth:/^max-w-/,height:/^h-/,minHeight:/^min-h-/,maxHeight:/^max-h-/,padding:/^p[xytblr]?-/,margin:/^-?m[xytblr]?-/,space:/^space-(x|y)-/,fontSize:/^text-(xs|sm|base|lg|xl|2xl|3xl|4xl|5xl|6xl|7xl|8xl|9xl)$/,fontWeight:/^font-(thin|extralight|light|normal|medium|semibold|bold|extrabold|black)$/,fontStyle:/^(italic|not-italic)$/,fontFamily:/^font-(sans|serif|mono)/,textAlign:/^text-(left|center|right|justify|start|end)$/,textColor:/^text-(inherit|current|transparent|black|white|slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-/,textDecoration:/^(underline|overline|line-through|no-underline)$/,textTransform:/^(uppercase|lowercase|capitalize|normal-case)$/,lineHeight:/^leading-/,letterSpacing:/^tracking-/,textOverflow:/^(truncate|text-ellipsis|text-clip)$/,whitespace:/^whitespace-/,wordBreak:/^break-/,bgColor:/^bg-(inherit|current|transparent|black|white|slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-/,bgGradient:/^bg-gradient-/,bgSize:/^bg-(auto|cover|contain)$/,bgPosition:/^bg-(bottom|center|left|left-bottom|left-top|right|right-bottom|right-top|top)$/,bgRepeat:/^bg-(repeat|no-repeat|repeat-x|repeat-y|repeat-round|repeat-space)$/,bgAttachment:/^bg-(fixed|local|scroll)$/,bgClip:/^bg-clip-/,bgOrigin:/^bg-origin-/,borderWidth:/^border(-[xytblr])?(-0|-2|-4|-8)?$/,borderColor:/^border-(inherit|current|transparent|black|white|slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-/,borderStyle:/^border-(solid|dashed|dotted|double|hidden|none)$/,borderRadius:/^rounded(-[tblrse]{1,2})?(-none|-sm|-md|-lg|-xl|-2xl|-3xl|-full)?$/,ringWidth:/^ring(-0|-1|-2|-4|-8|-inset)?$/,ringColor:/^ring-(inherit|current|transparent|black|white|slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-/,ringOffset:/^ring-offset-/,shadow:/^shadow(-sm|-md|-lg|-xl|-2xl|-inner|-none)?$/,opacity:/^opacity-/,mixBlend:/^mix-blend-/,bgBlend:/^bg-blend-/,blur:/^blur(-none|-sm|-md|-lg|-xl|-2xl|-3xl)?$/,brightness:/^brightness-/,contrast:/^contrast-/,grayscale:/^grayscale(-0)?$/,hueRotate:/^-?hue-rotate-/,invert:/^invert(-0)?$/,saturate:/^saturate-/,sepia:/^sepia(-0)?$/,backdropBlur:/^backdrop-blur-/,backdropBrightness:/^backdrop-brightness-/,backdropContrast:/^backdrop-contrast-/,backdropGrayscale:/^backdrop-grayscale-/,backdropHueRotate:/^backdrop-hue-rotate-/,backdropInvert:/^backdrop-invert-/,backdropOpacity:/^backdrop-opacity-/,backdropSaturate:/^backdrop-saturate-/,backdropSepia:/^backdrop-sepia-/,scale:/^scale(-x|-y)?-/,rotate:/^-?rotate-/,translate:/^-?translate-[xy]-/,skew:/^-?skew-[xy]-/,transformOrigin:/^origin-/,transition:/^transition(-none|-all|-colors|-opacity|-shadow|-transform)?$/,duration:/^duration-/,ease:/^ease-(linear|in|out|in-out)$/,delay:/^delay-/,animate:/^animate-/,cursor:/^cursor-/,userSelect:/^select-/,pointerEvents:/^pointer-events-/,resize:/^resize(-none|-x|-y)?$/,scrollBehavior:/^scroll-(auto|smooth)$/,touchAction:/^touch-/,overflow:/^overflow(-x|-y)?-(auto|hidden|clip|visible|scroll)$/,overscroll:/^overscroll(-x|-y)?-(auto|contain|none)$/,visibility:/^(visible|invisible|collapse)$/,aspectRatio:/^aspect-/,columns:/^columns-/,breakAfter:/^break-after-/,breakBefore:/^break-before-/,breakInside:/^break-inside-/,boxDecorationBreak:/^box-decoration-/,boxSizing:/^box-(border|content)$/,float:/^float-(right|left|none)$/,clear:/^clear-(left|right|both|none)$/,isolation:/^(isolate|isolation-auto)$/,objectFit:/^object-(contain|cover|fill|none|scale-down)$/,objectPosition:/^object-/};function py(o){const e=o.replace(/^(dark:|hover:|focus:|active:|disabled:|group-hover:|sm:|md:|lg:|xl:|2xl:)+/,"");for(const[n,r]of Object.entries(hA))if(r.test(e))return n;return null}function my(o){const e=o.match(/^((dark:|hover:|focus:|active:|disabled:|group-hover:|sm:|md:|lg:|xl:|2xl:)+)/);return e?e[1]:""}function gA(o,e){if(!e||e.trim()==="")return o;if(!o||o.trim()==="")return e;const n=o.split(/\s+/).filter(Boolean),r=e.split(/\s+/).filter(Boolean),i=new Map;for(const u of r){const d=py(u);if(d){const f=my(u),g=`${d}:${f}`;i.set(g,u)}}return[...n.filter(u=>{const d=py(u);if(!d)return!0;const f=my(u),g=`${d}:${f}`;return!i.has(g)}),...r].join(" ")}function pA(o){return Object.entries(o).filter(([,e])=>e).map(([e])=>e).join(" ")}function mA(...o){return o.filter(e=>typeof e=="string"&&e.length>0).join(" ")}const Se=dt("G7CoreGlobals");function yA(){window.React=Xe,window.ReactDOM={...nd,createPortal:Ar.createPortal,unstable_batchedUpdates:o=>o()},window.ReactJSXRuntime=hC,Se.log("전역 객체 window.React, window.ReactDOM, window.ReactJSXRuntime에 노출됨")}function bA(o){const e=new Map,n=Tr.getInstance();o.componentEvent={on:(r,i)=>(e.has(r)||e.set(r,new Set),e.get(r).add(i),n.trackEventSubscribe(r),()=>{e.get(r)?.delete(i),n.trackEventUnsubscribe(r)}),emit:async(r,i)=>{const l=e.get(r),u=l?.size??0;if(!l||l.size===0)return n.trackEventEmit(r,i,0),[];let d,f=[];try{f=await Promise.all(Array.from(l).map(async g=>{try{return await g(i)}catch(m){throw Se.error(`componentEvent: Error in listener for "${r}":`,m),m}}))}catch(g){d=g instanceof Error?g:new Error(String(g))}if(n.trackEventEmit(r,i,u,f,d),d)throw d;return f},off:r=>{e.delete(r),n.trackEventOff(r)},clear:()=>{e.clear(),n.trackEventClear()}},Se.log("전역 객체 window.G7Core.componentEvent에 노출됨")}function vA(o){o.__runtime||(o.__runtime={DynamicRenderer:ja,ComponentRegistry:fa,TranslationEngine:Er,DataSourceManager:Sa,dataSourceManager:Q_,DataBindingEngine:Rn,dataBindingEngine:aw,ActionDispatcher:fo,TranslationReactContext:of,TranslationProvider:hc,useTranslation:ty,ResponsiveContext:Hd,ResponsiveProvider:ec,useResponsive:zd,responsiveManager:ui,BREAKPOINT_PRESETS:$l,AuthManager:ga,createLogger:dt,G7DevToolsCore:Tr},Se.log("전역 객체 window.G7Core.__runtime(코어 런타임 표면)에 노출됨"))}function SA(o){if(o.layoutEditor&&o.layoutEditor.__isStub!==!0||o.layoutEditor&&o.layoutEditor.__isStub===!0)return;const e=[],n=[];o.layoutEditor={__isStub:!0,__queue:e,__readyCallbacks:n,registerWidget:(r,i)=>e.push(["widget",r,i]),registerNodeEditor:(r,i)=>e.push(["nodeEditor",r,i]),registerCanvasOverlay:(r,i)=>e.push(["canvasOverlay",r,i]),onReady:r=>{typeof r=="function"&&n.push(r)}},Se.log("전역 객체 window.G7Core.layoutEditor 예약 접수함(stub) 노출됨")}function wA(o,e){o.useTranslation=ty,o.t=(n,r)=>{const i=e.getState();if(!i.translationEngine||!i.translationContext)return n;if(r){const l="|"+Object.entries(r).map(([u,d])=>`${u}=${d}`).join("|");return i.translationEngine.translate(n,i.translationContext,l)}return i.translationEngine.translate(n,i.translationContext)},Se.log("전역 객체 window.G7Core.useTranslation에 노출됨")}function CA(o,e){o.createChangeEvent=cA,o.createClickEvent=uA,o.createSubmitEvent=dA,o.createKeyboardEvent=fA,o.uuid=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{const r=Math.random()*16|0;return(n==="x"?r:r&3|8).toString(16)}),o.createLogger=dt,Se.log("전역 객체 window.G7Core.createLogger에 노출됨"),o.renderItemChildren=(n,r,i,l,u)=>{const d=e.getState(),m={_global:window.__templateApp?.getGlobalState?.()||{},_local:r._local||{},_computed:r._computed||{},...r},b=new Set,v=(_,x)=>{const k=m._global?._remountKeys;return _&&k?.[_]&&!b.has(_)?(b.add(_),`${_}-remount-${k[_]}`):_||x},S={translationContext:d.translationContext,translationEngine:d.translationEngine,bindingEngine:d.bindingEngine,actionDispatcher:d.actionDispatcher,getRemountKey:v,...u};return no(n,m,i,l,S)},o.getComponentMap=()=>fa.getInstance().getComponentMap(),o.renderComponentLayout=(n,r,i)=>{if(!n||!Array.isArray(n)||n.length===0)return null;const l=fa.getInstance().getComponentMap(),u=e.getState(),f=window.__templateApp?.getGlobalState?.()||{},g={_global:f._global||{},_local:f._local||{},_computed:f._computed||{},...r},m=new Set,b=(v,S)=>{const _=g._global?._remountKeys;return v&&_?.[v]&&!m.has(v)?(m.add(v),`${v}-remount-${_[v]}`):v||S};return no(n,g,l,i,{translationContext:u.translationContext,translationEngine:u.translationEngine,bindingEngine:u.bindingEngine,actionDispatcher:u.actionDispatcher,getRemountKey:b})},o.renderExpandContent=n=>{const{children:r,row:i,expandContext:l,componentContext:u,keyPrefix:d}=n;if(!r||!Array.isArray(r)||r.length===0)return null;const f=n.componentMap||fa.getInstance().getComponentMap(),g=e.getState(),m=o.state?.get?.()||{},b=u?.stateRef?.current??u?.state??{},v={...m._local||{},...b},S=u?.computedRef?.current??m._computed??{},_=g.bindingEngine??o.getDataBindingEngine?.(),x={...m,_local:v,_computed:S,row:i,item:i,$item:i};let k={};if(l&&typeof l=="object"&&_)try{for(const[D,j]of Object.entries(l))if(typeof j=="string"){const H=j.match(/^\{\{([^}]+)\}\}$/);if(H){const P=H[1].trim();try{k[D]=_.evaluateExpression(P,x,{skipCache:!0})}catch{k[D]=void 0}}else k[D]=_.resolveBindings(j,x,{skipCache:!0})}else k[D]=j}catch(D){Se.warn("renderExpandContent: expandContext 평가 오류:",D)}const O={row:i,item:i,$item:i,_local:v,_global:m._global||{},_computed:m._computed||{},...k},M=new Set,T=(D,j)=>{const H=O._global?._remountKeys;return D&&H?.[D]&&!M.has(D)?(M.add(D),`${D}-remount-${H[D]}`):D||j};return no(r,O,f,d,{translationContext:g.translationContext,translationEngine:g.translationEngine??void 0,bindingEngine:g.bindingEngine??void 0,actionDispatcher:g.actionDispatcher,componentContext:u,getRemountKey:T})},o.$get=function(r,i,l=void 0){if(r==null)return l;const u=Array.isArray(i)?i:[i];if(u.length===0)return r;let d=r;for(const f of u){if(d==null||f==null)return l;d=d[f]}return d??l},Se.log("전역 객체 window.G7Core.renderItemChildren에 노출됨"),Se.log("전역 객체 window.G7Core.renderComponentLayout에 노출됨"),Se.log("전역 객체 window.G7Core.renderExpandContent에 노출됨"),Se.log("전역 객체 window.G7Core.$get에 노출됨")}function EA(o){o.dispatch=async(e,n)=>{const r=window.__templateApp;if(!r)return Se.warn("G7Core.dispatch: TemplateApp이 초기화되지 않았습니다."),{success:!1,error:new Error("TemplateApp이 초기화되지 않았습니다.")};const i=r.getActionDispatcher?.();if(!i)return Se.warn("G7Core.dispatch: ActionDispatcher를 찾을 수 없습니다."),{success:!1,error:new Error("ActionDispatcher를 찾을 수 없습니다.")};const l=r.getRouter?.(),u=r.getGlobalState?.(),d=r.setGlobalState?.bind(r),g=n?.componentContext||window.__g7ActionContext,m=window.__g7PendingLocalState;let b=g?.state??u;m&&g&&(b=m,Se.log("[dispatch] Using __g7PendingLocalState for context.state:",m));let v=g?.data??u;m&&g?.data?._local&&(v={...g.data,_local:m},Se.log("[dispatch] Updated context.data._local with pendingLocalState"));const S={navigate:l?(_,x)=>l.navigate(_,x):void 0,setState:g?.setState??d,state:b,data:v,_isDispatchFallbackContext:!g?.setState};if(e.debounce){const _=e.debounceKey||`dispatch-${e.handler}`,x=typeof e.debounce=="number"?e.debounce:e.debounce.delay;return i.debouncedCall(_,x,()=>{const{debounce:k,debounceKey:O,...M}=e;i.dispatchAction(M,S)}),{success:!0,debounced:!0}}try{return await i.dispatchAction(e,S)}catch(_){return Se.error("G7Core.dispatch: 액션 실행 오류:",_),{success:!1,error:_ instanceof Error?_:new Error(String(_))}}},Se.log("전역 객체 window.G7Core.dispatch에 노출됨")}function Ao(o){const e={};for(const[n,r]of Object.entries(o))if(n.includes(".")){const i=n.split(".");let l=e;for(let u=0;u0&&e.every(n=>/^\d+$/.test(n))}function by(o,e){const n={...o};for(const r of Object.keys(e))r in n?n[r]!==null&&typeof n[r]=="object"&&!Array.isArray(n[r])&&e[r]!==null&&typeof e[r]=="object"&&!Array.isArray(e[r])&&(n[r]=by(n[r],e[r])):n[r]=e[r];return n}function ta(o,e){if(Array.isArray(o)&&!Array.isArray(e)&&_A(e)){const r=Object.keys(e).map(l=>parseInt(l,10));if(!((r.length>0?Math.max(...r):0)>=o.length+r.length+10)){const l=[...o];for(const[u,d]of Object.entries(e)){const f=parseInt(u,10);f>=0&&f=l.length&&(l[f]=d)}return l}}const n={...o};for(const[r,i]of Object.entries(e))i!==null&&typeof i=="object"&&!Array.isArray(i)?n[r]!==null&&typeof n[r]=="object"?n[r]=ta(n[r],i):n[r]={...i}:n[r]=i;return n}function AA(o){o.state={get:()=>window.__templateApp?.getGlobalState?.()||{},set:(e,n)=>{const r=window.__templateApp;if(r?.setGlobalState&&r?.getGlobalState){const i=n?.merge||"deep",l=Ao(e);let u;if(i==="replace")u=l;else if(i==="shallow")u={...r.getGlobalState(),...l};else{const d=r.getGlobalState();u=ta(d,l)}r.setGlobalState(u,{render:n?.render})}else Se.warn("G7Core.state.set: TemplateApp이 초기화되지 않았습니다.")},setLocal:(e,n)=>{const r=window.__templateApp;if(n?.render===!1&&!n?.selfManaged){const k=window.__g7AutoBindingPaths;k&&k.size>0&&yy(Ao(e)).some(M=>k.has(M))&&(Se.log("[setLocal] render:false + 자동바인딩 경로 겹침 감지 → render:true 자동 승격 (engine-v1.43.0)"),n={...n,render:!0})}if(n?.debounce){const k=r?.getActionDispatcher?.();if(k){const O=n.debounceKey||`setLocal-${Object.keys(e).join(",")}`,{debounce:M,debounceKey:T,...D}=n;k.debouncedCall(O,n.debounce,()=>{o.state.setLocal(e,D)});return}}const i=n?.scope??"current",l=n?.merge||"deep",u=window.__g7ActionContext,d=Ao(e);if(i==="parent"||i==="root"){const k=window.__g7LayoutContextStack||[];if(k.length>0){const O=i==="parent"?k[k.length-1]:k[0];if(O?.setState){O.setState(M=>l==="replace"?d:l==="shallow"?{...M||{},...d}:ta(M||{},d)),Se.log(`[setLocal] scope=${i}: 타겟 컨텍스트에 상태 업데이트 (mergeMode=${l})`,d);return}}Se.warn(`[setLocal] scope=${i}: 레이아웃 컨텍스트 스택이 비어있습니다. current로 폴백합니다.`)}const f=window.__g7PendingLocalState,g=r?.getGlobalState?.()?._local||{},v=!((window.__g7LayoutContextStack||[]).length>0)&&u?.state?u.state:void 0,S=v?by(g,v):g,_=f||S;let x;if(l==="replace"?x=d:l==="shallow"?x={..._,...d}:x=ta(_,d),r?.setGlobalState&&(r.setGlobalState({_local:x},{render:n?.render}),Se.log(`[setLocal] globalLocal updated via setGlobalState (mergeMode=${l}, render=${n?.render??!0}):`,d)),window.__g7PendingLocalState=x,Se.log("[setLocal] __g7PendingLocalState updated:",x),window.__g7SequenceLocalSync=x,window.__g7LastSetLocalSnapshot=x,l==="replace")window.__g7ForcedLocalFields=d;else{const k=window.__g7ForcedLocalFields||{};window.__g7ForcedLocalFields=ta(k,d)}if(Se.log("[setLocal] __g7ForcedLocalFields updated:",d),l==="replace")window.__g7SetLocalOverrideKeys=d;else{const k=window.__g7SetLocalOverrideKeys||{};window.__g7SetLocalOverrideKeys=ta(k,d)}Se.log("[setLocal] __g7SetLocalOverrideKeys updated:",d),u?.setState&&u.setState(k=>l==="replace"?d:l==="shallow"?{...k||{},...d}:ta(k||{},d)),r?.setGlobalState||Se.warn("G7Core.state.setLocal: TemplateApp이 없습니다.")},getLocal:()=>{const r=(window.__templateApp?.getGlobalState?.()||{})._local||{},i=window.__g7PendingLocalState;if(i)return ta(r,i);const l=window.__g7LastSetLocalSnapshot;return l&&l!==r?ta(r,l):r},update:e=>{const n=window.__templateApp;if(n?.getGlobalState&&n?.setGlobalState){const r=n.getGlobalState(),i=e(r);n.setGlobalState(i)}else Se.warn("G7Core.state.update: TemplateApp이 초기화되지 않았습니다.")},subscribe:e=>{const n=window.__templateApp;return n?.onGlobalStateChange?n.onGlobalStateChange(e):(Se.warn("G7Core.state.subscribe: TemplateApp이 초기화되지 않았습니다."),()=>{})},getDataSource:e=>window.__templateApp?.getDataSource?.(e),getIsolated:e=>e?window.__g7IsolatedStates?.[e]?.state??null:window.__g7ActionContext?.isolatedContext?.state??null,setIsolated:(e,n,r)=>{let i,l,u;typeof e=="string"?(i=e,l=n||{},u=r):(l=e,u=n&&typeof n=="object"&&"merge"in n?n:r);const d=u?.merge||"deep",f=Ao(l);if(i){const b=window.__g7IsolatedStates?.[i];b?.mergeState?b.mergeState(f,d):Se.warn(`G7Core.state.setIsolated: scopeId '${i}'를 찾을 수 없습니다.`);return}const g=window.__g7ActionContext;g?.isolatedContext?.mergeState?g.isolatedContext.mergeState(f,d):Se.warn("G7Core.state.setIsolated: 액션 컨텍스트에 isolatedContext가 없습니다.")},getParent:()=>{const e=window.__g7LayoutContextStack||[];if(e.length===0)return Se.log("[getParent] 레이아웃 컨텍스트 스택이 비어있습니다."),null;const n=e[e.length-1];if(!n)return null;const r=n.dataContext||{};return{_local:n.state||r._local||{},_global:r._global||o.state.get()||{},setState:n.setState}},setParentLocal:(e,n,r)=>{const i=window.__g7LayoutContextStack||[];if(i.length===0){Se.warn("[setParentLocal] 레이아웃 컨텍스트 스택이 비어있습니다.");return}const l=i[i.length-1];if(!l?.setState){Se.warn("[setParentLocal] 부모 컨텍스트에 setState가 없습니다.");return}let u,d;typeof e=="string"?(u={[e]:n},d=r):(u=e,d=n&&typeof n=="object"&&"merge"in n?n:r);const f=d?.merge||"deep",g=Ao(u),m=l.state?._local!==void 0,b=m?l.state._local:l.state||{};let v;f==="replace"?v=g:f==="shallow"?v={...b,...g}:v=ta(b,g),window.__g7PendingLocalState=v;const S=window.__templateApp;if(S?.setGlobalState&&S.setGlobalState({_local:v}),l.setState(v),m?l.state._local=v:l.state=v,l.dataContext&&(l.dataContext._local=v),f==="replace")window.__g7ForcedLocalFields=g;else{const _=window.__g7ForcedLocalFields||{};window.__g7ForcedLocalFields=ta(_,g)}$d()},setParentGlobal:(e,n)=>{let r;typeof e=="string"?r={[e]:n}:r=e,o.state.set(r),Se.log("[setParentGlobal] 전역 상태 업데이트:",r)}},window.__g7IsolatedStates||(window.__g7IsolatedStates={}),o.state.getGlobal=o.state.get,o.state.setGlobal=o.state.set,Se.log("전역 객체 window.G7Core.state에 노출됨")}function xA(o){o.dataSource={get:e=>window.__templateApp?.getDataSource?.(e),set:(e,n,r)=>{const i=window.__templateApp;i?.setDataSource?i.setDataSource(e,n,r):Se.warn("G7Core.dataSource.set: TemplateApp이 초기화되지 않았습니다.")},refetch:async(e,n)=>{const r=window.__templateApp;if(r?.refetchDataSource)return r.refetchDataSource(e,n);Se.warn("G7Core.dataSource.refetch: TemplateApp이 초기화되지 않았습니다.")},updateItem:(e,n,r,i,l)=>{const u=window.__templateApp;return u?.updateDataSourceItem?u.updateDataSourceItem(e,n,r,i,l):(Se.warn("G7Core.dataSource.updateItem: TemplateApp이 초기화되지 않았습니다."),!1)},updateData:(e,n,r,i="append")=>{const l=window.__templateApp;if(!l?.getDataSource||!l?.setDataSource)return Se.warn("G7Core.dataSource.updateData: TemplateApp이 초기화되지 않았습니다."),!1;const u=l.getDataSource(e);if(!u)return Se.warn(`G7Core.dataSource.updateData: 데이터 소스 '${e}'를 찾을 수 없습니다.`),!1;let d,f=u,g=null;if(n){const b=n.split(".");g=b.pop();for(const v of b)if(f&&typeof f=="object"&&v in f)f=f[v];else return Se.warn(`G7Core.dataSource.updateData: 경로 '${n}'를 찾을 수 없습니다.`),!1;d=f[g]}else d=u;if(!Array.isArray(d))return Se.warn("G7Core.dataSource.updateData: 대상 경로의 데이터가 배열이 아닙니다."),!1;if(!Array.isArray(r))return Se.warn("G7Core.dataSource.updateData: newData가 배열이 아닙니다."),!1;const m=i==="prepend"?[...r,...d]:[...d,...r];return n&&g?(f[g]=m,l.setDataSource(e,u,{merge:!1})):l.setDataSource(e,m,{merge:!1}),Se.log(`G7Core.dataSource.updateData: '${e}'에 ${r.length}개 항목 ${i==="prepend"?"앞에":"뒤에"} 추가됨`),!0}},Se.log("전역 객체 window.G7Core.dataSource에 노출됨")}function TA(o,e){o.locale={current:()=>window.__templateApp?.getLocale?.()||"ko",supported:()=>{const r=window.__templateApp?.globalState?.appConfig?.supportedLocales;return Array.isArray(r)&&r.length>0?r:e.getState().templateMetadata?.locales||["ko","en"]},change:async n=>{const r=window.__templateApp;r?.changeLocale?await r.changeLocale(n):Se.warn("G7Core.locale.change: TemplateApp이 초기화되지 않았습니다.")}},Se.log("전역 객체 window.G7Core.locale에 노출됨")}function RA(o){o.toast={show:(e,n)=>{o.dispatch({handler:"toast",params:{message:e,type:n?.type||"info",...n?.duration&&{duration:n.duration}}})},success:(e,n)=>{o.toast.show(e,{type:"success",duration:n})},error:(e,n)=>{o.toast.show(e,{type:"error",duration:n})},warning:(e,n)=>{o.toast.show(e,{type:"warning",duration:n})},info:(e,n)=>{o.toast.show(e,{type:"info",duration:n})}},Se.log("전역 객체 window.G7Core.toast에 노출됨")}function kA(o){o.modal={open:e=>{o.dispatch({handler:"openModal",target:e})},close:e=>{o.dispatch({handler:"closeModal",...e&&{target:e}})},closeAll:()=>{o.dispatch({handler:"closeAllModals"})},isOpen:e=>{const n=o.state.get();return n._global?.activeModal===e||n._global?.modalStack?.includes(e)||!1},getStack:()=>o.state.get()._global?.modalStack||[]},Se.log("전역 객체 window.G7Core.modal에 노출됨")}function DA(o){o.style={mergeClasses:gA,conditionalClass:pA,joinClasses:mA},Se.log("전역 객체 window.G7Core.style에 노출됨")}function OA(o,e){const{webSocketManager:n}=e;o.websocket={manager:n,subscribe:(r,i,l,u)=>n.subscribe(r,i,l,u),unsubscribe:r=>n.unsubscribe(r),leaveChannel:r=>n.leaveChannel(r),disconnect:()=>n.disconnect(),isInitialized:()=>n.isInitialized(),getSubscriptionCount:()=>n.getSubscriptionCount()},Se.log("전역 객체 window.G7Core.websocket에 노출됨")}function LA(o,e){const{transitionManager:n}=e;o.navigation={isPending:()=>n?.getIsPending?.()||!1,onComplete:r=>{if(!n)return r(),()=>{};let i=n.getIsPending();const l=n.subscribe(u=>{u?i=!0:i&&(r(),l())});return l}},Se.log("전역 객체 window.G7Core.navigation에 노출됨")}function MA(o){o.plugin={getSettings:e=>window.G7Config?.plugins?.[e],get:(e,n,r)=>window.G7Config?.plugins?.[e]?.[n]??r,getAll:()=>window.G7Config?.plugins??{}},Se.log("전역 객체 window.G7Core.plugin에 노출됨")}function $A(o){o.module={getSettings:e=>window.G7Config?.modules?.[e],get:(e,n,r)=>window.G7Config?.modules?.[e]?.[n]??r,getAll:()=>window.G7Config?.modules??{}},Se.log("전역 객체 window.G7Core.module에 노출됨")}function NA(o,e){const{transitionManager:n,responsiveManager:r}=e;o.AuthManager=ga,o.api=Ia(),o.TransitionManager=n,o.useTransitionState=dm,o.ResponsiveManager=r,o.useResponsive=zd,o.useControllableState=_C,o.shallowArrayEqual=AC,o.shallowObjectEqual=hm,o.updateQueryParams=async(i,l)=>{const u=window.__templateApp;if(u?.updateQueryParams)return u.updateQueryParams(i,l);Se.warn("G7Core.updateQueryParams: TemplateApp이 초기화되지 않았습니다.")},Se.log("전역 객체 window.G7Core.AuthManager에 노출됨"),Se.log("전역 객체 window.G7Core.api에 노출됨"),Se.log("전역 객체 window.G7Core.ResponsiveManager에 노출됨"),Se.log("전역 객체 window.G7Core.useResponsive에 노출됨"),Se.log("전역 객체 window.G7Core.useControllableState에 노출됨"),Se.log("전역 객체 window.G7Core.updateQueryParams에 노출됨")}function IA(o,e){o.getSlotContext=()=>window.__slotContextValue??null,o.getDynamicRenderer=()=>window.__DynamicRenderer??null,o.getComponentRegistry=()=>e.getComponentRegistry?.()??fa.getInstance(),o.getDataBindingEngine=()=>e.getDataBindingEngine?.()??e.getState().bindingEngine,o.getTranslationEngine=()=>e.getTranslationEngine?.()??e.getState().translationEngine,o.getActionDispatcher=()=>e.getActionDispatcher?.()??e.getState().actionDispatcher,Se.log("전역 객체 window.G7Core 슬롯 API에 노출됨 (getSlotContext, getDynamicRenderer 등)")}function HA(o){o.identity={setLauncher:wt.setLauncher.bind(wt),handle:wt.handle.bind(wt),isIdentityRequired:wt.isIdentityRequired.bind(wt),hasLauncher:wt.hasLauncher.bind(wt),markDomainNoticeShown:wt.markDomainNoticeShown.bind(wt),redirectExternally:wt.redirectExternally.bind(wt),createDeferred:wt.createDeferred.bind(wt),resolveDeferred:wt.resolveDeferred.bind(wt),reset:wt.reset.bind(wt),redirectStashKey:Rd},Se.log("전역 객체 window.G7Core 본인인증(IDV) API에 노출됨 (identity)")}function zA(o){if(typeof window>"u")return;yA(),window.G7Core||(window.G7Core={});const e=window.G7Core;vA(e),bA(e),SA(e),NA(e,o),wA(e,o),CA(e,o),EA(e),AA(e),xA(e),TA(e,o),RA(e),kA(e),DA(e),OA(e,o),LA(e,o),MA(e),$A(e),IA(e,o),HA(e),Se.log("G7Core 전역 객체 초기화 완료")}function jA(){const o=window.G7Core;if(!o){Se.warn("G7Core가 초기화되지 않았습니다.");return}const e=()=>Tr.getInstance(),n={isEnabled:()=>{try{return e().isEnabled()}catch{return!1}},trackRender:r=>{try{e().isEnabled()&&e().trackRender(r)}catch{}},trackIteration:(r,i,l,u,d)=>{try{e().isEnabled()&&e().trackIteration(r,{source:i,itemVar:l,indexVar:u,sourceLength:d})}catch{}},trackIfCondition:(r,i,l,u)=>{try{e().isEnabled()&&e().trackIfCondition(r,i,l)}catch{}},trackMount:(r,i)=>{try{e().isEnabled()&&e().trackMount(r,{...i,id:r})}catch{}},trackUnmount:r=>{try{e().isEnabled()&&e().trackUnmount(r)}catch{}},trackExpressionEval:r=>{try{e().isEnabled()&&e().trackExpressionEval(r)}catch{}},trackBindingEval:r=>{try{e().isEnabled()&&e().trackBindingEval(r)}catch{}},recordCacheHit:()=>{try{e().isEnabled()&&e().recordCacheHit()}catch{}},recordCacheMiss:()=>{try{e().isEnabled()&&e().recordCacheMiss()}catch{}},trackHandlerRegistration:(r,i,l,u)=>{try{e().isEnabled()&&e().trackHandlerRegistration(r,i,l,u)}catch{}},trackHandlerUnregistration:r=>{try{e().isEnabled()&&e().trackHandlerUnregistration(r)}catch{}},logAction:r=>{try{e().isEnabled()&&e().logAction(r)}catch{}},trackRequest:(r,i)=>{try{return e().isEnabled()?e().trackRequest(r,i):""}catch{return""}},completeRequest:(r,i,l)=>{try{e().isEnabled()&&e().completeRequest(r,i,l)}catch{}},failRequest:(r,i)=>{try{e().isEnabled()&&e().failRequest(r,i)}catch{}},trackDataSourceDefinition:r=>{try{e().isEnabled()&&e().trackDataSourceDefinition(r)}catch{}},trackDataSourceLoading:r=>{try{e().isEnabled()&&e().trackDataSourceLoading(r)}catch{}},trackDataSourceLoaded:(r,i,l)=>{try{e().isEnabled()&&e().trackDataSourceLoaded(r,i,l)}catch{}},trackDataSourceError:(r,i)=>{try{e().isEnabled()&&e().trackDataSourceError(r,i)}catch{}},trackForm:(r,i,l)=>{try{e().isEnabled()&&e().trackForm(r,i,l)}catch{}},untrackForm:r=>{try{e().isEnabled()&&e().untrackForm(r)}catch{}},startStateChange:(r,i,l,u)=>{try{return e().isEnabled()?e().startStateChange(r,i,l,u):""}catch{return""}},completeStateChange:r=>{try{e().isEnabled()&&e().completeStateChange(r)}catch{}},trackComponentRender:(r,i,l,u,d,f)=>{try{e().isEnabled()&&e().trackComponentRender(r,i,l,u,d,f)}catch{}},updateLocalState:r=>{try{e().isEnabled()&&e().updateLocalState(r)}catch{}},updateComputedState:r=>{try{e().isEnabled()&&e().updateComputedState(r)}catch{}},updateParentContext:r=>{try{e().isEnabled()&&e().updateParentContext(r)}catch{}},trackComponentStateSource:(r,i,l,u)=>{try{e().isEnabled()&&e().trackComponentStateSource(r,i,l,u)}catch{}},trackDynamicState:(r,i)=>{try{e().isEnabled()&&e().trackDynamicState(r,i)}catch{}},trackContextFlow:(r,i,l,u,d,f)=>{try{e().isEnabled()&&e().trackContextFlow(r,i,l,u,d,f)}catch{}},trackComponentStyle:(r,i,l,u)=>{try{e().isEnabled()&&e().trackComponentStyle(r,i,l,u)}catch{}},trackAuthEvent:(r,i,l,u)=>{try{e().isEnabled()&&e().trackAuthEvent(r,i,l,u)}catch{}},trackAuthHeader:(r,i,l,u,d)=>{try{e().isEnabled()&&e().trackAuthHeader(r,i,l,u,d)}catch{}},trackLog:(r,i,l)=>{try{e().isEnabled()&&e().trackLog(r,i,l)}catch{}},trackAction:r=>{try{e().isEnabled()&&e().trackAction?.(r)}catch{}},trackDataSourceUpdate:r=>{try{e().isEnabled()&&e().trackDataSourceUpdate?.(r)}catch{}},startSequenceExecution:r=>{try{return e().isEnabled()?e().startSequenceExecution(r):""}catch{return""}},captureSequenceActionBefore:(r,i,l,u,d)=>{try{e().isEnabled()&&e().captureSequenceActionBefore(r,i,l,u,d)}catch{}},captureSequenceActionAfter:(r,i,l,u,d,f)=>{try{e().isEnabled()&&e().captureSequenceActionAfter(r,i,l,u,d,f)}catch{}},endSequenceExecution:(r,i)=>{try{e().isEnabled()&&e().endSequenceExecution(r,i)}catch{}},registerStateCaptureForHandler:(r,i,l)=>{try{e().isEnabled()&&e().registerStateCaptureForHandler(r,i,l)}catch{}},detectStaleClosure:(r,i,l,u,d)=>{try{return e().isEnabled()?e().detectStaleClosure(r,i,l,u,d):[]}catch{return[]}},trackStaleClosureWarning:r=>{try{e().isEnabled()&&e().trackStaleClosureWarning(r)}catch{}},trackModalOpen:r=>{try{e().isEnabled()&&e().trackModalOpen(r)}catch{}},trackModalClose:(r,i)=>{try{e().isEnabled()&&e().trackModalClose(r,i)}catch{}},trackModalStateChange:r=>{try{e().isEnabled()&&e().trackModalStateChange(r)}catch{}},trackNestedContext:r=>{try{return e().isEnabled()?e().trackNestedContext(r):""}catch{return""}},trackNestedContextAccess:(r,i)=>{try{e().isEnabled()&&e().trackNestedContextAccess(r,i)}catch{}},trackComputedProperty:(r,i,l,u,d,f,g)=>{try{e().isEnabled()&&e().trackComputedProperty(r,i,l,u,d,f,g)}catch{}},trackComputedRecalc:(r,i,l,u,d,f,g)=>{try{e().isEnabled()&&e().trackComputedRecalc(r,i,l,u,d,f,g)}catch{}},setNamedActionDefinitions:r=>{try{e().isEnabled()&&e().setNamedActionDefinitions(r)}catch{}},trackNamedActionRef:r=>{try{e().isEnabled()&&e().trackNamedActionRef(r)}catch{}}};o.devTools=n,Se.log("G7Core.devTools 인터페이스 초기화 완료")}let xo=null;function UA(){const o=window.G7Core;return o?.__devtools?Promise.resolve(o.__devtools):xo||(xo=new Promise((e,n)=>{const r=window.G7Config?.coreDevToolsAsset||"/build/core/devtools.min.js",i="g7-devtools-bundle",l=()=>{const f=window.G7Core?.__devtools;f?e(f):n(new Error("DevTools 번들 로드됨 — 그러나 __devtools 미노출"))};window.G7Core=window.G7Core||{},window.G7Core.__onDevToolsReady=l;const u=document.getElementById(i);if(u){u.addEventListener("load",l,{once:!0}),u.addEventListener("error",()=>n(new Error(`DevTools 번들 로드 실패: ${r}`)),{once:!0});return}const d=document.createElement("script");d.id=i,d.src=r,d.async=!1,d.addEventListener("load",l,{once:!0}),d.addEventListener("error",()=>{xo=null,n(new Error(`DevTools 번들 로드 실패: ${r}`))},{once:!0}),document.head.appendChild(d)}),xo)}function BA(){const o=window.G7Core;if(!o){Se.warn("G7Core가 초기화되지 않았습니다.");return}const e=Tr.getInstance();if(e.initialize(),!e.isEnabled()){window.G7DevTools={isEnabled:()=>!1,enable:()=>{Se.log("환경설정 > 고급 설정 > 디버그 모드를 켜세요")}},rd(),Se.log("G7DevTools 비활성화됨 (디버그 모드 꺼짐)");return}PA(o,e)}async function PA(o,e){let n;try{n=await UA()}catch(g){Se.warn("DevTools 번들 로드 실패 — 최소 API 로 폴백:",g),window.G7DevTools={isEnabled:()=>!1,enable:()=>{}},rd();return}const{DiagnosticEngine:r,getServerConnector:i,getStyleTracker:l}=n;jA(),rd();try{l().enable(),Se.log("StyleTracker 활성화됨")}catch(g){Se.warn("StyleTracker 활성화 실패:",g)}const u=new r,d=i(),f={isEnabled:()=>e.isEnabled(),state:{get:()=>e.getState(),getHistory:()=>e.getStateHistory(),watch:(g,m)=>e.watchState(g,m)},actions:{getHistory:()=>e.getActionHistory(),watch:g=>e.watchActions(g),getMetrics:()=>e.getActionMetrics()},binding:{evaluate:g=>{const m=o.getDataBindingEngine?.();if(!m){Se.warn("DataBindingEngine이 없습니다.");return}return m.evaluateExpression(g,e.getState())},getCacheStats:()=>e.getCacheStats(),clearStats:()=>{e.resetCacheStats(),Se.log("캐시 통계 초기화됨")}},diagnose:{analyze:g=>u.analyze(g),suggestFix:g=>u.suggestFix(g),getCommonIssues:()=>u.getCommonIssues(),getRulesByCategory:g=>u.getRulesByCategory(g)},server:{dumpState:g=>d.dumpState(g),sendLog:g=>d.sendLog(g),sendError:(g,m)=>d.sendError(g,m),isConnected:()=>d.isConnected(),testConnection:()=>d.testConnection()},config:{isDebugMode:()=>e.isEnabled(),setLogLevel:g=>e.setLogLevel(g),setMaxHistory:g=>e.setMaxHistory(g)},lifecycle:{getMountedComponents:()=>e.getLifecycleInfo().mountedComponents,getOrphanedListeners:()=>e.getLifecycleInfo().orphanedListeners},performance:{getRenderCount:()=>e.getPerformanceInfo().renderCounts,getBindingEvalCount:()=>e.getPerformanceInfo().bindingEvalCount,getMemoryWarnings:()=>e.getPerformanceInfo().memoryWarnings,startProfiling:()=>e.startProfiling(),stopProfiling:()=>e.stopProfiling()},network:{getActiveRequests:()=>e.getNetworkInfo().activeRequests,getRequestHistory:()=>e.getNetworkInfo().requestHistory,getPendingDataSources:()=>e.getNetworkInfo().pendingDataSources},conditional:{getIfConditions:()=>e.getConditionalInfo().ifConditions,getIterations:()=>e.getConditionalInfo().iterations},form:{getForms:()=>e.getFormInfo()},websocket:{getInfo:()=>e.getWebSocketInfo()}};window.G7DevTools=f,o.devtools=f,Se.log("G7DevTools 전역 객체 초기화 완료 (window.G7DevTools)"),qA(n.DevToolsPanel)}function qA(o){if(document.getElementById("g7-devtools-root")){Se.log("DevToolsPanel 이미 렌더링됨");return}const e=document.createElement("div");e.id="g7-devtools-root",document.body.appendChild(e);try{nd.createRoot(e).render(Xe.createElement(o)),Se.log("DevToolsPanel UI 렌더링 완료")}catch(n){Se.error("DevToolsPanel UI 렌더링 실패:",n)}}const et=dt("TemplateEngine"),re={templateId:null,locale:"ko",isInitialized:!1,reactRoot:null,containerId:null,currentLayoutJson:null,currentDataContext:{},translationContext:{templateId:"",locale:"ko"},registry:null,bindingEngine:null,translationEngine:null,actionDispatcher:null,templateMetadata:null};let To=!1;const Ro=[];async function GA(o){try{et.log("템플릿 메타데이터 로드 중...",o);const e=o.split("-").map(r=>r.split("_").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join("")).join(""),n=window[e];return n?.templateMetadata?(et.log("템플릿 메타데이터 로드 완료 (전역 변수)",n.templateMetadata),n.templateMetadata):(et.warn(`템플릿 번들에 메타데이터가 없습니다. 전역 변수: ${e}`),{identifier:o,locales:["ko","en"],name:{ko:o,en:o},description:{ko:"",en:""},version:"1.0.0",type:"admin"})}catch(e){return et.error("템플릿 메타데이터 로드 실패",e),{identifier:o,locales:["ko","en"],name:{ko:o,en:o},description:{ko:"",en:""},version:"1.0.0",type:"admin"}}}function vy(){const e=(typeof window<"u"?window.__templateApp:void 0)?.globalState?.appConfig?.supportedLocales,n=re.templateMetadata?.locales;return{$locale:re.locale,$locales:Array.isArray(e)&&e.length>0?e:n||["ko","en"],$templateLocales:n||["ko","en"],$templateId:re.templateId}}async function ko(o){try{if(et.log("템플릿 엔진 초기화 시작",o),re.isInitialized)throw new Error("템플릿 엔진이 이미 초기화되었습니다. destroyTemplate()을 먼저 호출하세요.");if(!o.templateId)throw new eA;To=o.debug??!1,typeof window<"u"&&(window.G7Config||(window.G7Config={}),window.G7Config.debug=To),BA(),re.templateId=o.templateId,re.locale=o.locale||"ko",et.log("엔진 인스턴스 생성 중..."),re.registry=fa.getInstance(),re.bindingEngine=new Rn,re.translationEngine=Er.getInstance(),o.cacheVersion!==void 0&&o.cacheVersion>0&&re.translationEngine.setCacheVersion(o.cacheVersion),re.translationContext={templateId:o.templateId,locale:re.locale},re.actionDispatcher=new fo({},re.translationEngine,re.translationContext),mC(re.actionDispatcher),et.log("다국어 파일 로드 중...",o.templateId,re.locale);const e="en",n=[re.translationEngine.loadTranslations(o.templateId,re.locale).then(()=>{et.log(`다국어 파일 로드 완료: ${re.locale}`)}).catch(r=>{et.warn(`다국어 파일 로드 실패 (${re.locale}):`,r instanceof Error?r.message:r)})];re.locale!==e&&n.push(re.translationEngine.loadTranslations(o.templateId,e).then(()=>{et.log(`폴백 다국어 파일 로드 완료: ${e}`)}).catch(r=>{et.warn(`폴백 다국어 파일 로드 실패 (${e}):`,r instanceof Error?r.message:r)})),await Promise.allSettled(n),et.log("템플릿 메타데이터 로드 중...",o.templateId),re.templateMetadata=await GA(o.templateId),re.isInitialized=!0,et.log("템플릿 엔진 초기화 완료 (ComponentRegistry는 별도 로드)")}catch(e){throw et.error("템플릿 엔진 초기화 실패",e),re.isInitialized=!1,re.registry=null,re.bindingEngine=null,re.translationEngine=null,re.actionDispatcher=null,e}}let Do=null;function yf(){const o=window.G7Core;return o?.__LayoutEditorChrome?Promise.resolve(o.__LayoutEditorChrome):Do||(Do=new Promise((e,n)=>{const r=window.G7Config?.coreEditorAsset||"/build/core/layout-editor.min.js",i="g7-layout-editor-bundle",l=document.getElementById(i),u=()=>{const f=window.G7Core?.__LayoutEditorChrome;f?e(f):n(new Error("편집기 번들 로드됨 — 그러나 __LayoutEditorChrome 미노출"))};if(window.G7Core=window.G7Core||{},window.G7Core.__onChromeReady=u,l){l.addEventListener("load",u,{once:!0}),l.addEventListener("error",()=>n(new Error(`편집기 번들 로드 실패: ${r}`)),{once:!0});return}const d=document.createElement("script");d.id=i,d.src=r,d.async=!1,d.addEventListener("load",u,{once:!0}),d.addEventListener("error",()=>{Do=null,n(new Error(`편집기 번들 로드 실패: ${r}`))},{once:!0}),document.head.appendChild(d)}),Do)}async function fs(o){try{if(et.log("템플릿 렌더링 시작",o),!re.isInitialized)throw new Error("템플릿 엔진이 초기화되지 않았습니다. initTemplateEngine()을 먼저 호출하세요.");if(!o.containerId)throw new Error("containerId는 필수입니다.");if(!o.layoutJson)throw new Error("layoutJson은 필수입니다.");const e=document.getElementById(o.containerId);if(!e)throw new Error(`컨테이너를 찾을 수 없습니다: #${o.containerId}`);const n=vy();if(re.containerId=o.containerId,re.currentLayoutJson=o.layoutJson,re.currentDataContext={...n,...o.dataContext||{}},re.translationContext=o.translationContext||{templateId:re.templateId||"",locale:re.locale},re.reactRoot||(et.log("React Root 생성"),re.reactRoot=nd.createRoot(e)),typeof window<"u"){const l=hy(window.location.pathname);if(l){et.log("레이아웃 편집기 모드 진입",l);let u;try{u=await yf()}catch(f){et.error("레이아웃 편집기 번들 로드 실패",f),ff.render(o.containerId,{title:"레이아웃 편집기 로드 실패",message:f instanceof Error?f.message:"편집기 번들을 불러오지 못했습니다.",icon:"fas fa-triangle-exclamation",showStack:!1,showReloadButton:!0,debug:To});return}const d=Xe.createElement(u,{templateIdentifier:l.templateIdentifier,initialLocale:re.locale});re.reactRoot.render(Xe.createElement(hc,{translationEngine:re.translationEngine,translationContext:re.translationContext,children:Xe.createElement(Nd,{children:Xe.createElement(ec,{children:Xe.createElement(lf,{children:d})})})}));return}}const r=o.layoutJson.components||[];if(r.length===0){et.warn("렌더링할 컴포넌트가 없습니다.");return}const i=o.layoutJson.modals||[];if(et.log("modals 배열:",i),et.log("modals 개수:",i.length),et.log("DynamicRenderer로 렌더링 시작"),re.reactRoot.render(Xe.createElement(hc,{translationEngine:re.translationEngine,translationContext:re.translationContext},Xe.createElement(Nd,null,Xe.createElement(ec,null,Xe.createElement(lf,null,[...r.map((l,u)=>{const d=re.currentLayoutJson?.layout_name||"";return Xe.createElement(ja,{key:d&&!l._fromBase?`${l.id}_${d}`:l.id,componentDef:l,dataContext:re.currentDataContext,translationContext:re.translationContext,registry:re.registry,bindingEngine:re.bindingEngine,translationEngine:re.translationEngine,actionDispatcher:re.actionDispatcher,isRootRenderer:u===0,layoutKey:d})}),Xe.createElement(sm,{key:"__modal_parent_context_provider"},i.map(l=>{const u=re.currentDataContext._global?.modalStack||[],f=u.includes(l.id)||re.currentDataContext._global?.activeModal===l.id,g=u.indexOf(l.id),m=g>=0?50+g:50,b=window.__g7LayoutContextStack||[],S=b[b.length-1]?.dataContext,_=Xe.createElement(ja,{key:`modal_${l.id}_renderer`,componentDef:{...l,props:{...l.props,isOpen:f,style:{...l.props?.style,zIndex:m},onClose:re.actionDispatcher?.createHandler({type:"click",handler:"closeModal"},re.currentDataContext)}},dataContext:re.currentDataContext,translationContext:re.translationContext,registry:re.registry,bindingEngine:re.bindingEngine,translationEngine:re.translationEngine,actionDispatcher:re.actionDispatcher,parentDataContext:S});return l.data_sources&&l.data_sources.length>0?Xe.createElement(dy,{key:`modal_${l.id}`,isOpen:f,modalId:l.id,dataSources:l.data_sources,dataContext:re.currentDataContext,globalStateUpdater:re.actionDispatcher?.getGlobalStateUpdater(),bindingEngine:re.bindingEngine,debug:To,children:_}):_}))]))))),et.log("템플릿 렌더링 완료"),Ro.length>0){et.log(`대기 중인 데이터 업데이트 ${Ro.length}건 적용`);const l=[...Ro];Ro.length=0;for(const{data:u,options:d}of l)hs(u,d)}}catch(e){throw et.error("템플릿 렌더링 실패",e),e}}function hs(o,e){try{if(et.log("템플릿 데이터 업데이트 시작",Object.keys(o)),!re.isInitialized)throw new Error("템플릿 엔진이 초기화되지 않았습니다.");if(!re.reactRoot||!re.currentLayoutJson){et.log("React 미준비 - 데이터 업데이트 큐잉:",Object.keys(o)),Ro.push({data:o,options:e});return}const n=vy(),r={...re.currentDataContext._global||{},...o._global||{}},i=CC(re.currentDataContext._localInit,o._localInit);re.currentDataContext={...n,...re.currentDataContext,...o,_global:r,_localInit:i},r._local!==void 0&&(re.currentDataContext._local=r._local),r._computed!==void 0&&(re.currentDataContext._computed=r._computed);const l=re.currentLayoutJson.components||[],u=re.currentLayoutJson.modals||[];et.log("updateTemplateData - modals 배열:",u),et.log("updateTemplateData - modals 개수:",u.length),et.log("updateTemplateData - activeModal:",re.currentDataContext._global?.activeModal);const d=()=>{re.reactRoot.render(Xe.createElement(hc,{translationEngine:re.translationEngine,translationContext:re.translationContext},Xe.createElement(Nd,null,Xe.createElement(ec,null,Xe.createElement(lf,null,[...l.map((f,g)=>{const m=re.currentLayoutJson?.layout_name||"";return Xe.createElement(ja,{key:m&&!f._fromBase?`${f.id}_${m}`:f.id,componentDef:f,dataContext:re.currentDataContext,translationContext:re.translationContext,registry:re.registry,bindingEngine:re.bindingEngine,translationEngine:re.translationEngine,actionDispatcher:re.actionDispatcher,isRootRenderer:g===0,layoutKey:m})}),Xe.createElement(sm,{key:"__modal_parent_context_provider_update"},u.map(f=>{const g=re.currentDataContext._global?.modalStack||[],b=g.includes(f.id)||re.currentDataContext._global?.activeModal===f.id,v=g.indexOf(f.id),S=v>=0?50+v:50,_=window.__g7LayoutContextStack||[],k=_[_.length-1]?.dataContext,O=Xe.createElement(ja,{key:`modal_${f.id}_renderer`,componentDef:{...f,props:{...f.props,isOpen:b,style:{...f.props?.style,zIndex:S},onClose:re.actionDispatcher?.createHandler({type:"click",handler:"closeModal"},re.currentDataContext)}},dataContext:re.currentDataContext,translationContext:re.translationContext,registry:re.registry,bindingEngine:re.bindingEngine,translationEngine:re.translationEngine,actionDispatcher:re.actionDispatcher,parentDataContext:k});return f.data_sources&&f.data_sources.length>0?Xe.createElement(dy,{key:`modal_${f.id}`,isOpen:b,modalId:f.id,dataSources:f.data_sources,dataContext:re.currentDataContext,globalStateUpdater:re.actionDispatcher?.getGlobalStateUpdater(),bindingEngine:re.bindingEngine,debug:To,children:O}):O}))])))))};e?.sync?(et.log("재렌더링 시작 (sync mode - 즉시 렌더링)"),d()):(et.log("재렌더링 시작 (with startTransition)"),I.startTransition(()=>{d()})),et.log("템플릿 데이터 업데이트 완료")}catch(n){throw et.error("템플릿 데이터 업데이트 실패",n),n}}function Sc(){try{et.log("템플릿 정리 시작"),re.reactRoot&&(et.log("React Root 언마운트"),re.reactRoot.unmount(),re.reactRoot=null),re.templateId=null,re.locale="ko",re.isInitialized=!1,re.containerId=null,re.currentLayoutJson=null,re.currentDataContext={},re.translationContext={templateId:"",locale:"ko"},re.registry=null,re.bindingEngine=null,re.translationEngine=null,re.actionDispatcher=null,re.templateMetadata=null,et.log("템플릿 정리 완료")}catch(o){throw et.error("템플릿 정리 실패",o),o}}function er(){return Object.freeze({...re})}function Sy(){return re.actionDispatcher}const Oo={initTemplateEngine:ko,renderTemplate:fs,updateTemplateData:hs,destroyTemplate:Sc,getState:er};typeof window<"u"&&(window.G7Core||(window.G7Core={}),window.G7Core.TemplateEngine=Oo,zA({getState:()=>({translationEngine:re.translationEngine,translationContext:re.translationContext,bindingEngine:re.bindingEngine,actionDispatcher:re.actionDispatcher,templateMetadata:re.templateMetadata}),transitionManager:Ha,responsiveManager:ui,webSocketManager:mc}),et.log("전역 객체 window.G7Core.TemplateEngine에 노출됨"));const Ua=Object.freeze(Object.defineProperty({__proto__:null,DataSourceManager:Sa,LayoutLoader:sf,TemplateApp:_o,TemplateEngine:Oo,default:Oo,destroyTemplate:Sc,getActionDispatcher:Sy,getState:er,initTemplateApp:mf,initTemplateEngine:ko,loadLayoutEditorBundle:yf,renderTemplate:fs,updateTemplateData:hs},Symbol.toStringTag,{value:"Module"}));Xt.DataSourceManager=Sa,Xt.LayoutLoader=sf,Xt.TemplateApp=_o,Xt.TemplateEngine=Oo,Xt.default=Oo,Xt.destroyTemplate=Sc,Xt.getActionDispatcher=Sy,Xt.getState=er,Xt.initTemplateApp=mf,Xt.initTemplateEngine=ko,Xt.loadLayoutEditorBundle=yf,Xt.renderTemplate=fs,Xt.updateTemplateData=hs,Object.defineProperties(Xt,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})})(this.G7Core=this.G7Core||{}); +//# sourceMappingURL=template-engine.min.js.map diff --git a/resources/js/core/template-engine/CHANGELOG.md b/resources/js/core/template-engine/CHANGELOG.md index 85e282e7..6cb1c3a2 100644 --- a/resources/js/core/template-engine/CHANGELOG.md +++ b/resources/js/core/template-engine/CHANGELOG.md @@ -5,6 +5,17 @@ > > 형식: [Keep a Changelog](https://keepachangelog.com/ko/1.1.0/) +## [engine-v1.54.4] - 2026-07-31 + +### Fixed + +#### 노드 `text` 키의 `{{raw:...}}` 바인딩이 평가되지 않고 텍스트가 통째로 사라지던 문제 + +- `DynamicRenderer.tsx` `renderChildren` — 노드 레벨 `text` 키 처리에서 `raw:` 접두사를 벗기지 않은 채 표현식 평가로 넘겨, `raw:` 의 콜론이 식의 일부로 파싱되며 `Unexpected token ':'` 로 예외가 났다. props 값 해석(`renderProps`)과 반복 렌더(`RenderHelpers.renderItemChildren`)에는 이미 있던 접두사 처리가 이 경로에만 빠져 있었다. +- 증상: 관리자 레이아웃 편집 화면의 파일 목록 등 `text: "{{raw:...}}"` 를 쓰는 자리에서 텍스트가 빈 값으로 렌더된다. 콘솔에는 경고만 남고 에러 화면이 뜨지 않아 조용한 실패로 관측된다(해당 화면 1회 진입에 174건). +- 접두사 제거 후 파이프/복합식/단순 경로 분기를 동일하게 태우고, 결과는 `wrapRawDeep` 로 감싸 번역 면제를 유지한다 — 다른 두 경로와 같은 규칙이다. +- 기존 동작 무영향: `raw:` 가 없는 `text` 는 종전 경로·결과 그대로다. + ## [engine-v1.54.3] - 2026-07-25 ### Fixed diff --git a/resources/js/core/template-engine/DynamicRenderer.tsx b/resources/js/core/template-engine/DynamicRenderer.tsx index fec3f75f..0bd9fedf 100644 --- a/resources/js/core/template-engine/DynamicRenderer.tsx +++ b/resources/js/core/template-engine/DynamicRenderer.tsx @@ -2606,13 +2606,24 @@ const DynamicRenderer: React.FC = memo( const singleBindingPath = extractSingleBinding(text); if (singleBindingPath !== null) { + // raw: 접두사 감지 — props 처리(위 renderProps)와 동일 규칙. + // 접두사를 벗기지 않으면 `raw:` 의 콜론이 식의 일부로 파싱되어 + // evaluateExpression 이 `Unexpected token ':'` 로 던지고 텍스트가 통째로 사라진다. + // @since engine-v1.54.4 + let isRawBinding = false; + let effectivePath = singleBindingPath; + if (singleBindingPath.startsWith(RAW_PREFIX)) { + isRawBinding = true; + effectivePath = singleBindingPath.slice(RAW_PREFIX.length); + } + // 파이프가 있는 경우 resolveBindings 사용 (파이프 처리 포함) - if (hasPipes(singleBindingPath)) { - resolvedText = bindingEngine.resolveBindings(text, extendedDataContext, { skipCache: true }, textTrackingInfo); - } else if (isComplexExpression(singleBindingPath)) { + if (hasPipes(effectivePath)) { + resolvedText = bindingEngine.resolveBindings(`{{${effectivePath}}}`, extendedDataContext, { skipCache: true }, textTrackingInfo); + } else if (isComplexExpression(effectivePath)) { // 복잡한 표현식인 경우 evaluateExpression 사용 try { - resolvedText = bindingEngine.evaluateExpression(singleBindingPath, extendedDataContext, textTrackingInfo); + resolvedText = bindingEngine.evaluateExpression(effectivePath, extendedDataContext, textTrackingInfo); } catch (error) { logger.warn( `text 표현식 평가 실패 (컴포넌트: ${effectiveComponentDef.id}):`, @@ -2621,7 +2632,11 @@ const DynamicRenderer: React.FC = memo( resolvedText = ''; } } else { - resolvedText = bindingEngine.resolve(singleBindingPath, extendedDataContext, { skipCache: true }, textTrackingInfo); + resolvedText = bindingEngine.resolve(effectivePath, extendedDataContext, { skipCache: true }, textTrackingInfo); + } + + if (isRawBinding && resolvedText != null) { + resolvedText = wrapRawDeep(resolvedText); } } else if (text.includes('{{')) { // 문자열 보간 diff --git a/resources/js/core/template-engine/__tests__/DynamicRenderer.test.tsx b/resources/js/core/template-engine/__tests__/DynamicRenderer.test.tsx index 8af6efcd..a6125c9a 100644 --- a/resources/js/core/template-engine/__tests__/DynamicRenderer.test.tsx +++ b/resources/js/core/template-engine/__tests__/DynamicRenderer.test.tsx @@ -2023,4 +2023,78 @@ describe('DynamicRenderer - TranslationEngine 통합', () => { expect(screen.getByRole('button').textContent).toBe('일반 제목 텍스트'); }); }); + + describe('노드 text 키의 raw: 접두사 (engine-v1.54.4 회귀)', () => { + // 배경: props.text 는 raw: 를 벗겼지만 노드 레벨 `text` 키 경로는 접두사를 + // 그대로 evaluateExpression 에 넘겨 `Unexpected token ':'` 로 던졌다. + // 결과적으로 레이아웃 편집 화면의 파일 목록 텍스트가 통째로 빈 값이 되었다. + it('노드 text 의 {{raw:복합식}} 이 평가되어 표시되어야 함', () => { + const componentDef: ComponentDefinition = { + id: 'raw-text-node-1', + type: 'basic', + name: 'Button', + text: '{{raw:file.description || file.name}}', + }; + + render( + + ); + + expect(screen.getByRole('button').textContent).toBe('admin_module_list.json'); + }); + + it('노드 text 의 {{raw:단순경로}} 결과의 $t: 토큰은 번역 면제되어야 함', () => { + const componentDef: ComponentDefinition = { + id: 'raw-text-node-2', + type: 'basic', + name: 'Button', + text: '{{raw:post.title}}', + }; + + render( + + ); + + expect(screen.getByRole('button').textContent).toBe('$t:admin.dashboard'); + }); + + it('노드 text 의 raw: 없는 복합식은 종전대로 평가되어야 함 (비회귀)', () => { + const componentDef: ComponentDefinition = { + id: 'raw-text-node-3', + type: 'basic', + name: 'Button', + text: "{{file.description || file.name}}", + }; + + render( + + ); + + expect(screen.getByRole('button').textContent).toBe('저장'); + }); + }); }); diff --git a/templates/_bundled/sirsoft-admin_basic/CHANGELOG.md b/templates/_bundled/sirsoft-admin_basic/CHANGELOG.md index cd68c9b0..9c5b445d 100644 --- a/templates/_bundled/sirsoft-admin_basic/CHANGELOG.md +++ b/templates/_bundled/sirsoft-admin_basic/CHANGELOG.md @@ -30,6 +30,10 @@ ### Fixed +- 모듈·플러그인·템플릿 관리 화면에서 '업데이트 확인'을 눌러 업데이트가 발견돼도 항상 "모두 최신 상태입니다"라고 안내되던 문제를 수정했습니다. +- 게시판·상품 카테고리 목록의 새로고침 버튼과 언어팩 재활성화 안내에서 번역되지 않은 내부 문구가 그대로 보이던 문제를 수정했습니다. +- 모듈·플러그인·템플릿 관리 화면의 목록 요약이 항상 "총 0개 중 1-0개 표시"로 나오고, 목록이 한 화면을 넘어도 다음 쪽으로 넘어갈 수 없던 문제를 수정했습니다. +- 업데이트 모달에서 수정된 화면 확인에 실패했는데도 "수정된 레이아웃이 없습니다"라고 표시되던 문제를 수정했습니다. 그대로 '모두 교체'를 진행하면 직접 고친 화면이 사라질 수 있어, 이제 확인하지 못했다는 안내와 함께 '수정 유지'를 권장합니다. - 본인확인 코드 입력 화면에서 "남은 시도" 안내를 제거했습니다. 외부 인증 화면을 거쳐 돌아온 경우 실제보다 많은 횟수가 표시될 수 있어, 잘못된 숫자를 보여주는 대신 표시하지 않도록 했습니다. 시도 횟수 제한 자체는 종전대로 적용됩니다. - 회원 목록에서 검색할 때 페이지를 넘길 때와 달리 표 위에 로딩 표시가 뜨지 않던 문제를 수정했습니다. - 회원·역할·스케줄 목록에서 검색·정렬·페이지 이동 시 표 위에 걸어 둔 로딩 표시가 실제로는 동작하지 않던 문제를 수정했습니다. 다른 관리자 목록 화면과 같은 방식으로 표 본문에만 표시됩니다. diff --git a/templates/_bundled/sirsoft-admin_basic/__tests__/i18n/layout-translation-keys.test.ts b/templates/_bundled/sirsoft-admin_basic/__tests__/i18n/layout-translation-keys.test.ts new file mode 100644 index 00000000..dd60d729 --- /dev/null +++ b/templates/_bundled/sirsoft-admin_basic/__tests__/i18n/layout-translation-keys.test.ts @@ -0,0 +1,139 @@ +/** + * @file layout-translation-keys.test.ts + * @description 레이아웃이 참조하는 `$t:` 키가 템플릿 언어 파일에 실제로 정의돼 있는지 전수 검사 + * + * Chrome MCP 정밀 점검에서 `common.refresh` / `common.activate` / `common.skip` 세 키가 + * 정의되지 않아, 게시판·이커머스 목록의 새로고침 버튼과 언어팩 재활성화 모달에 키 원문이 + * 그대로 노출됐다(D13). 화면에는 아무 오류도 뜨지 않고 문자열만 깨져 보인다. + * + * 특정 키를 손으로 열거하면 다음에 추가되는 키를 다시 놓친다. 그래서 이 테스트는 + * **레이아웃에서 참조된 키를 스캔해** 그 전부가 ko/en 양쪽에 있는지 확인한다. + * 검사 대상에는 이 템플릿의 레이아웃뿐 아니라, 같은 관리자 화면에 얹히는 번들 + * 모듈/플러그인 레이아웃도 포함한다 — 이들이 참조하는 `common.*` 도 결국 이 템플릿의 + * 언어 파일로 해석되기 때문이다. + */ + +import { describe, it, expect } from 'vitest'; +import fs from 'fs'; +import path from 'path'; +import { fileURLToPath } from 'url'; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const templateDir = path.resolve(here, '../..'); + +/** artisan 파일을 기준으로 프로젝트 루트를 찾는다 (_bundled/활성 디렉토리 모두 호환) */ +function findProjectRoot(startDir: string): string { + let dir = startDir; + while (dir !== path.dirname(dir)) { + if (fs.existsSync(path.join(dir, 'artisan'))) return dir; + dir = path.dirname(dir); + } + return path.resolve(startDir, '../..'); +} + +const rootDir = findProjectRoot(templateDir); + +/** 디렉토리 하위의 모든 JSON 파일 경로를 수집한다 */ +function collectJsonFiles(dir: string): string[] { + if (!fs.existsSync(dir)) return []; + + return fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => { + const full = path.join(dir, entry.name); + if (entry.isDirectory()) return collectJsonFiles(full); + return entry.isFile() && entry.name.endsWith('.json') ? [full] : []; + }); +} + +/** 확장 종류별 번들 레이아웃 디렉토리를 수집한다 */ +function collectBundledLayoutDirs(kind: 'modules' | 'plugins'): string[] { + const base = path.join(rootDir, kind, '_bundled'); + if (!fs.existsSync(base)) return []; + + return fs + .readdirSync(base, { withFileTypes: true }) + .filter((e) => e.isDirectory()) + .map((e) => path.join(base, e.name, 'resources', 'layouts')) + .filter((p) => fs.existsSync(p)); +} + +const LAYOUT_DIRS = [ + path.join(templateDir, 'layouts'), + ...collectBundledLayoutDirs('modules'), + ...collectBundledLayoutDirs('plugins'), +]; + +/** `$t:.` 참조를 수집한다 (namespace → key 집합) */ +function collectTranslationRefs(): Map>> { + const refs = new Map>>(); + const pattern = /\$t:([a-zA-Z0-9_]+)\.([a-zA-Z0-9_.]+)/g; + + for (const dir of LAYOUT_DIRS) { + for (const file of collectJsonFiles(dir)) { + const raw = fs.readFileSync(file, 'utf8'); + for (const match of raw.matchAll(pattern)) { + const [, namespace, key] = match; + // 표현식 끝의 마침표는 키의 일부가 아니다 + const normalized = key.replace(/\.$/, ''); + if (!refs.has(namespace)) refs.set(namespace, new Map()); + const byKey = refs.get(namespace)!; + if (!byKey.has(normalized)) byKey.set(normalized, new Set()); + byKey.get(normalized)!.add(path.relative(rootDir, file)); + } + } + } + + return refs; +} + +/** 로케일별 언어 파일을 읽는다 (없으면 null) */ +function loadLangFile(locale: string, namespace: string): Record | null { + const file = path.join(templateDir, 'lang', 'partial', locale, `${namespace}.json`); + if (!fs.existsSync(file)) return null; + + return JSON.parse(fs.readFileSync(file, 'utf8')); +} + +/** 점 표기 경로가 객체에 존재하는지 확인한다 */ +function hasPath(source: Record, dotted: string): boolean { + return dotted.split('.').reduce( + (acc, segment) => + acc && typeof acc === 'object' ? (acc as Record)[segment] : undefined, + source + ) !== undefined; +} + +const REFS = collectTranslationRefs(); +const LOCALES = ['ko', 'en']; + +describe('레이아웃 $t: 키 정의 검사', () => { + it('검사 대상 레이아웃과 참조 키가 실제로 수집되어야 함 (모집단 도달 확인)', () => { + expect(LAYOUT_DIRS.length).toBeGreaterThan(1); + expect(REFS.get('common')?.size ?? 0).toBeGreaterThan(10); + }); + + it.each(LOCALES)('common 네임스페이스의 모든 참조 키가 %s 에 정의되어야 함', (locale) => { + const defined = loadLangFile(locale, 'common'); + expect(defined, `lang/partial/${locale}/common.json 이 없습니다`).not.toBeNull(); + + const missing: string[] = []; + for (const [key, files] of REFS.get('common') ?? []) { + if (!hasPath(defined!, key)) { + missing.push(`common.${key} (참조: ${[...files].slice(0, 3).join(', ')})`); + } + } + + expect( + missing, + `정의되지 않은 키가 화면에 원문으로 노출됩니다:\n - ${missing.join('\n - ')}` + ).toEqual([]); + }); + + it('D13 회귀: 새로고침·활성화·건너뛰기 키가 ko/en 양쪽에 있어야 함', () => { + for (const locale of LOCALES) { + const defined = loadLangFile(locale, 'common')!; + for (const key of ['refresh', 'activate', 'skip']) { + expect(hasPath(defined, key), `${locale}/common.json 에 ${key} 누락`).toBe(true); + } + } + }); +}); diff --git a/templates/_bundled/sirsoft-admin_basic/__tests__/layouts/extension-list-contract.test.tsx b/templates/_bundled/sirsoft-admin_basic/__tests__/layouts/extension-list-contract.test.tsx new file mode 100644 index 00000000..f1b49d37 --- /dev/null +++ b/templates/_bundled/sirsoft-admin_basic/__tests__/layouts/extension-list-contract.test.tsx @@ -0,0 +1,99 @@ +/** + * @file extension-list-contract.test.tsx + * @description 확장(모듈/플러그인/템플릿) 목록·업데이트 모달의 API 계약 회귀 테스트 + * + * Chrome MCP 정밀 점검에서 실측된 결함 3건을 레이아웃 JSON 수준에서 고정한다. + * + * 1) check-updates 응답 필드는 `updated_count` 인데 레이아웃이 `update_count` 를 읽어 + * 업데이트가 감지돼도 항상 "모든 X가 최신 상태입니다" 토스트가 떴다. + * 2) 목록 페이지네이션이 `data.total` / `data.current_page` 를 읽는데 실제 응답은 + * `data.pagination.*` 이라 "총 0개 중 1-0개 표시" 로 고정 표기됐다. + * 3) check-modified-layouts 호출에 onError 가 없어, 네트워크 실패 시 모달이 + * "수정된 레이아웃이 없습니다" 라고 단언 → '모두 교체' 진행 시 수정 소실. + */ + +import { describe, it, expect } from 'vitest'; +import moduleList from '../../layouts/admin_module_list.json'; +import pluginList from '../../layouts/admin_plugin_list.json'; +import templateList from '../../layouts/admin_template_list.json'; +import tabAdmin from '../../layouts/partials/admin_template_list/_tab_admin.json'; +import tabUser from '../../layouts/partials/admin_template_list/_tab_user.json'; +import moduleModal from '../../layouts/partials/admin_module_list/_modal_update.json'; +import pluginModal from '../../layouts/partials/admin_plugin_list/_modal_update.json'; +import templateModal from '../../layouts/partials/admin_template_list/_modal_update.json'; + +const LIST_LAYOUTS: Array<[string, unknown]> = [ + ['admin_module_list', moduleList], + ['admin_plugin_list', pluginList], + ['admin_template_list', templateList], +]; + +const PAGINATION_LAYOUTS: Array<[string, unknown, string]> = [ + ['admin_module_list', moduleList, 'modules'], + ['admin_plugin_list', pluginList, 'plugins'], + ['_tab_admin', tabAdmin, 'templates'], + ['_tab_user', tabUser, 'templates'], +]; + +const MODALS: Array<[string, unknown, string]> = [ + ['module', moduleModal, 'Module'], + ['plugin', pluginModal, 'Plugin'], + ['template', templateModal, 'Template'], +]; + +const CHECK_SOURCES: Array<[string, unknown, string]> = [ + ['admin_module_list', moduleList, 'Module'], + ['admin_plugin_list', pluginList, 'Plugin'], + ['_tab_admin', tabAdmin, 'Template'], + ['_tab_user', tabUser, 'Template'], +]; + +describe('확장 목록 레이아웃 — API 계약', () => { + it.each(LIST_LAYOUTS)('%s: check-updates 는 updated_count 를 읽어야 함', (_name, layout) => { + const json = JSON.stringify(layout); + expect(json).toContain('response.data?.updated_count'); + // 잘못된 필드명이 남아있으면 토스트가 영구히 "최신 상태" 로 고정된다 + expect(json).not.toContain('response.data?.update_count'); + expect(json).not.toContain('response.data.update_count'); + }); + + it.each(PAGINATION_LAYOUTS)('%s: 페이지네이션은 data.pagination.* 경로여야 함', (_name, layout, ds) => { + const json = JSON.stringify(layout); + for (const key of ['total', 'current_page', 'last_page', 'per_page']) { + expect(json).not.toContain(`${ds}?.data?.${key}`); + } + expect(json).toContain(`${ds}?.data?.pagination?.total`); + }); + + it.each(CHECK_SOURCES)('%s: check-modified-layouts 호출에 onError 가 있어야 함', (_name, layout, kind) => { + const found: any[] = []; + const walk = (node: any) => { + if (Array.isArray(node)) { node.forEach(walk); return; } + if (!node || typeof node !== 'object') return; + if (node.handler === 'apiCall' && typeof node.target === 'string' + && node.target.includes('/check-modified-layouts')) { + found.push(node); + } + Object.values(node).forEach(walk); + }; + walk(layout); + + expect(found.length).toBeGreaterThan(0); + for (const call of found) { + expect(Array.isArray(call.onError)).toBe(true); + expect(JSON.stringify(call.onError)).toContain(`modified${kind}LayoutsCheckFailed`); + // 성공 시에는 플래그를 반드시 해제해야 재조회가 경고에 갇히지 않는다 + expect(JSON.stringify(call.onSuccess)).toContain(`modified${kind}LayoutsCheckFailed`); + } + }); + + it.each(MODALS)('%s 업데이트 모달: 확인 실패 분기가 있고 "수정 없음" 단언을 가로막아야 함', (_name, modal, kind) => { + const json = JSON.stringify(modal); + expect(json).toContain('modified_layouts_check_failed'); + expect(json).toContain(`_global.modified${kind}LayoutsCheckFailed`); + // "수정된 레이아웃이 없습니다" 는 확인이 성공했을 때만 표시되어야 한다 + expect(json).toContain( + `{{!_global.hasModified${kind}Layouts && !_global.modified${kind}LayoutsCheckFailed}}` + ); + }); +}); diff --git a/templates/_bundled/sirsoft-admin_basic/lang/partial/en/admin.json b/templates/_bundled/sirsoft-admin_basic/lang/partial/en/admin.json index 655be059..1728e307 100644 --- a/templates/_bundled/sirsoft-admin_basic/lang/partial/en/admin.json +++ b/templates/_bundled/sirsoft-admin_basic/lang/partial/en/admin.json @@ -723,6 +723,7 @@ "layout_strategy_keep_desc": "Preserve user-modified layouts.", "modified_layouts_warning": "{{count}} modified layout(s) exist. Choosing 'Overwrite All' will discard the modifications.", "no_modified_layouts": "No modified layouts.", + "modified_layouts_check_failed": "Could not check for modified layouts. Check your connection and retry, or choose 'Keep changes' to be safe.", "modified_layouts_list_title": "Modified layouts to keep ({{count}})", "modified_layouts_keep_notice": "These layouts will retain their current content after the update." }, @@ -928,6 +929,7 @@ "layout_strategy_keep_desc": "Preserve user-modified layouts.", "modified_layouts_warning": "{{count}} modified layout(s) exist. Choosing 'Overwrite All' will discard the modifications.", "no_modified_layouts": "No modified layouts.", + "modified_layouts_check_failed": "Could not check for modified layouts. Check your connection and retry, or choose 'Keep changes' to be safe.", "modified_layouts_list_title": "Modified layouts to keep ({{count}})", "modified_layouts_keep_notice": "These layouts will retain their current content after the update." }, @@ -2120,6 +2122,7 @@ "layout_strategy_keep_desc": "Keep user-modified layouts.", "modified_layouts_warning": "{{count}} layout(s) have been modified. Selecting 'Overwrite All' will discard modifications.", "no_modified_layouts": "No modified layouts found.", + "modified_layouts_check_failed": "Could not check for modified layouts. Check your connection and retry, or choose 'Keep changes' to be safe.", "modified_layouts_list_title": "Modified layouts to be preserved ({{count}})", "modified_layouts_keep_notice": "These layouts will retain their current content after the update.", "activate_warning_title": "Template Activation Warning", diff --git a/templates/_bundled/sirsoft-admin_basic/lang/partial/en/common.json b/templates/_bundled/sirsoft-admin_basic/lang/partial/en/common.json index df72e0c5..a877aaa0 100644 --- a/templates/_bundled/sirsoft-admin_basic/lang/partial/en/common.json +++ b/templates/_bundled/sirsoft-admin_basic/lang/partial/en/common.json @@ -76,5 +76,8 @@ "scope_type_role_desc": "Only resources from users with the same role", "multilingual": { "add_language": "Add Language" - } -} \ No newline at end of file + }, + "refresh": "Refresh", + "activate": "Activate", + "skip": "Skip" +} diff --git a/templates/_bundled/sirsoft-admin_basic/lang/partial/ko/admin.json b/templates/_bundled/sirsoft-admin_basic/lang/partial/ko/admin.json index 5de4da04..39279b2d 100644 --- a/templates/_bundled/sirsoft-admin_basic/lang/partial/ko/admin.json +++ b/templates/_bundled/sirsoft-admin_basic/lang/partial/ko/admin.json @@ -727,6 +727,7 @@ "layout_strategy_keep_desc": "사용자가 수정한 레이아웃을 유지합니다.", "modified_layouts_warning": "수정된 레이아웃이 {{count}}개 있습니다. '모두 교체'를 선택하면 수정 내용이 삭제됩니다.", "no_modified_layouts": "수정된 레이아웃이 없습니다.", + "modified_layouts_check_failed": "수정 여부를 확인하지 못했습니다. 네트워크 상태를 확인한 뒤 다시 시도하거나, 안전하게 '수정 유지'를 선택하세요.", "modified_layouts_list_title": "유지될 수정 레이아웃 ({{count}}개)", "modified_layouts_keep_notice": "위 레이아웃은 업데이트 후에도 현재 내용이 유지됩니다." }, @@ -932,6 +933,7 @@ "layout_strategy_keep_desc": "사용자가 수정한 레이아웃을 유지합니다.", "modified_layouts_warning": "수정된 레이아웃이 {{count}}개 있습니다. '모두 교체'를 선택하면 수정 내용이 삭제됩니다.", "no_modified_layouts": "수정된 레이아웃이 없습니다.", + "modified_layouts_check_failed": "수정 여부를 확인하지 못했습니다. 네트워크 상태를 확인한 뒤 다시 시도하거나, 안전하게 '수정 유지'를 선택하세요.", "modified_layouts_list_title": "유지될 수정 레이아웃 ({{count}}개)", "modified_layouts_keep_notice": "위 레이아웃은 업데이트 후에도 현재 내용이 유지됩니다." }, @@ -2124,6 +2126,7 @@ "layout_strategy_keep_desc": "사용자가 수정한 레이아웃을 유지합니다.", "modified_layouts_warning": "수정된 레이아웃이 {{count}}개 있습니다. '모두 교체'를 선택하면 수정 내용이 삭제됩니다.", "no_modified_layouts": "수정된 레이아웃이 없습니다.", + "modified_layouts_check_failed": "수정 여부를 확인하지 못했습니다. 네트워크 상태를 확인한 뒤 다시 시도하거나, 안전하게 '수정 유지'를 선택하세요.", "modified_layouts_list_title": "유지될 수정 레이아웃 ({{count}}개)", "modified_layouts_keep_notice": "위 레이아웃은 업데이트 후에도 현재 내용이 유지됩니다.", "activate_warning_title": "템플릿 활성화 경고", diff --git a/templates/_bundled/sirsoft-admin_basic/lang/partial/ko/common.json b/templates/_bundled/sirsoft-admin_basic/lang/partial/ko/common.json index 1c5decac..eea0abb6 100644 --- a/templates/_bundled/sirsoft-admin_basic/lang/partial/ko/common.json +++ b/templates/_bundled/sirsoft-admin_basic/lang/partial/ko/common.json @@ -76,5 +76,8 @@ "scope_type_role_desc": "같은 역할의 사용자 리소스만", "multilingual": { "add_language": "언어 추가" - } -} \ No newline at end of file + }, + "refresh": "새로고침", + "activate": "활성화", + "skip": "건너뛰기" +} diff --git a/templates/_bundled/sirsoft-admin_basic/layouts/admin_module_list.json b/templates/_bundled/sirsoft-admin_basic/layouts/admin_module_list.json index ad5c57f3..9526a871 100644 --- a/templates/_bundled/sirsoft-admin_basic/layouts/admin_module_list.json +++ b/templates/_bundled/sirsoft-admin_basic/layouts/admin_module_list.json @@ -49,10 +49,12 @@ "fallback": { "data": { "data": [], - "current_page": 1, - "last_page": 1, - "per_page": 12, - "total": 0 + "pagination": { + "current_page": 1, + "last_page": 1, + "per_page": 12, + "total": 0 + } } } }, @@ -167,7 +169,7 @@ "handler": "toast", "params": { "type": "success", - "message": "{{response.data?.update_count > 0 ? '$t:admin.modules.check_updates_success|count=' + response.data.update_count : '$t:admin.modules.check_updates_no_updates'}}" + "message": "{{response.data?.updated_count > 0 ? '$t:admin.modules.check_updates_success|count=' + response.data.updated_count : '$t:admin.modules.check_updates_no_updates'}}" } } ], @@ -640,8 +642,8 @@ "pagination": true, "alwaysShowPagination": true, "serverSidePagination": true, - "serverCurrentPage": "{{modules?.data?.current_page ?? 1}}", - "serverTotalPages": "{{modules?.data?.last_page ?? 1}}", + "serverCurrentPage": "{{modules?.data?.pagination?.current_page ?? 1}}", + "serverTotalPages": "{{modules?.data?.pagination?.last_page ?? 1}}", "cardClassName": "border border-gray-200 dark:border-gray-700 rounded-lg p-4 relative", "cardColumns": [ { @@ -1010,7 +1012,8 @@ "moduleLayoutStrategy": "overwrite", "hasModifiedModuleLayouts": false, "modifiedModuleLayoutsCount": 0, - "modifiedModuleLayouts": [] + "modifiedModuleLayouts": [], + "modifiedModuleLayoutsCheckFailed": false } }, { @@ -1027,7 +1030,17 @@ "target": "global", "hasModifiedModuleLayouts": "{{response.data?.has_modified_layouts ?? false}}", "modifiedModuleLayoutsCount": "{{response.data?.modified_count ?? 0}}", - "modifiedModuleLayouts": "{{response.data?.modified_layouts ?? []}}" + "modifiedModuleLayouts": "{{response.data?.modified_layouts ?? []}}", + "modifiedModuleLayoutsCheckFailed": false + } + } + ], + "onError": [ + { + "handler": "setState", + "params": { + "target": "global", + "modifiedModuleLayoutsCheckFailed": true } } ] @@ -1397,7 +1410,7 @@ { "type": "basic", "name": "Span", - "text": "$t:admin.modules.pagination_info|total={{modules?.data?.total ?? 0}}|from={{((modules?.data?.current_page ?? 1) - 1) * (modules?.data?.per_page ?? 12) + 1}}|to={{Math.min((modules?.data?.current_page ?? 1) * (modules?.data?.per_page ?? 12), modules?.data?.total ?? 0)}}" + "text": "$t:admin.modules.pagination_info|total={{modules?.data?.pagination?.total ?? 0}}|from={{((modules?.data?.pagination?.current_page ?? 1) - 1) * (modules?.data?.pagination?.per_page ?? 12) + 1}}|to={{Math.min((modules?.data?.pagination?.current_page ?? 1) * (modules?.data?.pagination?.per_page ?? 12), modules?.data?.pagination?.total ?? 0)}}" } ] } diff --git a/templates/_bundled/sirsoft-admin_basic/layouts/admin_plugin_list.json b/templates/_bundled/sirsoft-admin_basic/layouts/admin_plugin_list.json index 8b2d8239..f55b65e4 100644 --- a/templates/_bundled/sirsoft-admin_basic/layouts/admin_plugin_list.json +++ b/templates/_bundled/sirsoft-admin_basic/layouts/admin_plugin_list.json @@ -49,10 +49,12 @@ "fallback": { "data": { "data": [], - "current_page": 1, - "last_page": 1, - "per_page": 12, - "total": 0 + "pagination": { + "current_page": 1, + "last_page": 1, + "per_page": 12, + "total": 0 + } } } }, @@ -167,7 +169,7 @@ "handler": "toast", "params": { "type": "success", - "message": "{{response.data?.update_count > 0 ? '$t:admin.plugins.check_updates_success|count=' + response.data.update_count : '$t:admin.plugins.check_updates_no_updates'}}" + "message": "{{response.data?.updated_count > 0 ? '$t:admin.plugins.check_updates_success|count=' + response.data.updated_count : '$t:admin.plugins.check_updates_no_updates'}}" } } ], @@ -649,8 +651,8 @@ "pagination": true, "alwaysShowPagination": true, "serverSidePagination": true, - "serverCurrentPage": "{{plugins?.data?.current_page ?? 1}}", - "serverTotalPages": "{{plugins?.data?.last_page ?? 1}}", + "serverCurrentPage": "{{plugins?.data?.pagination?.current_page ?? 1}}", + "serverTotalPages": "{{plugins?.data?.pagination?.last_page ?? 1}}", "cardClassName": "border border-gray-200 dark:border-gray-700 rounded-lg p-4 relative", "cardColumns": [ { @@ -1022,7 +1024,8 @@ "pluginLayoutStrategy": "overwrite", "hasModifiedPluginLayouts": false, "modifiedPluginLayoutsCount": 0, - "modifiedPluginLayouts": [] + "modifiedPluginLayouts": [], + "modifiedPluginLayoutsCheckFailed": false } }, { @@ -1039,7 +1042,17 @@ "target": "global", "hasModifiedPluginLayouts": "{{response.data?.has_modified_layouts ?? false}}", "modifiedPluginLayoutsCount": "{{response.data?.modified_count ?? 0}}", - "modifiedPluginLayouts": "{{response.data?.modified_layouts ?? []}}" + "modifiedPluginLayouts": "{{response.data?.modified_layouts ?? []}}", + "modifiedPluginLayoutsCheckFailed": false + } + } + ], + "onError": [ + { + "handler": "setState", + "params": { + "target": "global", + "modifiedPluginLayoutsCheckFailed": true } } ] @@ -1422,7 +1435,7 @@ { "type": "basic", "name": "Span", - "text": "$t:admin.plugins.pagination_info|total={{plugins?.data?.total ?? 0}}|from={{((plugins?.data?.current_page ?? 1) - 1) * (plugins?.data?.per_page ?? 12) + 1}}|to={{Math.min((plugins?.data?.current_page ?? 1) * (plugins?.data?.per_page ?? 12), plugins?.data?.total ?? 0)}}" + "text": "$t:admin.plugins.pagination_info|total={{plugins?.data?.pagination?.total ?? 0}}|from={{((plugins?.data?.pagination?.current_page ?? 1) - 1) * (plugins?.data?.pagination?.per_page ?? 12) + 1}}|to={{Math.min((plugins?.data?.pagination?.current_page ?? 1) * (plugins?.data?.pagination?.per_page ?? 12), plugins?.data?.pagination?.total ?? 0)}}" } ] } diff --git a/templates/_bundled/sirsoft-admin_basic/layouts/admin_template_list.json b/templates/_bundled/sirsoft-admin_basic/layouts/admin_template_list.json index 09f51476..5e8550e2 100644 --- a/templates/_bundled/sirsoft-admin_basic/layouts/admin_template_list.json +++ b/templates/_bundled/sirsoft-admin_basic/layouts/admin_template_list.json @@ -52,10 +52,12 @@ "fallback": { "data": { "data": [], - "current_page": 1, - "last_page": 1, - "per_page": 12, - "total": 0 + "pagination": { + "current_page": 1, + "last_page": 1, + "per_page": 12, + "total": 0 + } } } }, @@ -170,7 +172,7 @@ "handler": "toast", "params": { "type": "success", - "message": "{{response.data?.update_count > 0 ? '$t:admin.templates.check_updates_success|count=' + response.data.update_count : '$t:admin.templates.check_updates_no_updates'}}" + "message": "{{response.data?.updated_count > 0 ? '$t:admin.templates.check_updates_success|count=' + response.data.updated_count : '$t:admin.templates.check_updates_no_updates'}}" } } ], diff --git a/templates/_bundled/sirsoft-admin_basic/layouts/partials/admin_module_list/_modal_update.json b/templates/_bundled/sirsoft-admin_basic/layouts/partials/admin_module_list/_modal_update.json index b3e43726..622c7a22 100644 --- a/templates/_bundled/sirsoft-admin_basic/layouts/partials/admin_module_list/_modal_update.json +++ b/templates/_bundled/sirsoft-admin_basic/layouts/partials/admin_module_list/_modal_update.json @@ -440,7 +440,17 @@ { "type": "basic", "name": "Div", - "if": "{{!_global.hasModifiedModuleLayouts}}", + "if": "{{_global.modifiedModuleLayoutsCheckFailed}}", + "props": { + "className": "mb-2 p-2 bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-700 rounded text-xs text-red-700 dark:text-red-400", + "role": "alert" + }, + "text": "$t:admin.modules.modals.modified_layouts_check_failed" + }, + { + "type": "basic", + "name": "Div", + "if": "{{!_global.hasModifiedModuleLayouts && !_global.modifiedModuleLayoutsCheckFailed}}", "props": { "className": "mb-2 p-2 bg-green-50 dark:bg-green-900/30 border border-green-200 dark:border-green-700 rounded text-xs text-green-700 dark:text-green-400" }, diff --git a/templates/_bundled/sirsoft-admin_basic/layouts/partials/admin_plugin_list/_modal_update.json b/templates/_bundled/sirsoft-admin_basic/layouts/partials/admin_plugin_list/_modal_update.json index 66fbdbef..733d45ce 100644 --- a/templates/_bundled/sirsoft-admin_basic/layouts/partials/admin_plugin_list/_modal_update.json +++ b/templates/_bundled/sirsoft-admin_basic/layouts/partials/admin_plugin_list/_modal_update.json @@ -440,7 +440,17 @@ { "type": "basic", "name": "Div", - "if": "{{!_global.hasModifiedPluginLayouts}}", + "if": "{{_global.modifiedPluginLayoutsCheckFailed}}", + "props": { + "className": "mb-2 p-2 bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-700 rounded text-xs text-red-700 dark:text-red-400", + "role": "alert" + }, + "text": "$t:admin.plugins.modals.modified_layouts_check_failed" + }, + { + "type": "basic", + "name": "Div", + "if": "{{!_global.hasModifiedPluginLayouts && !_global.modifiedPluginLayoutsCheckFailed}}", "props": { "className": "mb-2 p-2 bg-green-50 dark:bg-green-900/30 border border-green-200 dark:border-green-700 rounded text-xs text-green-700 dark:text-green-400" }, diff --git a/templates/_bundled/sirsoft-admin_basic/layouts/partials/admin_template_list/_modal_update.json b/templates/_bundled/sirsoft-admin_basic/layouts/partials/admin_template_list/_modal_update.json index 29e39690..2a880fb6 100644 --- a/templates/_bundled/sirsoft-admin_basic/layouts/partials/admin_template_list/_modal_update.json +++ b/templates/_bundled/sirsoft-admin_basic/layouts/partials/admin_template_list/_modal_update.json @@ -440,7 +440,17 @@ { "type": "basic", "name": "Div", - "if": "{{!_global.hasModifiedTemplateLayouts}}", + "if": "{{_global.modifiedTemplateLayoutsCheckFailed}}", + "props": { + "className": "mb-2 p-2 bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-700 rounded text-xs text-red-700 dark:text-red-400", + "role": "alert" + }, + "text": "$t:admin.templates.modals.modified_layouts_check_failed" + }, + { + "type": "basic", + "name": "Div", + "if": "{{!_global.hasModifiedTemplateLayouts && !_global.modifiedTemplateLayoutsCheckFailed}}", "props": { "className": "mb-2 p-2 bg-green-50 dark:bg-green-900/30 border border-green-200 dark:border-green-700 rounded text-xs text-green-700 dark:text-green-400" }, diff --git a/templates/_bundled/sirsoft-admin_basic/layouts/partials/admin_template_list/_tab_admin.json b/templates/_bundled/sirsoft-admin_basic/layouts/partials/admin_template_list/_tab_admin.json index d63d6057..cca91ad7 100644 --- a/templates/_bundled/sirsoft-admin_basic/layouts/partials/admin_template_list/_tab_admin.json +++ b/templates/_bundled/sirsoft-admin_basic/layouts/partials/admin_template_list/_tab_admin.json @@ -104,8 +104,8 @@ "pagination": true, "alwaysShowPagination": true, "serverSidePagination": true, - "serverCurrentPage": "{{templates?.data?.current_page ?? 1}}", - "serverTotalPages": "{{templates?.data?.last_page ?? 1}}", + "serverCurrentPage": "{{templates?.data?.pagination?.current_page ?? 1}}", + "serverTotalPages": "{{templates?.data?.pagination?.last_page ?? 1}}", "cardClassName": "border border-gray-200 dark:border-gray-700 rounded-lg p-4 relative", "cardColumns": [ { @@ -122,7 +122,7 @@ "type": "basic", "name": "Div", "props": { - "className": "flex-shrink-0 w-12 h-12 bg-gray-100 dark:bg-gray-700 rounded-lg flex items-center justify-center" + "className": "flex-shrink-0 text-5xl bg-gray-100 dark:bg-gray-700 rounded-lg flex items-center justify-center" }, "children": [ { @@ -272,7 +272,7 @@ "name": "Icon", "props": { "name": "exclamation-triangle", - "className": "w-3 h-3" + "className": "text-xs" } }, { @@ -346,7 +346,7 @@ "if": "{{dep.type === 'module'}}", "props": { "name": "cube", - "className": "w-3.5 h-3.5 text-gray-500 dark:text-gray-400" + "className": "text-sm text-gray-500 dark:text-gray-400" } }, { @@ -355,7 +355,7 @@ "if": "{{dep.type === 'plugin'}}", "props": { "name": "puzzle-piece", - "className": "w-3.5 h-3.5 text-gray-500 dark:text-gray-400" + "className": "text-sm text-gray-500 dark:text-gray-400" } }, { @@ -428,7 +428,7 @@ "name": "Icon", "props": { "name": "code", - "className": "w-4 h-4" + "className": "text-base" } }, { @@ -470,7 +470,7 @@ "name": "Icon", "props": { "name": "edit", - "className": "w-4 h-4" + "className": "text-base" } }, { @@ -520,7 +520,7 @@ "name": "Icon", "props": { "name": "download", - "className": "w-4 h-4" + "className": "text-base" } }, { @@ -554,7 +554,8 @@ "templateLayoutStrategy": "overwrite", "hasModifiedTemplateLayouts": false, "modifiedTemplateLayoutsCount": 0, - "modifiedTemplateLayouts": [] + "modifiedTemplateLayouts": [], + "modifiedTemplateLayoutsCheckFailed": false } }, { @@ -571,7 +572,17 @@ "target": "global", "hasModifiedTemplateLayouts": "{{response.data?.has_modified_layouts ?? false}}", "modifiedTemplateLayoutsCount": "{{response.data?.modified_count ?? 0}}", - "modifiedTemplateLayouts": "{{response.data?.modified_layouts ?? []}}" + "modifiedTemplateLayouts": "{{response.data?.modified_layouts ?? []}}", + "modifiedTemplateLayoutsCheckFailed": false + } + } + ], + "onError": [ + { + "handler": "setState", + "params": { + "target": "global", + "modifiedTemplateLayoutsCheckFailed": true } } ] @@ -627,7 +638,7 @@ "name": "Icon", "props": { "name": "refresh", - "className": "w-4 h-4" + "className": "text-base" } }, { @@ -872,7 +883,7 @@ { "type": "basic", "name": "Span", - "text": "$t:admin.templates.pagination_info|total={{templates?.data?.total ?? 0}}|from={{((templates?.data?.current_page ?? 1) - 1) * (templates?.data?.per_page ?? 12) + 1}}|to={{Math.min((templates?.data?.current_page ?? 1) * (templates?.data?.per_page ?? 12), templates?.data?.total ?? 0)}}" + "text": "$t:admin.templates.pagination_info|total={{templates?.data?.pagination?.total ?? 0}}|from={{((templates?.data?.pagination?.current_page ?? 1) - 1) * (templates?.data?.pagination?.per_page ?? 12) + 1}}|to={{Math.min((templates?.data?.pagination?.current_page ?? 1) * (templates?.data?.pagination?.per_page ?? 12), templates?.data?.pagination?.total ?? 0)}}" } ] } @@ -898,7 +909,7 @@ "name": "Icon", "props": { "name": "info-circle", - "className": "w-5 h-5 text-blue-600 dark:text-blue-400 flex-shrink-0 mt-0.5" + "className": "text-xl text-blue-600 dark:text-blue-400 flex-shrink-0 mt-0.5" } }, { diff --git a/templates/_bundled/sirsoft-admin_basic/layouts/partials/admin_template_list/_tab_user.json b/templates/_bundled/sirsoft-admin_basic/layouts/partials/admin_template_list/_tab_user.json index d578cf3a..ec53c661 100644 --- a/templates/_bundled/sirsoft-admin_basic/layouts/partials/admin_template_list/_tab_user.json +++ b/templates/_bundled/sirsoft-admin_basic/layouts/partials/admin_template_list/_tab_user.json @@ -104,8 +104,8 @@ "pagination": true, "alwaysShowPagination": true, "serverSidePagination": true, - "serverCurrentPage": "{{templates?.data?.current_page ?? 1}}", - "serverTotalPages": "{{templates?.data?.last_page ?? 1}}", + "serverCurrentPage": "{{templates?.data?.pagination?.current_page ?? 1}}", + "serverTotalPages": "{{templates?.data?.pagination?.last_page ?? 1}}", "cardClassName": "border border-gray-200 dark:border-gray-700 rounded-lg p-4 relative", "cardColumns": [ { @@ -122,7 +122,7 @@ "type": "basic", "name": "Div", "props": { - "className": "flex-shrink-0 w-12 h-12 bg-gray-100 dark:bg-gray-700 rounded-lg flex items-center justify-center" + "className": "flex-shrink-0 text-5xl bg-gray-100 dark:bg-gray-700 rounded-lg flex items-center justify-center" }, "children": [ { @@ -272,7 +272,7 @@ "name": "Icon", "props": { "name": "exclamation-triangle", - "className": "w-3 h-3" + "className": "text-xs" } }, { @@ -346,7 +346,7 @@ "if": "{{dep.type === 'module'}}", "props": { "name": "cube", - "className": "w-3.5 h-3.5 text-gray-500 dark:text-gray-400" + "className": "text-sm text-gray-500 dark:text-gray-400" } }, { @@ -355,7 +355,7 @@ "if": "{{dep.type === 'plugin'}}", "props": { "name": "puzzle-piece", - "className": "w-3.5 h-3.5 text-gray-500 dark:text-gray-400" + "className": "text-sm text-gray-500 dark:text-gray-400" } }, { @@ -428,7 +428,7 @@ "name": "Icon", "props": { "name": "code", - "className": "w-4 h-4" + "className": "text-base" } }, { @@ -470,7 +470,7 @@ "name": "Icon", "props": { "name": "edit", - "className": "w-4 h-4" + "className": "text-base" } }, { @@ -520,7 +520,7 @@ "name": "Icon", "props": { "name": "download", - "className": "w-4 h-4" + "className": "text-base" } }, { @@ -583,7 +583,8 @@ "templateLayoutStrategy": "overwrite", "hasModifiedTemplateLayouts": false, "modifiedTemplateLayoutsCount": 0, - "modifiedTemplateLayouts": [] + "modifiedTemplateLayouts": [], + "modifiedTemplateLayoutsCheckFailed": false } }, { @@ -600,7 +601,17 @@ "target": "global", "hasModifiedTemplateLayouts": "{{response.data?.has_modified_layouts ?? false}}", "modifiedTemplateLayoutsCount": "{{response.data?.modified_count ?? 0}}", - "modifiedTemplateLayouts": "{{response.data?.modified_layouts ?? []}}" + "modifiedTemplateLayouts": "{{response.data?.modified_layouts ?? []}}", + "modifiedTemplateLayoutsCheckFailed": false + } + } + ], + "onError": [ + { + "handler": "setState", + "params": { + "target": "global", + "modifiedTemplateLayoutsCheckFailed": true } } ] @@ -656,7 +667,7 @@ "name": "Icon", "props": { "name": "refresh", - "className": "w-4 h-4" + "className": "text-base" } }, { @@ -864,7 +875,7 @@ { "type": "basic", "name": "Span", - "text": "$t:admin.templates.pagination_info|total={{templates?.data?.total ?? 0}}|from={{((templates?.data?.current_page ?? 1) - 1) * (templates?.data?.per_page ?? 12) + 1}}|to={{Math.min((templates?.data?.current_page ?? 1) * (templates?.data?.per_page ?? 12), templates?.data?.total ?? 0)}}" + "text": "$t:admin.templates.pagination_info|total={{templates?.data?.pagination?.total ?? 0}}|from={{((templates?.data?.pagination?.current_page ?? 1) - 1) * (templates?.data?.pagination?.per_page ?? 12) + 1}}|to={{Math.min((templates?.data?.pagination?.current_page ?? 1) * (templates?.data?.pagination?.per_page ?? 12), templates?.data?.pagination?.total ?? 0)}}" } ] } @@ -890,7 +901,7 @@ "name": "Icon", "props": { "name": "info-circle", - "className": "w-5 h-5 text-blue-600 dark:text-blue-400 flex-shrink-0 mt-0.5" + "className": "text-xl text-blue-600 dark:text-blue-400 flex-shrink-0 mt-0.5" } }, { diff --git a/tests/Feature/Api/Admin/CheckModifiedLayoutsContractTest.php b/tests/Feature/Api/Admin/CheckModifiedLayoutsContractTest.php new file mode 100644 index 00000000..132962e6 --- /dev/null +++ b/tests/Feature/Api/Admin/CheckModifiedLayoutsContractTest.php @@ -0,0 +1,213 @@ + ModuleService::class, 'lookup' => 'getModuleInfo', 'segment' => 'modules', 'update' => 'updateModule', 'name' => 'zz-audit-module'], + ['service' => PluginService::class, 'lookup' => 'getPluginInfo', 'segment' => 'plugins', 'update' => 'updatePlugin', 'name' => 'zz-audit-plugin'], + ['service' => TemplateService::class, 'lookup' => 'getTemplateInfo', 'segment' => 'templates', 'update' => 'performVersionUpdate', 'name' => 'zz-audit-template'], + ]; + + protected function setUp(): void + { + parent::setUp(); + + $admin = $this->createAdminUser([ + 'core.modules.read', 'core.modules.install', + 'core.plugins.read', 'core.plugins.install', + 'core.templates.read', 'core.templates.install', + ]); + $this->token = $admin->createToken('test-token')->plainTextToken; + } + + /** + * admin 역할 + 지정 권한을 가진 사용자를 생성합니다. + * + * AdminMiddleware 가 hasRole('admin') 을 확인하므로 admin 역할 부여가 필수입니다. + * + * @param array $permissions 부여할 권한 식별자 목록 + * @return User 생성된 관리자 + */ + private function createAdminUser(array $permissions): User + { + $user = User::factory()->create(); + + $permissionIds = []; + foreach ($permissions as $identifier) { + $permissionIds[] = Permission::firstOrCreate( + ['identifier' => $identifier], + [ + 'name' => ['ko' => $identifier, 'en' => $identifier], + 'description' => ['ko' => $identifier, 'en' => $identifier], + 'extension_type' => ExtensionOwnerType::Core, + 'extension_identifier' => 'core', + 'type' => PermissionType::Admin, + ] + )->id; + } + + $testRole = Role::create([ + 'identifier' => 'admin_test_'.uniqid(), + 'name' => ['ko' => '테스트 관리자', 'en' => 'Test Administrator'], + 'description' => ['ko' => '테스트 관리자', 'en' => 'Test Administrator'], + 'is_active' => true, + ]); + $testRole->permissions()->sync($permissionIds); + + $adminRole = Role::firstOrCreate( + ['identifier' => 'admin'], + [ + 'name' => ['ko' => '관리자', 'en' => 'Administrator'], + 'description' => ['ko' => '시스템 관리자', 'en' => 'System Administrator'], + 'extension_type' => ExtensionOwnerType::Core, + 'extension_identifier' => 'core', + 'is_active' => true, + ] + ); + + foreach ([$adminRole->id, $testRole->id] as $roleId) { + $user->roles()->attach($roleId, ['assigned_at' => now(), 'assigned_by' => null]); + } + + return $user->fresh(); + } + + /** + * 인증 헤더가 붙은 요청 헬퍼. + */ + private function authRequest(): static + { + return $this->withHeaders([ + 'Authorization' => 'Bearer '.$this->token, + 'Accept' => 'application/json', + ]); + } + + /** + * 미존재 식별자는 200 "수정 없음" 이 아니라 404 여야 한다 (D4). + */ + public function test_check_modified_layouts_returns_404_for_missing_identifier(): void + { + foreach (self::EXTENSIONS as $ext) { + $this->mock($ext['service'], function ($mock) use ($ext) { + $mock->shouldReceive($ext['lookup'])->andReturn(null); + $mock->shouldNotReceive('checkModifiedLayouts'); + }); + + $response = $this->authRequest() + ->getJson("/api/admin/{$ext['segment']}/{$ext['name']}/check-modified-layouts"); + + $response->assertStatus(404); + $this->assertFalse( + $response->json('success'), + "{$ext['segment']}: 미존재 식별자가 성공 응답으로 통과했습니다." + ); + $this->assertStringNotContainsString( + 'modified', + (string) $response->json('message'), + "{$ext['segment']}: 미존재인데 수정 감지 결과 메시지가 반환되었습니다." + ); + } + } + + /** + * 존재하는 식별자는 종전대로 200 + 감지 결과를 반환한다 (비회귀). + */ + public function test_check_modified_layouts_returns_200_for_existing_identifier(): void + { + foreach (self::EXTENSIONS as $ext) { + $this->mock($ext['service'], function ($mock) use ($ext) { + $mock->shouldReceive($ext['lookup'])->andReturn(['identifier' => $ext['name']]); + $mock->shouldReceive('checkModifiedLayouts')->andReturn([ + 'has_modified_layouts' => true, + 'modified_count' => 2, + 'modified_layouts' => [ + ['name' => 'a', 'size_diff' => 10], + ['name' => 'b', 'size_diff' => -4], + ], + ]); + }); + + $response = $this->authRequest() + ->getJson("/api/admin/{$ext['segment']}/{$ext['name']}/check-modified-layouts"); + + $response->assertStatus(200); + $this->assertSame(2, $response->json('data.modified_count'), $ext['segment']); + } + } + + /** + * 업데이트 성공 메시지에 식별자·버전이 실제로 채워져야 한다 (D7). + */ + public function test_update_success_message_has_substituted_placeholders(): void + { + foreach (self::EXTENSIONS as $ext) { + $this->mock($ext['service'], function ($mock) use ($ext) { + // module_info/plugin_info/template_info 를 비워 success() 경로를 통과시킨다. + $mock->shouldReceive($ext['update'])->andReturn([ + 'success' => true, + 'from_version' => '1.0.0', + 'to_version' => '1.2.3', + ]); + }); + + $response = $this->authRequest() + ->postJson("/api/admin/{$ext['segment']}/{$ext['name']}/update", [ + 'layout_strategy' => 'keep', + ]); + + $response->assertStatus(200); + $message = (string) $response->json('message'); + + $this->assertStringContainsString($ext['name'], $message, "{$ext['segment']}: 식별자가 메시지에 치환되지 않았습니다."); + $this->assertStringContainsString('1.2.3', $message, "{$ext['segment']}: 버전이 메시지에 치환되지 않았습니다."); + $this->assertDoesNotMatchRegularExpression( + '/:(module|plugin|template|version)\b/', + $message, + "{$ext['segment']}: 치환되지 않은 플레이스홀더가 사용자에게 노출됩니다 — {$message}" + ); + } + } + + /** + * 인증 없이 호출하면 401 (라우트 가드 비회귀). + */ + public function test_check_modified_layouts_requires_authentication(): void + { + foreach (self::EXTENSIONS as $ext) { + $this->getJson("/api/admin/{$ext['segment']}/{$ext['name']}/check-modified-layouts") + ->assertStatus(401); + } + } +} diff --git a/tests/Feature/Console/ConvertJsonUnicodeEscapesTest.php b/tests/Feature/Console/ConvertJsonUnicodeEscapesTest.php new file mode 100644 index 00000000..a1938452 --- /dev/null +++ b/tests/Feature/Console/ConvertJsonUnicodeEscapesTest.php @@ -0,0 +1,115 @@ + json_encode(['ko' => '게시판 '.$i, 'en' => 'Board '.$i]), + 'slug' => 'chunkskip-'.$i, + 'created_at' => now(), + 'updated_at' => now(), + ]; + } + + foreach (array_chunk($rows, 100) as $batch) { + DB::table('boards')->insert($batch); + } + } + + /** + * `\uXXXX` 이스케이프가 남아 있는 boards 건수를 반환합니다. + * + * @return int 잔여 건수 + */ + private function remainingEscapedCount(): int + { + return DB::table('boards')->where('name', 'LIKE', '%\\\\u%')->count(); + } + + public function test_conversion_leaves_no_escaped_rows_when_filter_column_is_mutated_during_iteration(): void + { + $this->seedEscapedBoards(); + + $this->assertSame( + self::SEED_COUNT, + $this->remainingEscapedCount(), + '시드 직후에는 \\uXXXX 이스케이프 행이 시드 건수만큼 존재해야 합니다.' + ); + + $this->artisan('json:convert-unicode', ['--table' => 'boards', '--chunk' => 100]) + ->assertExitCode(0); + + $this->assertSame( + 0, + $this->remainingEscapedCount(), + 'OFFSET 순회로 인해 변환되지 않고 남은 행이 있습니다 (chunk → chunkById 필요).' + ); + } + + public function test_converted_values_preserve_original_payload(): void + { + $this->seedEscapedBoards(); + + $this->artisan('json:convert-unicode', ['--table' => 'boards', '--chunk' => 100]) + ->assertExitCode(0); + + $rows = DB::table('boards')->orderBy('id')->get(['slug', 'name']); + + foreach ($rows as $row) { + $index = (int) str_replace('chunkskip-', '', $row->slug); + + $this->assertSame( + ['ko' => '게시판 '.$index, 'en' => 'Board '.$index], + json_decode($row->name, true), + '변환 후에도 원본 값이 그대로 보존되어야 합니다.' + ); + } + } + + public function test_dry_run_does_not_modify_rows(): void + { + $this->seedEscapedBoards(); + + $this->artisan('json:convert-unicode', ['--table' => 'boards', '--chunk' => 100, '--dry-run' => true]) + ->assertExitCode(0); + + $this->assertSame( + self::SEED_COUNT, + $this->remainingEscapedCount(), + 'dry-run 은 실제 데이터를 변경하지 않아야 합니다.' + ); + } +} diff --git a/tests/Feature/Console/PlaywrightIssueTokenTest.php b/tests/Feature/Console/PlaywrightIssueTokenTest.php new file mode 100644 index 00000000..84a70e89 --- /dev/null +++ b/tests/Feature/Console/PlaywrightIssueTokenTest.php @@ -0,0 +1,256 @@ + $identifier, + 'name' => ['ko' => '시드 역할', 'en' => 'Seeded Role'], + 'description' => ['ko' => '테스트용', 'en' => 'For testing'], + 'is_active' => true, + ]); + + if ($createdAt) { + Role::where('id', $role->id)->update(['created_at' => $createdAt]); + } + + for ($i = 0; $i < $userCount; $i++) { + $user = User::factory()->create(); + $user->roles()->attach($role->id, ['assigned_at' => now(), 'assigned_by' => null]); + } + + return $role; + } + + // ======================================================================== + // D10 — array 캐스팅 컬럼 이중 인코딩 + // ======================================================================== + + /** + * 커맨드가 만든 역할/권한의 name·description 이 이중 인코딩되지 않아야 한다. + */ + public function test_created_role_and_permission_are_not_double_encoded(): void + { + $this->artisan('playwright:issue-token', [ + '--permissions' => ['core.audit.doubleencode'], + '--gc-hours' => 0, + ])->assertSuccessful(); + + $permission = Permission::where('identifier', 'core.audit.doubleencode')->firstOrFail(); + $role = Role::where('identifier', 'like', self::TEST_ROLE_PREFIX.'%')->firstOrFail(); + + foreach ([ + ['permissions', $permission->id, $permission], + ['roles', $role->id, $role], + ] as [$table, $id, $model]) { + foreach (['name', 'description'] as $column) { + // 모델 캐스팅을 거친 값은 배열이어야 한다 + $this->assertIsArray( + $model->{$column}, + "{$table}.{$column} 이 배열로 캐스팅되지 않았습니다 (이중 인코딩 의심)." + ); + $this->assertArrayHasKey('ko', $model->{$column}); + + // 원시 저장값을 1회 디코딩하면 배열이어야 한다. + // 이중 인코딩이면 1회 디코딩 결과가 문자열(JSON) 이 된다. + $raw = DB::table($table)->where('id', $id)->value($column); + $decoded = json_decode((string) $raw, true); + + $this->assertIsArray( + $decoded, + "{$table}.{$column} 원시값이 이중 인코딩되었습니다 — 화면에 JSON 원문이 노출됩니다: {$raw}" + ); + $this->assertArrayHasKey('ko', $decoded); + } + } + } + + /** + * 저장된 한글 값이 화면에서 그대로 읽히는지 (유니코드 이스케이프 원문 미노출). + */ + public function test_created_role_name_reads_back_as_plain_text(): void + { + $this->artisan('playwright:issue-token', ['--gc-hours' => 0])->assertSuccessful(); + + $role = Role::where('identifier', 'like', self::TEST_ROLE_PREFIX.'%')->firstOrFail(); + + $this->assertSame('Playwright 테스트 관리자', $role->name['ko']); + $this->assertStringNotContainsString('\\u', json_encode($role->name, JSON_UNESCAPED_UNICODE)); + } + + // ======================================================================== + // D11 — 오래된 테스트 아티팩트 정리 (--gc-hours) + // ======================================================================== + + /** + * 청크 크기를 넘는 규모에서도 오래된 테스트 역할/유저가 하나도 남지 않아야 한다. + * + * 250건 시드 → OFFSET 기반 순회면 100건이 남는다(키셋 순회 필요). + */ + public function test_gc_removes_all_stale_artifacts_beyond_chunk_size(): void + { + $stale = now()->subHours(24); + for ($i = 0; $i < self::STALE_COUNT; $i++) { + $this->seedRoleWithUsers(self::TEST_ROLE_PREFIX.'stale'.$i, $stale); + } + + $this->assertSame( + self::STALE_COUNT, + Role::where('identifier', 'like', self::TEST_ROLE_PREFIX.'%')->count(), + '시드 직후에는 정리 대상이 시드 건수만큼 존재해야 합니다.' + ); + $seededUsers = User::count(); + + $this->artisan('playwright:issue-token', ['--gc-hours' => 6])->assertSuccessful(); + + // 커맨드가 방금 만든 역할 1건(발급용) 외에는 남으면 안 된다 + $remaining = Role::where('identifier', 'like', self::TEST_ROLE_PREFIX.'%') + ->where('created_at', '<', now()->subHours(6)) + ->count(); + + $this->assertSame( + 0, + $remaining, + 'OFFSET 순회로 인해 정리되지 않고 남은 테스트 역할이 있습니다 (chunk → chunkById 필요).' + ); + + // 유저도 함께 회수되어야 한다 (시드 유저 250명 제거 + 커맨드가 만든 1명 추가) + $this->assertSame( + $seededUsers - self::STALE_COUNT + 1, + User::count(), + '오래된 테스트 유저가 회수되지 않았습니다.' + ); + } + + /** + * 임계 시간 이내의 아티팩트는 건드리면 안 된다 (동시 실행 중인 다른 워커 보호). + */ + public function test_gc_preserves_recent_artifacts(): void + { + $recent = $this->seedRoleWithUsers(self::TEST_ROLE_PREFIX.'recent', now()->subHour()); + + $this->artisan('playwright:issue-token', ['--gc-hours' => 6])->assertSuccessful(); + + $this->assertDatabaseHas('roles', ['id' => $recent->id]); + $this->assertSame(1, $recent->users()->count(), '동시 실행 중인 워커의 계정이 삭제되었습니다.'); + } + + /** + * playwright 테스트 역할이 아닌 역할과 그 소속 회원은 절대 삭제되지 않아야 한다. + */ + public function test_gc_never_touches_real_roles_and_members(): void + { + $realRole = $this->seedRoleWithUsers('shop_manager', now()->subYear()); + $realUserId = $realRole->users()->first()->id; + + $this->artisan('playwright:issue-token', ['--gc-hours' => 6])->assertSuccessful(); + + $this->assertDatabaseHas('roles', ['id' => $realRole->id]); + $this->assertDatabaseHas('users', ['id' => $realUserId]); + } + + /** + * 오래된 역할을 지우더라도, 아직 유효한 다른 테스트 역할을 가진 계정은 남겨야 한다. + * + * 병렬 워커가 같은 계정을 쓰는 상황에서 세션이 끊기는 것을 막는 분기다. + */ + public function test_gc_keeps_user_that_still_holds_a_recent_test_role(): void + { + $staleRole = Role::create([ + 'identifier' => self::TEST_ROLE_PREFIX.'stale_shared', + 'name' => ['ko' => '오래된 역할', 'en' => 'Stale Role'], + 'description' => ['ko' => '테스트용', 'en' => 'For testing'], + 'is_active' => true, + ]); + Role::where('id', $staleRole->id)->update(['created_at' => now()->subHours(24)]); + + $recentRole = Role::create([ + 'identifier' => self::TEST_ROLE_PREFIX.'recent_shared', + 'name' => ['ko' => '최근 역할', 'en' => 'Recent Role'], + 'description' => ['ko' => '테스트용', 'en' => 'For testing'], + 'is_active' => true, + ]); + + $user = User::factory()->create(); + $user->roles()->attach($staleRole->id, ['assigned_at' => now(), 'assigned_by' => null]); + $user->roles()->attach($recentRole->id, ['assigned_at' => now(), 'assigned_by' => null]); + + $this->artisan('playwright:issue-token', ['--gc-hours' => 6])->assertSuccessful(); + + $this->assertDatabaseMissing('roles', ['id' => $staleRole->id]); + $this->assertDatabaseHas('roles', ['id' => $recentRole->id]); + $this->assertDatabaseHas('users', ['id' => $user->id]); + } + + /** + * `--gc-hours=0` 이면 정리를 수행하지 않는다 (옵트아웃). + */ + public function test_gc_is_skipped_when_disabled(): void + { + $stale = $this->seedRoleWithUsers(self::TEST_ROLE_PREFIX.'stale_disabled', now()->subHours(24)); + + $this->artisan('playwright:issue-token', ['--gc-hours' => 0])->assertSuccessful(); + + $this->assertDatabaseHas('roles', ['id' => $stale->id]); + } +} diff --git a/tests/Feature/Extension/UpdateLayoutStrategyKeepTest.php b/tests/Feature/Extension/UpdateLayoutStrategyKeepTest.php new file mode 100644 index 00000000..7c8dda9c --- /dev/null +++ b/tests/Feature/Extension/UpdateLayoutStrategyKeepTest.php @@ -0,0 +1,259 @@ +moduleManager = app(ModuleManager::class); + + $this->adminTemplate = Template::create([ + 'identifier' => 'test-keep-admin', + 'vendor' => 'test', + 'name' => ['ko' => '보존 테스트 관리자', 'en' => 'Keep Test Admin'], + 'version' => '1.0.0', + 'type' => 'admin', + 'status' => ExtensionStatus::Active->value, + 'description' => ['ko' => '테스트용', 'en' => 'For testing'], + ]); + + Module::create([ + 'identifier' => self::MODULE, + 'vendor' => 'sirsoft', + 'name' => ['ko' => '게시판', 'en' => 'Board'], + 'version' => '1.0.3', + 'status' => ExtensionStatus::Active->value, + 'description' => ['ko' => '테스트용', 'en' => 'For testing'], + ]); + + $this->moduleManager->loadModules(); + + if (! $this->moduleManager->getModule(self::MODULE)) { + $this->markTestSkipped(self::MODULE.' 설치본이 없어 레이아웃 보존 동작을 실행할 수 없습니다.'); + } + } + + /** + * 배포 상태(파일 기준)로 레이아웃을 DB 에 등록합니다. + * + * `registerModuleLayouts()` 는 protected 이므로 리플렉션으로 호출합니다. + * 이 메서드가 곧 D6 의 원인이 된 "전략 미인지 선덮어쓰기" 단계입니다. + * + * @return int 등록된 레이아웃 수 + */ + private function registerFromFiles(): int + { + $method = new ReflectionMethod(ModuleManager::class, 'registerModuleLayouts'); + $method->setAccessible(true); + + return (int) $method->invoke($this->moduleManager, self::MODULE); + } + + /** + * 사용자가 UI 에서 레이아웃 1건을 수정한 상태를 만듭니다. + * + * content 만 바꾸고 original_content_hash 는 배포 원본 그대로 두어야 + * "수정됨" 으로 판정됩니다. + * + * @return TemplateLayout 수정된 레이아웃 + */ + private function markOneLayoutAsUserModified(): TemplateLayout + { + $layout = TemplateLayout::where('source_type', 'module') + ->where('source_identifier', self::MODULE) + ->orderBy('id') + ->firstOrFail(); + + $content = $layout->content; + $content['__user_marker'] = 'keep-me'; + $layout->content = $content; + $layout->saveQuietly(); + + return $layout->fresh(); + } + + // ======================================================================== + // keep / overwrite 동작 + // ======================================================================== + + /** + * keep 전략은 사용자 수정 레이아웃을 덮어쓰지 않는다. + */ + public function test_keep_strategy_preserves_user_modified_layout(): void + { + $this->assertGreaterThan(0, $this->registerFromFiles(), '레이아웃이 등록되지 않았습니다.'); + $modified = $this->markOneLayoutAsUserModified(); + + $this->moduleManager->refreshModuleLayouts(self::MODULE, true); + + $this->assertArrayHasKey( + '__user_marker', + $modified->fresh()->content, + 'keep 전략인데 사용자 수정본이 파일 내용으로 덮어써졌습니다.' + ); + } + + /** + * overwrite 전략은 사용자 수정 레이아웃을 파일 내용으로 되돌린다 (비회귀). + */ + public function test_overwrite_strategy_replaces_user_modified_layout(): void + { + $this->registerFromFiles(); + $modified = $this->markOneLayoutAsUserModified(); + + $this->moduleManager->refreshModuleLayouts(self::MODULE, false); + + $this->assertArrayNotHasKey( + '__user_marker', + $modified->fresh()->content, + 'overwrite 전략인데 수정본이 그대로 남았습니다.' + ); + } + + // ======================================================================== + // 선행 register 금지 (D6 의 인과) + // ======================================================================== + + /** + * 전략 인지 refresh **앞에서** register 를 호출하면 keep 이 무효가 된다. + * + * 이 테스트는 결함 재현을 고정한다 — 여기서 보존이 되어버리면 오히려 전제가 바뀐 + * 것이므로, updateModule 의 호출 계약(아래)과 함께 읽어야 한다. + */ + public function test_pre_registering_before_refresh_destroys_the_modification_marker(): void + { + $this->registerFromFiles(); + $modified = $this->markOneLayoutAsUserModified(); + + // 결함 당시 updateModule 이 하던 순서를 그대로 재현 + $this->registerFromFiles(); + $this->moduleManager->refreshModuleLayouts(self::MODULE, true); + + $this->assertArrayNotHasKey( + '__user_marker', + $modified->fresh()->content, + '선행 register 가 수정 마커를 파괴하지 않는다면 이 회귀의 전제가 달라진 것입니다 — 계약을 재검토하세요.' + ); + } + + /** + * register 를 빼도 DB 에 없는 레이아웃은 refresh 가 생성한다. + */ + public function test_refresh_creates_layouts_missing_from_database(): void + { + $registered = $this->registerFromFiles(); + + TemplateLayout::where('source_type', 'module') + ->where('source_identifier', self::MODULE) + ->forceDelete(); + + $this->assertSame(0, $this->countModuleLayouts()); + + $this->moduleManager->refreshModuleLayouts(self::MODULE, true); + + $this->assertSame( + $registered, + $this->countModuleLayouts(), + 'registerModuleLayouts 제거 후 신규 레이아웃이 누락되었습니다 (refresh 의 created 분기 확인 필요).' + ); + } + + /** + * 현재 템플릿에 등록된 모듈 레이아웃 수. + */ + private function countModuleLayouts(): int + { + return TemplateLayout::where('template_id', $this->adminTemplate->id) + ->where('source_type', 'module') + ->where('source_identifier', self::MODULE) + ->count(); + } + + // ======================================================================== + // 호출 계약 — 전체 업데이트 경로는 실행 불가하므로 순서만 고정 + // ======================================================================== + + /** + * updateModule / updatePlugin 의 레이아웃 단계에 전략 미인지 선덮어쓰기가 없어야 한다. + */ + public function test_update_path_does_not_pre_register_layouts(): void + { + foreach ([ + [ModuleManager::class, 'updateModule', 'refreshModuleLayouts', 'registerModuleLayouts'], + [PluginManager::class, 'updatePlugin', 'refreshPluginLayouts', 'registerPluginLayouts'], + ] as [$class, $method, $refresh, $register]) { + $source = $this->methodSource($class, $method); + + $this->assertMatchesRegularExpression( + '/'.preg_quote($refresh, '/').'\(\s*\$identifier\s*,\s*\$preserveModified\s*\)/', + $source, + "{$class}::{$method} 는 전략 인지 {$refresh} 를 호출해야 한다" + ); + $this->assertDoesNotMatchRegularExpression( + '/\$this->'.preg_quote($register, '/').'\(\s*\$identifier\s*\)/', + $source, + "{$class}::{$method} 가 {$register} 를 호출하면 keep 전략이 무효화된다 " + .'(content/original_content_hash 를 파일 기준으로 선덮어쓰기)' + ); + } + } + + /** + * 지정 메서드의 소스 본문을 반환합니다. + * + * @param string $class 대상 클래스 FQCN + * @param string $method 대상 메서드명 + * @return string 메서드 본문 소스 + */ + private function methodSource(string $class, string $method): string + { + $ref = new ReflectionMethod($class, $method); + $lines = file($ref->getFileName()); + + return implode('', array_slice( + $lines, + $ref->getStartLine() - 1, + $ref->getEndLine() - $ref->getStartLine() + 1 + )); + } +} diff --git a/tests/Feature/Upgrades/Alpha15UuidBackfillTest.php b/tests/Feature/Upgrades/Alpha15UuidBackfillTest.php new file mode 100644 index 00000000..c23254d0 --- /dev/null +++ b/tests/Feature/Upgrades/Alpha15UuidBackfillTest.php @@ -0,0 +1,153 @@ +upgrade = new $class; + $this->context = new UpgradeContext( + fromVersion: '7.0.0-alpha.14', + toVersion: '7.0.0-alpha.15', + currentStep: '7.0.0-alpha.15', + ); + } + + /** + * 스텝의 ALTER TABLE 은 MySQL 에서 암묵적 커밋을 유발하므로 RefreshDatabase 의 + * 트랜잭션 롤백으로 되돌아가지 않는다. 시드 행과 컬럼 제약을 명시적으로 원복한다. + */ + protected function tearDown(): void + { + try { + DB::table('users')->where('email', 'LIKE', self::EMAIL_PREFIX.'%')->delete(); + + if ($this->uuidColumnIsNotNull()) { + Schema::table('users', function ($table) { + $table->uuid('uuid')->nullable()->change(); + }); + } + } catch (\Throwable) { + // 정리 실패는 테스트 결과에 영향을 주지 않도록 무시 (RefreshDatabase 가 다음 실행에서 재생성) + } + + parent::tearDown(); + } + + /** + * uuid 컬럼이 NOT NULL 인지 확인합니다. + * + * @return bool NOT NULL 이면 true + */ + private function uuidColumnIsNotNull(): bool + { + $column = DB::selectOne("SHOW COLUMNS FROM {$this->context->table('users')} WHERE Field = 'uuid'"); + + return $column !== null && $column->Null === 'NO'; + } + + /** + * uuid 가 NULL 인 사용자 레코드를 시드합니다. + * + * @return void + */ + private function seedUsersWithoutUuid(): void + { + $rows = []; + + for ($i = 0; $i < self::SEED_COUNT; $i++) { + $rows[] = [ + 'uuid' => null, + 'name' => 'chunk skip user '.$i, + 'email' => self::EMAIL_PREFIX.$i.'@g7.test', + 'password' => bcrypt('password'), + 'created_at' => now(), + 'updated_at' => now(), + ]; + } + + foreach (array_chunk($rows, 100) as $batch) { + DB::table('users')->insert($batch); + } + } + + public function test_uuid_backfill_leaves_no_null_rows_when_filter_column_is_mutated_during_iteration(): void + { + $this->seedUsersWithoutUuid(); + + $this->assertSame( + self::SEED_COUNT, + DB::table('users')->whereNull('uuid')->count(), + '시드 직후에는 uuid NULL 레코드가 시드 건수만큼 존재해야 합니다.' + ); + + $this->upgrade->run($this->context); + + $this->assertSame( + 0, + DB::table('users')->whereNull('uuid')->count(), + 'OFFSET 순회로 인해 백필되지 않고 남은 레코드가 있습니다 (chunk → chunkById 필요).' + ); + + // 백필이 끝나야 컬럼을 NOT NULL 로 조일 수 있다 — 한 건이라도 남으면 + // 스텝의 ALTER TABLE 이 실패하거나 제약이 적용되지 않은 채 넘어간다. + $this->assertTrue( + $this->uuidColumnIsNotNull(), + '백필 후 uuid 컬럼이 NOT NULL 로 전환되지 않았습니다.' + ); + } + + public function test_backfilled_uuids_are_unique(): void + { + $this->seedUsersWithoutUuid(); + + $this->upgrade->run($this->context); + + $uuids = DB::table('users') + ->where('email', 'LIKE', self::EMAIL_PREFIX.'%') + ->pluck('uuid') + ->all(); + + $this->assertCount(self::SEED_COUNT, $uuids); + $this->assertCount(self::SEED_COUNT, array_unique($uuids), '백필된 UUID 는 모두 고유해야 합니다.'); + } +} diff --git a/tests/Feature/Upgrades/Beta2LayoutHashBackfillTest.php b/tests/Feature/Upgrades/Beta2LayoutHashBackfillTest.php new file mode 100644 index 00000000..11097b8a --- /dev/null +++ b/tests/Feature/Upgrades/Beta2LayoutHashBackfillTest.php @@ -0,0 +1,185 @@ +upgrade = new $class; + $this->context = new UpgradeContext( + fromVersion: '7.0.0-beta.1', + toVersion: '7.0.0-beta.2', + currentStep: '7.0.0-beta.2', + ); + } + + /** + * 백필 private 메서드만 호출합니다. + * + * (전체 run() 은 알림 시스템 이관 등 무관한 단계를 함께 실행하므로 검증 대상인 + * 백필 로직만 reflection 으로 직접 실행합니다 — 기존 업그레이드 테스트와 동일 방식) + * + * @return void + */ + private function runBackfill(): void + { + $reflection = new ReflectionClass($this->upgrade); + $method = $reflection->getMethod('backfillModuleAndPluginLayoutHashes'); + $method->setAccessible(true); + $method->invoke($this->upgrade, $this->context); + } + + /** + * 테스트용 템플릿 1건을 생성합니다. + * + * @return int 생성된 템플릿 ID + */ + private function seedTemplate(): int + { + return DB::table('templates')->insertGetId([ + 'identifier' => 'test-chunkskip_template', + 'vendor' => 'test', + 'name' => json_encode(['ko' => '청크 테스트 템플릿', 'en' => 'Chunk Test Template']), + 'version' => '1.0.0', + 'type' => 'admin', + 'status' => 'active', + 'created_at' => now(), + 'updated_at' => now(), + ]); + } + + /** + * hash 가 NULL 인 모듈/플러그인 레이아웃을 시드합니다. + * + * @param int $templateId 템플릿 ID + * @return void + */ + private function seedLayoutsWithoutHash(int $templateId): void + { + $rows = []; + + for ($i = 0; $i < self::SEED_COUNT; $i++) { + $sourceType = $i % 2 === 0 ? 'module' : 'plugin'; + + $rows[] = [ + 'template_id' => $templateId, + 'name' => 'chunkskip/layout_'.$i, + 'content' => json_encode(['type' => 'page', 'index' => $i]), + 'source_type' => $sourceType, + 'source_identifier' => $sourceType === 'module' ? 'test-module' : 'test-plugin', + 'original_content_hash' => null, + 'original_content_size' => null, + 'created_at' => now(), + 'updated_at' => now(), + ]; + } + + foreach (array_chunk($rows, 100) as $batch) { + DB::table('template_layouts')->insert($batch); + } + } + + public function test_layout_hash_backfill_leaves_no_null_rows_when_filter_column_is_mutated_during_iteration(): void + { + $templateId = $this->seedTemplate(); + $this->seedLayoutsWithoutHash($templateId); + + $this->assertSame( + self::SEED_COUNT, + DB::table('template_layouts')->whereNull('original_content_hash')->count(), + '시드 직후에는 hash NULL 레이아웃이 시드 건수만큼 존재해야 합니다.' + ); + + $this->runBackfill(); + + $this->assertSame( + 0, + DB::table('template_layouts') + ->whereIn('source_type', ['module', 'plugin']) + ->whereNull('original_content_hash') + ->count(), + 'OFFSET 순회로 인해 백필되지 않고 남은 레이아웃이 있습니다 (chunk → chunkById 필요).' + ); + } + + public function test_backfilled_hash_and_size_match_normalized_content(): void + { + $templateId = $this->seedTemplate(); + $this->seedLayoutsWithoutHash($templateId); + + $this->runBackfill(); + + $rows = DB::table('template_layouts') + ->where('template_id', $templateId) + ->get(['content', 'original_content_hash', 'original_content_size']); + + foreach ($rows as $row) { + $normalized = json_encode( + json_decode($row->content, true), + JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES + ); + + $this->assertSame(hash('sha256', $normalized), $row->original_content_hash); + $this->assertSame(strlen($normalized), (int) $row->original_content_size); + } + } + + public function test_template_source_layouts_are_not_touched(): void + { + $templateId = $this->seedTemplate(); + $this->seedLayoutsWithoutHash($templateId); + + DB::table('template_layouts')->insert([ + 'template_id' => $templateId, + 'name' => 'chunkskip/template_owned', + 'content' => json_encode(['type' => 'page']), + 'source_type' => 'template', + 'original_content_hash' => null, + 'created_at' => now(), + 'updated_at' => now(), + ]); + + $this->runBackfill(); + + $row = DB::table('template_layouts') + ->where('template_id', $templateId) + ->where('source_type', 'template') + ->first(['original_content_hash']); + + $this->assertNull($row->original_content_hash, '템플릿 소유 레이아웃은 백필 대상이 아닙니다.'); + } +} diff --git a/tests/Playwright/specs/admin/extension-update-modal-contract.spec.ts b/tests/Playwright/specs/admin/extension-update-modal-contract.spec.ts new file mode 100644 index 00000000..fe983a2c --- /dev/null +++ b/tests/Playwright/specs/admin/extension-update-modal-contract.spec.ts @@ -0,0 +1,227 @@ +/** + * 확장(모듈/플러그인/템플릿) 관리 화면의 업데이트 계약 회귀 검증 + * + * Chrome MCP 정밀 점검(2026-07-31)에서 실측된 결함을 브라우저 경로로 고정한다. + * + * - 목록 요약이 `data.total` 을 읽어 항상 "총 0개 중 1-0개 표시" 로 고정 표기됐다. + * 실제 응답은 `data.pagination.total` 이다. + * - `check-updates` 응답 필드는 `updated_count` 인데 레이아웃이 `update_count` 를 + * 읽어, 업데이트가 감지돼도 항상 "모두 최신 상태입니다" 토스트가 떴다. + * - 업데이트 모달의 수정 감지 조회가 실패해도 "수정된 레이아웃이 없습니다" 라고 + * 단언해, 그대로 '모두 교체' 를 진행하면 사용자가 고친 화면이 소실됐다. + * + * @scenario extension-update-modal + * @effects pagination-summary, check-updates-toast, modified-layouts-warning + */ +import { test, expect, issueToken, authenticatePage } from '../../fixtures/auth'; +import type { Locator, Page } from '@playwright/test'; + +// 이 파일의 테스트는 매번 관리자 SPA 를 냉시동해 목록 화면을 완전히 렌더한 뒤 조작한다. +// 전역 기본 30s 는 워커가 여럿 붙어 서로 PHP-FPM 을 나눠 쓰는 병렬 실행에서 부족하다 +// (실측: 6워커 동시 실행 시 테스트당 22~35s). 회귀 감지는 개별 단언 타임아웃이 맡고, +// 이 값은 하네스 예산일 뿐이므로 파일 단위로 늘린다. +test.describe.configure({ timeout: 60_000 }); + +const LIST_ROUTES: Array<{ path: string; label: string; api: string; permission: string }> = [ + { path: '/admin/modules', label: '모듈', api: '**/api/admin/modules?*', permission: 'core.modules.read' }, + { path: '/admin/plugins', label: '플러그인', api: '**/api/admin/plugins?*', permission: 'core.plugins.read' }, +]; + +/** + * 목록 화면이 함께 부르는 부수 데이터소스를 고정한다. + * + * `admin_module_list` / `admin_plugin_list` 는 목록 외에 `auto_deactivated_banner` + * (`/api/admin/extensions/auto-deactivated`) 도 페이지 데이터소스로 선언한다. 카드 그리드에는 + * `blur_until_loaded: true` 가 걸려 있어 **모든** 데이터소스가 끝나기 전까지 래퍼에 + * `pointer-events-none` 이 붙고(DynamicRenderer), 툴바 버튼은 목록 응답의 abilities 로 + * `disabled` 가 결정된다. 이 요청 하나를 실서버에 남겨두면 병렬 워커 경합에서 응답이 늦어져 + * 클릭이 로딩 가드에 막힌다 — 실측: 6워커에서 카드 버튼 클릭이 `#content_area` 로 흘러 20s 타임아웃. + * 이 spec 이 검증하는 것은 바인딩 계약이지 서버 지연이 아니므로 빈 응답으로 고정한다. + */ +async function stubSupportingSources(page: Page): Promise { + await page.route('**/api/admin/extensions/auto-deactivated*', async (route) => { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ + success: true, + message: 'ok', + data: { + items: { plugins: [], modules: [], templates: [] }, + current_core_version: '7.0.6', + }, + }), + }); + }); +} + +/** + * 카드 그리드 안의 대상이 실제로 클릭 가능해질 때까지 기다린다. + * + * `blur_until_loaded` 래퍼는 로딩 중 `opacity-50 blur-sm … pointer-events-none` 을 달아 + * 카드 안 버튼 클릭을 부모(`#content_area`)로 흘려보낸다. `domcontentloaded` 는 SPA 가 + * 데이터를 받기 전에 끝나므로, 이 대기 없이 카드 버튼을 누르면 클릭이 가로채인다. + * + * 순서가 중요하다 — blur 부재(`toHaveCount(0)`)만 먼저 단언하면 그리드가 **아직 렌더되기 + * 전이라** 즉시 통과하고, 그 뒤에 blur 가 붙어 대기가 무효가 된다. 대상이 보이는 것을 + * 먼저 확인해 그리드 렌더를 확정한 뒤 blur 해제를 기다린다. + */ +async function waitForGridInteractive(page: Page, target: Locator): Promise { + await expect(target).toBeVisible({ timeout: 20_000 }); + await expect(page.locator('#content_area .blur-sm')).toHaveCount(0, { timeout: 20_000 }); +} + +for (const { path, label, api, permission } of LIST_ROUTES) { + test(`${label} 목록의 페이지네이션 요약이 응답의 총건수를 표시한다`, async ({ page }) => { + const token = issueToken(permission); + await authenticatePage(page, token); + await stubSupportingSources(page); + + // 응답을 고정해 "환경에 몇 건 있는지" 가 아니라 바인딩 경로를 검증한다. + // (회귀 시 응답이 무엇이든 화면은 "총 0개 중 1-0개 표시" 로 고정된다) + await page.route(api, async (route) => { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ + success: true, + message: 'ok', + data: { + data: [], + pagination: { total: 37, current_page: 1, last_page: 4, per_page: 12 }, + meta: {}, + abilities: {}, + }, + }), + }); + }); + + await page.goto(path); + await page.waitForLoadState('domcontentloaded', { timeout: 30_000 }); + + const summary = page.locator('#pagination_info'); + await expect(summary).toBeVisible({ timeout: 20_000 }); + // "총 0개 중 1-0개 표시" 는 data.pagination 경로 회귀의 지문이다. + await expect(summary).toContainText('총 37개', { timeout: 20_000 }); + await expect(summary).not.toContainText('총 0개'); + }); +} + +test('업데이트 확인은 감지 건수를 토스트에 반영한다', async ({ page }) => { + const token = issueToken('core.modules.read', 'core.modules.install'); + await authenticatePage(page, token); + await stubSupportingSources(page); + + // 툴바의 '업데이트 확인' 은 `disabled: "{{… modules?.data?.abilities?.can_install !== true}}"` 이라 + // 목록 응답이 도착하기 전까지 비활성이다. 목록도 고정해 버튼 활성 시점을 서버 지연에서 분리한다. + // (route 는 나중에 등록한 것이 먼저 매칭되므로 check-updates 보다 앞서 등록한다 — + // `**/api/admin/modules?*` 의 `?` 는 임의 1문자라 check-updates 경로에도 매칭될 수 있다) + await page.route('**/api/admin/modules?*', async (route) => { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ + success: true, + message: 'ok', + data: { + data: [], + pagination: { total: 0, current_page: 1, last_page: 1, per_page: 12 }, + meta: {}, + abilities: { can_install: true, can_activate: true, can_uninstall: true }, + }, + }), + }); + }); + + // check-updates 응답을 감지 1건으로 고정 — 레이아웃이 updated_count 를 읽는지 검증 + await page.route('**/api/admin/modules/check-updates', async (route) => { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ + success: true, + message: '업데이트 확인이 완료되었습니다.', + data: { + updated_count: 1, + details: [ + { + identifier: 'sirsoft-board', + current_version: '1.0.1', + latest_version: '1.0.2', + update_source: 'bundled', + }, + ], + }, + }), + }); + }); + + await page.goto('/admin/modules'); + await page.waitForLoadState('domcontentloaded', { timeout: 30_000 }); + + const checkButton = page.getByRole('button', { name: /업데이트 확인/ }); + await expect(checkButton).toBeEnabled({ timeout: 20_000 }); + await checkButton.click(); + + const toast = page.getByRole('alert'); + await expect(toast).toContainText(/업데이트 확인 완료/, { timeout: 20_000 }); + await expect(toast).not.toContainText(/최신 상태입니다/); +}); + +test('수정 감지 조회가 실패하면 "수정 없음" 대신 확인 실패를 알린다', async ({ page }) => { + const token = issueToken('core.modules.read', 'core.modules.install'); + await authenticatePage(page, token); + await stubSupportingSources(page); + + // 업데이트 가용 상태를 고정하고, 수정 감지 조회만 실패시킨다 + await page.route('**/api/admin/modules?*', async (route) => { + await route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify({ + success: true, + message: 'ok', + data: { + data: [ + { + identifier: 'sirsoft-board', + vendor: 'sirsoft', + name: '게시판', + description: '검수용 고정 응답', + version: '1.0.1', + status: 'active', + dependencies: [], + update_available: true, + update_source: 'bundled', + latest_version: '1.0.2', + is_compatible: true, + is_pending: false, + is_bundled: true, + abilities: { can_install: true, can_activate: true, can_uninstall: true }, + }, + ], + pagination: { total: 1, current_page: 1, last_page: 1, per_page: 12 }, + meta: {}, + abilities: { can_install: true, can_activate: true, can_uninstall: true }, + }, + }), + }); + }); + await page.route('**/check-modified-layouts', (route) => route.abort('failed')); + await page.route('**/changelog*', (route) => route.abort('failed')); + + await page.goto('/admin/modules'); + await page.waitForLoadState('domcontentloaded', { timeout: 30_000 }); + + // 접근성 이름은 아이콘 글리프를 포함한다 ("refresh 업데이트") — '업데이트 확인' 과 구분한다. + const updateButton = page + .getByRole('button', { name: 'refresh 업데이트', exact: true }) + .first(); + await waitForGridInteractive(page, updateButton); + await updateButton.click({ timeout: 20_000 }); + + const dialog = page.getByRole('dialog'); + await expect(dialog).toBeVisible({ timeout: 20_000 }); + await expect(dialog).toContainText(/확인하지 못했습니다/, { timeout: 20_000 }); + await expect(dialog).not.toContainText(/수정된 레이아웃이 없습니다/); +}); diff --git a/tests/Unit/Extension/TemplateModifiedLayoutScopeTest.php b/tests/Unit/Extension/TemplateModifiedLayoutScopeTest.php new file mode 100644 index 00000000..a070452a --- /dev/null +++ b/tests/Unit/Extension/TemplateModifiedLayoutScopeTest.php @@ -0,0 +1,159 @@ + 'home', 'slots' => ['content' => []]]; + + /** 사용자가 UI 에서 수정한 콘텐츠 */ + private const MODIFIED = ['layout_name' => 'home', 'slots' => ['content' => [['component' => 'Div']]]]; + + protected function setUp(): void + { + parent::setUp(); + + $this->templateManager = app(TemplateManager::class); + + $this->template = Template::create([ + 'identifier' => 'test-scope-admin', + 'vendor' => 'test', + 'name' => ['ko' => '범위 테스트 관리자', 'en' => 'Scope Test Admin'], + 'version' => '1.0.0', + 'type' => 'admin', + 'status' => ExtensionStatus::Active->value, + 'description' => ['ko' => '테스트용', 'en' => 'For testing'], + ]); + } + + /** + * 레이아웃 1건을 시드합니다. + * + * original_content_hash 는 항상 배포 원본 기준으로 기록하고, content 만 수정본으로 + * 바꿔 "사용자가 UI 에서 고친 상태" 를 재현합니다. + * + * @param int $templateId 소속 템플릿 ID + * @param string $name 레이아웃 이름 + * @param string $sourceType 소유 구분 (template/module/plugin) + * @param string|null $sourceIdentifier 소유 확장 식별자 (템플릿 소유는 null) + * @param bool $modified true 면 수정된 상태로 시드 + * @return TemplateLayout 생성된 레이아웃 + */ + private function seedLayout( + int $templateId, + string $name, + string $sourceType, + ?string $sourceIdentifier, + bool $modified + ): TemplateLayout { + return TemplateLayout::create([ + 'template_id' => $templateId, + 'name' => $name, + 'content' => $modified ? self::MODIFIED : self::ORIGINAL, + 'source_type' => $sourceType, + 'source_identifier' => $sourceIdentifier, + 'original_content_hash' => $this->computeContentHash(self::ORIGINAL), + 'original_content_size' => $this->computeContentSize(self::ORIGINAL), + ]); + } + + /** + * 템플릿 소유 수정본만 집계하고 남의 확장 소유는 제외해야 한다. + */ + public function test_has_modified_layouts_counts_only_template_owned_layouts(): void + { + $this->seedLayout($this->template->id, 'admin_home', 'template', null, true); + + // 같은 template_id 에 얹힌 남의 확장 소유 수정본 3건 + $this->seedLayout($this->template->id, 'sirsoft-board.admin_index', 'module', 'sirsoft-board', true); + $this->seedLayout($this->template->id, 'sirsoft-page.admin_index', 'module', 'sirsoft-page', true); + $this->seedLayout($this->template->id, 'sirsoft-gdpr.admin_index', 'plugin', 'sirsoft-gdpr', true); + + $result = $this->templateManager->hasModifiedLayouts('test-scope-admin'); + + $this->assertTrue($result['has_modified_layouts']); + $this->assertSame( + 1, + $result['modified_count'], + '템플릿 업데이트가 실제로 갱신하지 않는 모듈/플러그인 소유 레이아웃이 수정 건수에 합산되었습니다.' + ); + $this->assertSame(['admin_home'], array_column($result['modified_layouts'], 'name')); + } + + /** + * 남의 확장만 수정된 상태에서는 경고가 뜨면 안 된다. + */ + public function test_has_modified_layouts_returns_zero_when_only_other_extensions_are_modified(): void + { + $this->seedLayout($this->template->id, 'admin_home', 'template', null, false); + $this->seedLayout($this->template->id, 'sirsoft-board.admin_index', 'module', 'sirsoft-board', true); + + $result = $this->templateManager->hasModifiedLayouts('test-scope-admin'); + + $this->assertFalse($result['has_modified_layouts']); + $this->assertSame(0, $result['modified_count']); + $this->assertEmpty($result['modified_layouts']); + } + + /** + * 다른 템플릿의 수정본은 집계 대상이 아니다. + */ + public function test_has_modified_layouts_ignores_layouts_of_other_templates(): void + { + $other = Template::create([ + 'identifier' => 'test-scope-user', + 'vendor' => 'test', + 'name' => ['ko' => '범위 테스트 사용자', 'en' => 'Scope Test User'], + 'version' => '1.0.0', + 'type' => 'user', + 'status' => ExtensionStatus::Active->value, + 'description' => ['ko' => '테스트용', 'en' => 'For testing'], + ]); + + $this->seedLayout($other->id, 'user_home', 'template', null, true); + $this->seedLayout($this->template->id, 'admin_home', 'template', null, false); + + $result = $this->templateManager->hasModifiedLayouts('test-scope-admin'); + + $this->assertSame(0, $result['modified_count'], '다른 템플릿의 수정본까지 집계되었습니다.'); + } + + /** + * 미존재 템플릿은 빈 결과를 반환한다. + */ + public function test_has_modified_layouts_returns_empty_for_unknown_template(): void + { + $result = $this->templateManager->hasModifiedLayouts('no-such-template'); + + $this->assertFalse($result['has_modified_layouts']); + $this->assertSame(0, $result['modified_count']); + $this->assertEmpty($result['modified_layouts']); + } +} diff --git a/tests/Unit/Seo/ExpressionEvaluatorRawPrefixTest.php b/tests/Unit/Seo/ExpressionEvaluatorRawPrefixTest.php new file mode 100644 index 00000000..eec7facf --- /dev/null +++ b/tests/Unit/Seo/ExpressionEvaluatorRawPrefixTest.php @@ -0,0 +1,69 @@ +setTranslations(['common' => ['save' => '저장']]); + + return $e; + } + + public function test_raw_prefix_is_stripped_before_evaluation(): void + { + $context = ['file' => ['description' => '', 'name' => 'admin_module_list.json']]; + + $this->assertSame( + 'admin_module_list.json', + $this->evaluator()->evaluate('{{raw:file.description || file.name}}', $context), + 'raw: 접두사를 벗기지 않으면 콜론이 식으로 파싱돼 평가가 실패한다' + ); + } + + public function test_raw_prefix_result_is_translation_exempt(): void + { + $context = ['post' => ['title' => '$t:common.save']]; + + $this->assertSame( + '$t:common.save', + $this->evaluator()->evaluate('{{raw:post.title}}', $context), + 'raw: 결과의 $t: 토큰은 번역하지 않아야 한다 (React rawMarkers 와 동일)' + ); + } + + public function test_non_raw_binding_still_resolves_translation_tokens(): void + { + $context = ['post' => ['title' => '$t:common.save']]; + + $this->assertSame( + '저장', + $this->evaluator()->evaluate('{{post.title}}', $context), + 'raw: 가 없으면 종전대로 번역되어야 한다 (비회귀)' + ); + } + + public function test_evaluate_raw_strips_prefix(): void + { + $context = ['items' => [1, 2, 3]]; + + $this->assertSame( + [1, 2, 3], + $this->evaluator()->evaluateRaw('{{raw:items}}', $context), + 'evaluateRaw 도 접두사를 벗기고 원본 타입을 유지해야 한다' + ); + } +} diff --git a/upgrades/Upgrade_7_0_0_alpha_15.php b/upgrades/Upgrade_7_0_0_alpha_15.php index f8fb4439..5180b34f 100644 --- a/upgrades/Upgrade_7_0_0_alpha_15.php +++ b/upgrades/Upgrade_7_0_0_alpha_15.php @@ -20,7 +20,7 @@ class Upgrade_7_0_0_alpha_15 implements UpgradeStepInterface /** * 업그레이드 스텝을 실행합니다. * - * @param UpgradeContext $context 업그레이드 컨텍스트 + * @param UpgradeContext $context 업그레이드 컨텍스트 * @return void */ public function run(UpgradeContext $context): void @@ -37,7 +37,9 @@ class Upgrade_7_0_0_alpha_15 implements UpgradeStepInterface if ($nullCount > 0) { $context->logger->info("UUID 백필 시작: {$nullCount}건의 기존 레코드"); - DB::table('users')->whereNull('uuid')->orderBy('id')->chunk(100, function ($users) { + // chunkById(키셋 순회) 필수 — 콜백이 필터 컬럼(uuid)을 채우므로 처리된 행이 + // 필터 결과에서 이탈한다. OFFSET 기반 chunk() 는 그만큼 앞으로 밀려 미처리 행을 건너뛴다. + DB::table('users')->whereNull('uuid')->chunkById(100, function ($users) { foreach ($users as $user) { DB::table('users') ->where('id', $user->id) @@ -54,8 +56,11 @@ class Upgrade_7_0_0_alpha_15 implements UpgradeStepInterface $columnType = DB::selectOne("SHOW COLUMNS FROM {$context->table('users')} WHERE Field = 'uuid'"); if ($columnType && $columnType->Null === 'YES') { + // unique 인덱스는 add_uuid_to_users_table 마이그레이션이 이미 생성했다. + // change() 에 ->unique() 를 함께 붙이면 동일 이름의 인덱스를 다시 만들려 해 + // "Duplicate key name" 으로 실패한다 (MODIFY COLUMN 은 기존 인덱스를 보존). Schema::table('users', function ($table) { - $table->uuid('uuid')->nullable(false)->unique()->change(); + $table->uuid('uuid')->nullable(false)->change(); }); $context->logger->info('uuid 컬럼에 NOT NULL 제약을 추가했습니다.'); diff --git a/upgrades/Upgrade_7_0_0_beta_2.php b/upgrades/Upgrade_7_0_0_beta_2.php index 77c13c2a..289aed9b 100644 --- a/upgrades/Upgrade_7_0_0_beta_2.php +++ b/upgrades/Upgrade_7_0_0_beta_2.php @@ -6,7 +6,9 @@ use App\Contracts\Extension\UpgradeStepInterface; use App\Extension\UpgradeContext; use App\Models\NotificationDefinition; use App\Models\NotificationTemplate; +use App\Services\CoreUpdateService; use Database\Seeders\NotificationDefinitionSeeder; +use Illuminate\Database\Query\Builder; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\File; @@ -53,7 +55,7 @@ class Upgrade_7_0_0_beta_2 implements UpgradeStepInterface /** * 업그레이드 스텝을 실행합니다. * - * @param UpgradeContext $context 업그레이드 컨텍스트 + * @param UpgradeContext $context 업그레이드 컨텍스트 * @return void */ public function run(UpgradeContext $context): void @@ -77,7 +79,7 @@ class Upgrade_7_0_0_beta_2 implements UpgradeStepInterface // 2. 코어 알림 정의 시딩 (3종) $context->logger->info('[beta.2] 코어 알림 정의 시딩...'); - (new NotificationDefinitionSeeder())->run(); + (new NotificationDefinitionSeeder)->run(); // 3. mail_templates → notification_templates 데이터 이관 if (Schema::hasTable('mail_templates')) { @@ -151,7 +153,7 @@ class Upgrade_7_0_0_beta_2 implements UpgradeStepInterface * * 멱등: 이미 hash 가 있는 행은 건너뜀. * - * @param UpgradeContext $context 업그레이드 컨텍스트 + * @param UpgradeContext $context 업그레이드 컨텍스트 * @return void */ private function backfillModuleAndPluginLayoutHashes(UpgradeContext $context): void @@ -164,11 +166,13 @@ class Upgrade_7_0_0_beta_2 implements UpgradeStepInterface } $total = 0; + // chunkById(키셋 순회) 필수 — 콜백이 필터 컬럼(original_content_hash)을 채우므로 + // 처리된 행이 필터 결과에서 이탈한다. OFFSET 기반 chunk() 는 그만큼 앞으로 밀려 + // 미처리 행을 건너뛴다. DB::table('template_layouts') ->whereIn('source_type', ['module', 'plugin']) ->whereNull('original_content_hash') - ->orderBy('id') - ->chunk(100, function ($layouts) use (&$total) { + ->chunkById(100, function ($layouts) use (&$total) { foreach ($layouts as $layout) { $content = json_decode($layout->content, true); $normalized = json_encode($content, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); @@ -200,7 +204,7 @@ class Upgrade_7_0_0_beta_2 implements UpgradeStepInterface * * 멱등: 파일/테이블이 없으면 no-op. * - * @param UpgradeContext $context + * @param UpgradeContext $context * @return void */ private function cleanupMailTemplateShim(UpgradeContext $context): void @@ -274,7 +278,7 @@ class Upgrade_7_0_0_beta_2 implements UpgradeStepInterface } config(['core' => $fresh]); - $service = app(\App\Services\CoreUpdateService::class); + $service = app(CoreUpdateService::class); try { $service->syncCoreRolesAndPermissions(); $context->logger->info('[beta.2] fallback: 코어 권한 재동기화 완료'); @@ -305,7 +309,7 @@ class Upgrade_7_0_0_beta_2 implements UpgradeStepInterface * (eval 실행 컨텍스트의 cwd 가 base_path 와 일치한다는 보장 없음). * * @param UpgradeContext $context - * @return bool spawn 성공 여부 (false 면 호출자가 in-process fallback 진행) + * @return bool spawn 성공 여부 (false 면 호출자가 in-process fallback 진행) */ private function spawnResyncInlineLocal(UpgradeContext $context): bool { @@ -488,7 +492,7 @@ PHP; * - TTY 연결 + 감지 결과 있음 → 목록 출력 후 "yes/no [yes]" 프롬프트. 빈 응답=yes. * * @param UpgradeContext $context - * @return bool 사용자가 일괄 업데이트에 동의했으면 true + * @return bool 사용자가 일괄 업데이트에 동의했으면 true */ private function promptBulkBundledUpdateLocal(UpgradeContext $context): bool { @@ -538,7 +542,7 @@ PHP; return false; } - echo " 번들에 포함된 새 버전으로 일괄 업데이트하시겠습니까? (yes/no) [yes]: "; + echo ' 번들에 포함된 새 버전으로 일괄 업데이트하시겠습니까? (yes/no) [yes]: '; $answer = trim((string) fgets(STDIN)); $confirmed = ($answer === '' || strtolower($answer) === 'yes' || strtolower($answer) === 'y'); @@ -627,7 +631,7 @@ PHP; * user_overrides 는 JSON 배열(보통 수정된 필드명 목록). null / 빈 배열 / 빈 객체 / 빈 문자열 * 을 모두 "비어있음" 으로 판정. * - * @param \Illuminate\Database\Query\Builder $query + * @param Builder $query * @param bool $hasOverrides * @return void */ @@ -904,7 +908,7 @@ PHP; * beta.1 메모리의 구 클래스를 우회하기 위해 로컬 구현을 유지한다. * beta.3 에서 본 upgrade step 전체가 제거되며 공용 Helper 만 남는다. * - * @return array{0: int|false, 1: int|false, 2: string} [owner, group, source] + * @return array{0: int|false, 1: int|false, 2: string} [owner, group, source] */ private function inferWebServerOwnershipLocal(): array { @@ -945,9 +949,9 @@ PHP; * 로직은 `FilePermissionHelper::chownRecursive()` 과 동일하나, beta.1 메모리 구 * 클래스 우회를 위해 로컬 구현을 유지한다. * - * @param string $path 대상 경로 - * @param int $owner 기준 소유자 UID - * @param int|false $group 기준 그룹 GID + * @param string $path 대상 경로 + * @param int $owner 기준 소유자 UID + * @param int|false $group 기준 그룹 GID * @return int 변경 건수 */ private function chownRecursiveLocal(string $path, int $owner, int|false $group): int @@ -986,7 +990,7 @@ PHP; * 본 정리 스텝은 이미 buggy 시드가 실행된 dev/staging 환경에서만 영향이 있으며, * 신규 설치에서는 no-op 입니다. * - * @param UpgradeContext $context 업그레이드 컨텍스트 + * @param UpgradeContext $context 업그레이드 컨텍스트 * @return void */ private function cleanupUserNotificationPermissions(UpgradeContext $context): void @@ -1026,7 +1030,7 @@ PHP; * * 기존 사용자 수정 데이터(user_overrides)를 보존합니다. * - * @param UpgradeContext $context + * @param UpgradeContext $context * @return void */ private function migrateMailTemplates(UpgradeContext $context): void @@ -1078,7 +1082,7 @@ PHP; * * 멱등성: 두 번째 실행 시 매칭 0건 (안전). * - * @param UpgradeContext $context + * @param UpgradeContext $context * @return void */ private function migrateActivityLogDescriptionKeys(UpgradeContext $context): void @@ -1108,7 +1112,7 @@ PHP; /** * mail_send_logs → notification_logs 데이터를 이관합니다. * - * @param UpgradeContext $context + * @param UpgradeContext $context * @return void */ private function migrateMailSendLogs(UpgradeContext $context): void @@ -1165,7 +1169,7 @@ PHP; /** * 권한 식별자를 mail-send-logs → notification-logs로 전환합니다. * - * @param UpgradeContext $context + * @param UpgradeContext $context * @return void */ private function migratePermissions(UpgradeContext $context): void @@ -1249,7 +1253,7 @@ PHP; // 1. pre-beta.2 메일 템플릿 캐시 (기존 로직 유지) $mailTypes = ['welcome', 'reset_password', 'password_changed']; foreach ($mailTypes as $type) { - Cache::forget('mail_template:core:' . $type); + Cache::forget('mail_template:core:'.$type); } // 2. 공통 캐시 이관 이전의 레거시 키 제거 (고아 방지)